fix email regix
[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 });        /*
5471  * Based on:
5472  * Ext JS Library 1.1.1
5473  * Copyright(c) 2006-2007, Ext JS, LLC.
5474  *
5475  * Originally Released Under LGPL - original licence link has changed is not relivant.
5476  *
5477  * Fork - LGPL
5478  * <script type="text/javascript">
5479  */
5480 /**
5481  * @class Roo.TabPanel
5482  * @extends Roo.util.Observable
5483  * A lightweight tab container.
5484  * <br><br>
5485  * Usage:
5486  * <pre><code>
5487 // basic tabs 1, built from existing content
5488 var tabs = new Roo.TabPanel("tabs1");
5489 tabs.addTab("script", "View Script");
5490 tabs.addTab("markup", "View Markup");
5491 tabs.activate("script");
5492
5493 // more advanced tabs, built from javascript
5494 var jtabs = new Roo.TabPanel("jtabs");
5495 jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
5496
5497 // set up the UpdateManager
5498 var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
5499 var updater = tab2.getUpdateManager();
5500 updater.setDefaultUrl("ajax1.htm");
5501 tab2.on('activate', updater.refresh, updater, true);
5502
5503 // Use setUrl for Ajax loading
5504 var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
5505 tab3.setUrl("ajax2.htm", null, true);
5506
5507 // Disabled tab
5508 var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
5509 tab4.disable();
5510
5511 jtabs.activate("jtabs-1");
5512  * </code></pre>
5513  * @constructor
5514  * Create a new TabPanel.
5515  * @param {String/HTMLElement/Roo.Element} container The id, DOM element or Roo.Element container where this TabPanel is to be rendered.
5516  * @param {Object/Boolean} config Config object to set any properties for this TabPanel, or true to render the tabs on the bottom.
5517  */
5518 Roo.TabPanel = function(container, config){
5519     /**
5520     * The container element for this TabPanel.
5521     * @type Roo.Element
5522     */
5523     this.el = Roo.get(container, true);
5524     if(config){
5525         if(typeof config == "boolean"){
5526             this.tabPosition = config ? "bottom" : "top";
5527         }else{
5528             Roo.apply(this, config);
5529         }
5530     }
5531     if(this.tabPosition == "bottom"){
5532         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5533         this.el.addClass("x-tabs-bottom");
5534     }
5535     this.stripWrap = Roo.get(this.createStrip(this.el.dom), true);
5536     this.stripEl = Roo.get(this.createStripList(this.stripWrap.dom), true);
5537     this.stripBody = Roo.get(this.stripWrap.dom.firstChild.firstChild, true);
5538     if(Roo.isIE){
5539         Roo.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
5540     }
5541     if(this.tabPosition != "bottom"){
5542         /** The body element that contains {@link Roo.TabPanelItem} bodies. +
5543          * @type Roo.Element
5544          */
5545         this.bodyEl = Roo.get(this.createBody(this.el.dom));
5546         this.el.addClass("x-tabs-top");
5547     }
5548     this.items = [];
5549
5550     this.bodyEl.setStyle("position", "relative");
5551
5552     this.active = null;
5553     this.activateDelegate = this.activate.createDelegate(this);
5554
5555     this.addEvents({
5556         /**
5557          * @event tabchange
5558          * Fires when the active tab changes
5559          * @param {Roo.TabPanel} this
5560          * @param {Roo.TabPanelItem} activePanel The new active tab
5561          */
5562         "tabchange": true,
5563         /**
5564          * @event beforetabchange
5565          * Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
5566          * @param {Roo.TabPanel} this
5567          * @param {Object} e Set cancel to true on this object to cancel the tab change
5568          * @param {Roo.TabPanelItem} tab The tab being changed to
5569          */
5570         "beforetabchange" : true
5571     });
5572
5573     Roo.EventManager.onWindowResize(this.onResize, this);
5574     this.cpad = this.el.getPadding("lr");
5575     this.hiddenCount = 0;
5576
5577
5578     // toolbar on the tabbar support...
5579     if (this.toolbar) {
5580         var tcfg = this.toolbar;
5581         tcfg.container = this.stripEl.child('td.x-tab-strip-toolbar');  
5582         this.toolbar = new Roo.Toolbar(tcfg);
5583         if (Roo.isSafari) {
5584             var tbl = tcfg.container.child('table', true);
5585             tbl.setAttribute('width', '100%');
5586         }
5587         
5588     }
5589    
5590
5591
5592     Roo.TabPanel.superclass.constructor.call(this);
5593 };
5594
5595 Roo.extend(Roo.TabPanel, Roo.util.Observable, {
5596     /*
5597      *@cfg {String} tabPosition "top" or "bottom" (defaults to "top")
5598      */
5599     tabPosition : "top",
5600     /*
5601      *@cfg {Number} currentTabWidth The width of the current tab (defaults to 0)
5602      */
5603     currentTabWidth : 0,
5604     /*
5605      *@cfg {Number} minTabWidth The minimum width of a tab (defaults to 40) (ignored if {@link #resizeTabs} is not true)
5606      */
5607     minTabWidth : 40,
5608     /*
5609      *@cfg {Number} maxTabWidth The maximum width of a tab (defaults to 250) (ignored if {@link #resizeTabs} is not true)
5610      */
5611     maxTabWidth : 250,
5612     /*
5613      *@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
5614      */
5615     preferredTabWidth : 175,
5616     /*
5617      *@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
5618      */
5619     resizeTabs : false,
5620     /*
5621      *@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
5622      */
5623     monitorResize : true,
5624     /*
5625      *@cfg {Object} toolbar xtype description of toolbar to show at the right of the tab bar. 
5626      */
5627     toolbar : false,
5628
5629     /**
5630      * Creates a new {@link Roo.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
5631      * @param {String} id The id of the div to use <b>or create</b>
5632      * @param {String} text The text for the tab
5633      * @param {String} content (optional) Content to put in the TabPanelItem body
5634      * @param {Boolean} closable (optional) True to create a close icon on the tab
5635      * @return {Roo.TabPanelItem} The created TabPanelItem
5636      */
5637     addTab : function(id, text, content, closable){
5638         var item = new Roo.TabPanelItem(this, id, text, closable);
5639         this.addTabItem(item);
5640         if(content){
5641             item.setContent(content);
5642         }
5643         return item;
5644     },
5645
5646     /**
5647      * Returns the {@link Roo.TabPanelItem} with the specified id/index
5648      * @param {String/Number} id The id or index of the TabPanelItem to fetch.
5649      * @return {Roo.TabPanelItem}
5650      */
5651     getTab : function(id){
5652         return this.items[id];
5653     },
5654
5655     /**
5656      * Hides the {@link Roo.TabPanelItem} with the specified id/index
5657      * @param {String/Number} id The id or index of the TabPanelItem to hide.
5658      */
5659     hideTab : function(id){
5660         var t = this.items[id];
5661         if(!t.isHidden()){
5662            t.setHidden(true);
5663            this.hiddenCount++;
5664            this.autoSizeTabs();
5665         }
5666     },
5667
5668     /**
5669      * "Unhides" the {@link Roo.TabPanelItem} with the specified id/index.
5670      * @param {String/Number} id The id or index of the TabPanelItem to unhide.
5671      */
5672     unhideTab : function(id){
5673         var t = this.items[id];
5674         if(t.isHidden()){
5675            t.setHidden(false);
5676            this.hiddenCount--;
5677            this.autoSizeTabs();
5678         }
5679     },
5680
5681     /**
5682      * Adds an existing {@link Roo.TabPanelItem}.
5683      * @param {Roo.TabPanelItem} item The TabPanelItem to add
5684      */
5685     addTabItem : function(item){
5686         this.items[item.id] = item;
5687         this.items.push(item);
5688         if(this.resizeTabs){
5689            item.setWidth(this.currentTabWidth || this.preferredTabWidth);
5690            this.autoSizeTabs();
5691         }else{
5692             item.autoSize();
5693         }
5694     },
5695
5696     /**
5697      * Removes a {@link Roo.TabPanelItem}.
5698      * @param {String/Number} id The id or index of the TabPanelItem to remove.
5699      */
5700     removeTab : function(id){
5701         var items = this.items;
5702         var tab = items[id];
5703         if(!tab) { return; }
5704         var index = items.indexOf(tab);
5705         if(this.active == tab && items.length > 1){
5706             var newTab = this.getNextAvailable(index);
5707             if(newTab) {
5708                 newTab.activate();
5709             }
5710         }
5711         this.stripEl.dom.removeChild(tab.pnode.dom);
5712         if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
5713             this.bodyEl.dom.removeChild(tab.bodyEl.dom);
5714         }
5715         items.splice(index, 1);
5716         delete this.items[tab.id];
5717         tab.fireEvent("close", tab);
5718         tab.purgeListeners();
5719         this.autoSizeTabs();
5720     },
5721
5722     getNextAvailable : function(start){
5723         var items = this.items;
5724         var index = start;
5725         // look for a next tab that will slide over to
5726         // replace the one being removed
5727         while(index < items.length){
5728             var item = items[++index];
5729             if(item && !item.isHidden()){
5730                 return item;
5731             }
5732         }
5733         // if one isn't found select the previous tab (on the left)
5734         index = start;
5735         while(index >= 0){
5736             var item = items[--index];
5737             if(item && !item.isHidden()){
5738                 return item;
5739             }
5740         }
5741         return null;
5742     },
5743
5744     /**
5745      * Disables a {@link Roo.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
5746      * @param {String/Number} id The id or index of the TabPanelItem to disable.
5747      */
5748     disableTab : function(id){
5749         var tab = this.items[id];
5750         if(tab && this.active != tab){
5751             tab.disable();
5752         }
5753     },
5754
5755     /**
5756      * Enables a {@link Roo.TabPanelItem} that is disabled.
5757      * @param {String/Number} id The id or index of the TabPanelItem to enable.
5758      */
5759     enableTab : function(id){
5760         var tab = this.items[id];
5761         tab.enable();
5762     },
5763
5764     /**
5765      * Activates a {@link Roo.TabPanelItem}. The currently active one will be deactivated.
5766      * @param {String/Number} id The id or index of the TabPanelItem to activate.
5767      * @return {Roo.TabPanelItem} The TabPanelItem.
5768      */
5769     activate : function(id){
5770         var tab = this.items[id];
5771         if(!tab){
5772             return null;
5773         }
5774         if(tab == this.active || tab.disabled){
5775             return tab;
5776         }
5777         var e = {};
5778         this.fireEvent("beforetabchange", this, e, tab);
5779         if(e.cancel !== true && !tab.disabled){
5780             if(this.active){
5781                 this.active.hide();
5782             }
5783             this.active = this.items[id];
5784             this.active.show();
5785             this.fireEvent("tabchange", this, this.active);
5786         }
5787         return tab;
5788     },
5789
5790     /**
5791      * Gets the active {@link Roo.TabPanelItem}.
5792      * @return {Roo.TabPanelItem} The active TabPanelItem or null if none are active.
5793      */
5794     getActiveTab : function(){
5795         return this.active;
5796     },
5797
5798     /**
5799      * Updates the tab body element to fit the height of the container element
5800      * for overflow scrolling
5801      * @param {Number} targetHeight (optional) Override the starting height from the elements height
5802      */
5803     syncHeight : function(targetHeight){
5804         var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
5805         var bm = this.bodyEl.getMargins();
5806         var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
5807         this.bodyEl.setHeight(newHeight);
5808         return newHeight;
5809     },
5810
5811     onResize : function(){
5812         if(this.monitorResize){
5813             this.autoSizeTabs();
5814         }
5815     },
5816
5817     /**
5818      * Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
5819      */
5820     beginUpdate : function(){
5821         this.updating = true;
5822     },
5823
5824     /**
5825      * Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
5826      */
5827     endUpdate : function(){
5828         this.updating = false;
5829         this.autoSizeTabs();
5830     },
5831
5832     /**
5833      * Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
5834      */
5835     autoSizeTabs : function(){
5836         var count = this.items.length;
5837         var vcount = count - this.hiddenCount;
5838         if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) {
5839             return;
5840         }
5841         var w = Math.max(this.el.getWidth() - this.cpad, 10);
5842         var availWidth = Math.floor(w / vcount);
5843         var b = this.stripBody;
5844         if(b.getWidth() > w){
5845             var tabs = this.items;
5846             this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
5847             if(availWidth < this.minTabWidth){
5848                 /*if(!this.sleft){    // incomplete scrolling code
5849                     this.createScrollButtons();
5850                 }
5851                 this.showScroll();
5852                 this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
5853             }
5854         }else{
5855             if(this.currentTabWidth < this.preferredTabWidth){
5856                 this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
5857             }
5858         }
5859     },
5860
5861     /**
5862      * Returns the number of tabs in this TabPanel.
5863      * @return {Number}
5864      */
5865      getCount : function(){
5866          return this.items.length;
5867      },
5868
5869     /**
5870      * Resizes all the tabs to the passed width
5871      * @param {Number} The new width
5872      */
5873     setTabWidth : function(width){
5874         this.currentTabWidth = width;
5875         for(var i = 0, len = this.items.length; i < len; i++) {
5876                 if(!this.items[i].isHidden()) {
5877                 this.items[i].setWidth(width);
5878             }
5879         }
5880     },
5881
5882     /**
5883      * Destroys this TabPanel
5884      * @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
5885      */
5886     destroy : function(removeEl){
5887         Roo.EventManager.removeResizeListener(this.onResize, this);
5888         for(var i = 0, len = this.items.length; i < len; i++){
5889             this.items[i].purgeListeners();
5890         }
5891         if(removeEl === true){
5892             this.el.update("");
5893             this.el.remove();
5894         }
5895     }
5896 });
5897
5898 /**
5899  * @class Roo.TabPanelItem
5900  * @extends Roo.util.Observable
5901  * Represents an individual item (tab plus body) in a TabPanel.
5902  * @param {Roo.TabPanel} tabPanel The {@link Roo.TabPanel} this TabPanelItem belongs to
5903  * @param {String} id The id of this TabPanelItem
5904  * @param {String} text The text for the tab of this TabPanelItem
5905  * @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
5906  */
5907 Roo.TabPanelItem = function(tabPanel, id, text, closable){
5908     /**
5909      * The {@link Roo.TabPanel} this TabPanelItem belongs to
5910      * @type Roo.TabPanel
5911      */
5912     this.tabPanel = tabPanel;
5913     /**
5914      * The id for this TabPanelItem
5915      * @type String
5916      */
5917     this.id = id;
5918     /** @private */
5919     this.disabled = false;
5920     /** @private */
5921     this.text = text;
5922     /** @private */
5923     this.loaded = false;
5924     this.closable = closable;
5925
5926     /**
5927      * The body element for this TabPanelItem.
5928      * @type Roo.Element
5929      */
5930     this.bodyEl = Roo.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
5931     this.bodyEl.setVisibilityMode(Roo.Element.VISIBILITY);
5932     this.bodyEl.setStyle("display", "block");
5933     this.bodyEl.setStyle("zoom", "1");
5934     this.hideAction();
5935
5936     var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
5937     /** @private */
5938     this.el = Roo.get(els.el, true);
5939     this.inner = Roo.get(els.inner, true);
5940     this.textEl = Roo.get(this.el.dom.firstChild.firstChild.firstChild, true);
5941     this.pnode = Roo.get(els.el.parentNode, true);
5942     this.el.on("mousedown", this.onTabMouseDown, this);
5943     this.el.on("click", this.onTabClick, this);
5944     /** @private */
5945     if(closable){
5946         var c = Roo.get(els.close, true);
5947         c.dom.title = this.closeText;
5948         c.addClassOnOver("close-over");
5949         c.on("click", this.closeClick, this);
5950      }
5951
5952     this.addEvents({
5953          /**
5954          * @event activate
5955          * Fires when this tab becomes the active tab.
5956          * @param {Roo.TabPanel} tabPanel The parent TabPanel
5957          * @param {Roo.TabPanelItem} this
5958          */
5959         "activate": true,
5960         /**
5961          * @event beforeclose
5962          * Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
5963          * @param {Roo.TabPanelItem} this
5964          * @param {Object} e Set cancel to true on this object to cancel the close.
5965          */
5966         "beforeclose": true,
5967         /**
5968          * @event close
5969          * Fires when this tab is closed.
5970          * @param {Roo.TabPanelItem} this
5971          */
5972          "close": true,
5973         /**
5974          * @event deactivate
5975          * Fires when this tab is no longer the active tab.
5976          * @param {Roo.TabPanel} tabPanel The parent TabPanel
5977          * @param {Roo.TabPanelItem} this
5978          */
5979          "deactivate" : true
5980     });
5981     this.hidden = false;
5982
5983     Roo.TabPanelItem.superclass.constructor.call(this);
5984 };
5985
5986 Roo.extend(Roo.TabPanelItem, Roo.util.Observable, {
5987     purgeListeners : function(){
5988        Roo.util.Observable.prototype.purgeListeners.call(this);
5989        this.el.removeAllListeners();
5990     },
5991     /**
5992      * Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
5993      */
5994     show : function(){
5995         this.pnode.addClass("on");
5996         this.showAction();
5997         if(Roo.isOpera){
5998             this.tabPanel.stripWrap.repaint();
5999         }
6000         this.fireEvent("activate", this.tabPanel, this);
6001     },
6002
6003     /**
6004      * Returns true if this tab is the active tab.
6005      * @return {Boolean}
6006      */
6007     isActive : function(){
6008         return this.tabPanel.getActiveTab() == this;
6009     },
6010
6011     /**
6012      * Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
6013      */
6014     hide : function(){
6015         this.pnode.removeClass("on");
6016         this.hideAction();
6017         this.fireEvent("deactivate", this.tabPanel, this);
6018     },
6019
6020     hideAction : function(){
6021         this.bodyEl.hide();
6022         this.bodyEl.setStyle("position", "absolute");
6023         this.bodyEl.setLeft("-20000px");
6024         this.bodyEl.setTop("-20000px");
6025     },
6026
6027     showAction : function(){
6028         this.bodyEl.setStyle("position", "relative");
6029         this.bodyEl.setTop("");
6030         this.bodyEl.setLeft("");
6031         this.bodyEl.show();
6032     },
6033
6034     /**
6035      * Set the tooltip for the tab.
6036      * @param {String} tooltip The tab's tooltip
6037      */
6038     setTooltip : function(text){
6039         if(Roo.QuickTips && Roo.QuickTips.isEnabled()){
6040             this.textEl.dom.qtip = text;
6041             this.textEl.dom.removeAttribute('title');
6042         }else{
6043             this.textEl.dom.title = text;
6044         }
6045     },
6046
6047     onTabClick : function(e){
6048         e.preventDefault();
6049         this.tabPanel.activate(this.id);
6050     },
6051
6052     onTabMouseDown : function(e){
6053         e.preventDefault();
6054         this.tabPanel.activate(this.id);
6055     },
6056
6057     getWidth : function(){
6058         return this.inner.getWidth();
6059     },
6060
6061     setWidth : function(width){
6062         var iwidth = width - this.pnode.getPadding("lr");
6063         this.inner.setWidth(iwidth);
6064         this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
6065         this.pnode.setWidth(width);
6066     },
6067
6068     /**
6069      * Show or hide the tab
6070      * @param {Boolean} hidden True to hide or false to show.
6071      */
6072     setHidden : function(hidden){
6073         this.hidden = hidden;
6074         this.pnode.setStyle("display", hidden ? "none" : "");
6075     },
6076
6077     /**
6078      * Returns true if this tab is "hidden"
6079      * @return {Boolean}
6080      */
6081     isHidden : function(){
6082         return this.hidden;
6083     },
6084
6085     /**
6086      * Returns the text for this tab
6087      * @return {String}
6088      */
6089     getText : function(){
6090         return this.text;
6091     },
6092
6093     autoSize : function(){
6094         //this.el.beginMeasure();
6095         this.textEl.setWidth(1);
6096         /*
6097          *  #2804 [new] Tabs in Roojs
6098          *  increase the width by 2-4 pixels to prevent the ellipssis showing in chrome
6099          */
6100         this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr") + 2);
6101         //this.el.endMeasure();
6102     },
6103
6104     /**
6105      * Sets the text for the tab (Note: this also sets the tooltip text)
6106      * @param {String} text The tab's text and tooltip
6107      */
6108     setText : function(text){
6109         this.text = text;
6110         this.textEl.update(text);
6111         this.setTooltip(text);
6112         if(!this.tabPanel.resizeTabs){
6113             this.autoSize();
6114         }
6115     },
6116     /**
6117      * Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
6118      */
6119     activate : function(){
6120         this.tabPanel.activate(this.id);
6121     },
6122
6123     /**
6124      * Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
6125      */
6126     disable : function(){
6127         if(this.tabPanel.active != this){
6128             this.disabled = true;
6129             this.pnode.addClass("disabled");
6130         }
6131     },
6132
6133     /**
6134      * Enables this TabPanelItem if it was previously disabled.
6135      */
6136     enable : function(){
6137         this.disabled = false;
6138         this.pnode.removeClass("disabled");
6139     },
6140
6141     /**
6142      * Sets the content for this TabPanelItem.
6143      * @param {String} content The content
6144      * @param {Boolean} loadScripts true to look for and load scripts
6145      */
6146     setContent : function(content, loadScripts){
6147         this.bodyEl.update(content, loadScripts);
6148     },
6149
6150     /**
6151      * Gets the {@link Roo.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
6152      * @return {Roo.UpdateManager} The UpdateManager
6153      */
6154     getUpdateManager : function(){
6155         return this.bodyEl.getUpdateManager();
6156     },
6157
6158     /**
6159      * Set a URL to be used to load the content for this TabPanelItem.
6160      * @param {String/Function} url The URL to load the content from, or a function to call to get the URL
6161      * @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)
6162      * @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)
6163      * @return {Roo.UpdateManager} The UpdateManager
6164      */
6165     setUrl : function(url, params, loadOnce){
6166         if(this.refreshDelegate){
6167             this.un('activate', this.refreshDelegate);
6168         }
6169         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
6170         this.on("activate", this.refreshDelegate);
6171         return this.bodyEl.getUpdateManager();
6172     },
6173
6174     /** @private */
6175     _handleRefresh : function(url, params, loadOnce){
6176         if(!loadOnce || !this.loaded){
6177             var updater = this.bodyEl.getUpdateManager();
6178             updater.update(url, params, this._setLoaded.createDelegate(this));
6179         }
6180     },
6181
6182     /**
6183      *   Forces a content refresh from the URL specified in the {@link #setUrl} method.
6184      *   Will fail silently if the setUrl method has not been called.
6185      *   This does not activate the panel, just updates its content.
6186      */
6187     refresh : function(){
6188         if(this.refreshDelegate){
6189            this.loaded = false;
6190            this.refreshDelegate();
6191         }
6192     },
6193
6194     /** @private */
6195     _setLoaded : function(){
6196         this.loaded = true;
6197     },
6198
6199     /** @private */
6200     closeClick : function(e){
6201         var o = {};
6202         e.stopEvent();
6203         this.fireEvent("beforeclose", this, o);
6204         if(o.cancel !== true){
6205             this.tabPanel.removeTab(this.id);
6206         }
6207     },
6208     /**
6209      * The text displayed in the tooltip for the close icon.
6210      * @type String
6211      */
6212     closeText : "Close this tab"
6213 });
6214
6215 /** @private */
6216 Roo.TabPanel.prototype.createStrip = function(container){
6217     var strip = document.createElement("div");
6218     strip.className = "x-tabs-wrap";
6219     container.appendChild(strip);
6220     return strip;
6221 };
6222 /** @private */
6223 Roo.TabPanel.prototype.createStripList = function(strip){
6224     // div wrapper for retard IE
6225     // returns the "tr" element.
6226     strip.innerHTML = '<div class="x-tabs-strip-wrap">'+
6227         '<table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr>'+
6228         '<td class="x-tab-strip-toolbar"></td></tr></tbody></table></div>';
6229     return strip.firstChild.firstChild.firstChild.firstChild;
6230 };
6231 /** @private */
6232 Roo.TabPanel.prototype.createBody = function(container){
6233     var body = document.createElement("div");
6234     Roo.id(body, "tab-body");
6235     Roo.fly(body).addClass("x-tabs-body");
6236     container.appendChild(body);
6237     return body;
6238 };
6239 /** @private */
6240 Roo.TabPanel.prototype.createItemBody = function(bodyEl, id){
6241     var body = Roo.getDom(id);
6242     if(!body){
6243         body = document.createElement("div");
6244         body.id = id;
6245     }
6246     Roo.fly(body).addClass("x-tabs-item-body");
6247     bodyEl.insertBefore(body, bodyEl.firstChild);
6248     return body;
6249 };
6250 /** @private */
6251 Roo.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
6252     var td = document.createElement("td");
6253     stripEl.insertBefore(td, stripEl.childNodes[stripEl.childNodes.length-1]);
6254     //stripEl.appendChild(td);
6255     if(closable){
6256         td.className = "x-tabs-closable";
6257         if(!this.closeTpl){
6258             this.closeTpl = new Roo.Template(
6259                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6260                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
6261                '<div unselectable="on" class="close-icon">&#160;</div></em></span></a>'
6262             );
6263         }
6264         var el = this.closeTpl.overwrite(td, {"text": text});
6265         var close = el.getElementsByTagName("div")[0];
6266         var inner = el.getElementsByTagName("em")[0];
6267         return {"el": el, "close": close, "inner": inner};
6268     } else {
6269         if(!this.tabTpl){
6270             this.tabTpl = new Roo.Template(
6271                '<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
6272                '<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
6273             );
6274         }
6275         var el = this.tabTpl.overwrite(td, {"text": text});
6276         var inner = el.getElementsByTagName("em")[0];
6277         return {"el": el, "inner": inner};
6278     }
6279 };/*
6280  * Based on:
6281  * Ext JS Library 1.1.1
6282  * Copyright(c) 2006-2007, Ext JS, LLC.
6283  *
6284  * Originally Released Under LGPL - original licence link has changed is not relivant.
6285  *
6286  * Fork - LGPL
6287  * <script type="text/javascript">
6288  */
6289
6290 /**
6291  * @class Roo.Button
6292  * @extends Roo.util.Observable
6293  * Simple Button class
6294  * @cfg {String} text The button text
6295  * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
6296  * CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
6297  * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event)
6298  * @cfg {Object} scope The scope of the handler
6299  * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width)
6300  * @cfg {String/Object} tooltip The tooltip for the button - can be a string or QuickTips config object
6301  * @cfg {Boolean} hidden True to start hidden (defaults to false)
6302  * @cfg {Boolean} disabled True to start disabled (defaults to false)
6303  * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
6304  * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed, only
6305    applies if enableToggle = true)
6306  * @cfg {String/HTMLElement/Element} renderTo The element to append the button to
6307  * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
6308   an {@link Roo.util.ClickRepeater} config object (defaults to false).
6309  * @constructor
6310  * Create a new button
6311  * @param {Object} config The config object
6312  */
6313 Roo.Button = function(renderTo, config)
6314 {
6315     if (!config) {
6316         config = renderTo;
6317         renderTo = config.renderTo || false;
6318     }
6319     
6320     Roo.apply(this, config);
6321     this.addEvents({
6322         /**
6323              * @event click
6324              * Fires when this button is clicked
6325              * @param {Button} this
6326              * @param {EventObject} e The click event
6327              */
6328             "click" : true,
6329         /**
6330              * @event toggle
6331              * Fires when the "pressed" state of this button changes (only if enableToggle = true)
6332              * @param {Button} this
6333              * @param {Boolean} pressed
6334              */
6335             "toggle" : true,
6336         /**
6337              * @event mouseover
6338              * Fires when the mouse hovers over the button
6339              * @param {Button} this
6340              * @param {Event} e The event object
6341              */
6342         'mouseover' : true,
6343         /**
6344              * @event mouseout
6345              * Fires when the mouse exits the button
6346              * @param {Button} this
6347              * @param {Event} e The event object
6348              */
6349         'mouseout': true,
6350          /**
6351              * @event render
6352              * Fires when the button is rendered
6353              * @param {Button} this
6354              */
6355         'render': true
6356     });
6357     if(this.menu){
6358         this.menu = Roo.menu.MenuMgr.get(this.menu);
6359     }
6360     // register listeners first!!  - so render can be captured..
6361     Roo.util.Observable.call(this);
6362     if(renderTo){
6363         this.render(renderTo);
6364     }
6365     
6366   
6367 };
6368
6369 Roo.extend(Roo.Button, Roo.util.Observable, {
6370     /**
6371      * 
6372      */
6373     
6374     /**
6375      * Read-only. True if this button is hidden
6376      * @type Boolean
6377      */
6378     hidden : false,
6379     /**
6380      * Read-only. True if this button is disabled
6381      * @type Boolean
6382      */
6383     disabled : false,
6384     /**
6385      * Read-only. True if this button is pressed (only if enableToggle = true)
6386      * @type Boolean
6387      */
6388     pressed : false,
6389
6390     /**
6391      * @cfg {Number} tabIndex 
6392      * The DOM tabIndex for this button (defaults to undefined)
6393      */
6394     tabIndex : undefined,
6395
6396     /**
6397      * @cfg {Boolean} enableToggle
6398      * True to enable pressed/not pressed toggling (defaults to false)
6399      */
6400     enableToggle: false,
6401     /**
6402      * @cfg {Roo.menu.Menu} menu
6403      * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
6404      */
6405     menu : undefined,
6406     /**
6407      * @cfg {String} menuAlign
6408      * The position to align the menu to (see {@link Roo.Element#alignTo} for more details, defaults to 'tl-bl?').
6409      */
6410     menuAlign : "tl-bl?",
6411
6412     /**
6413      * @cfg {String} iconCls
6414      * A css class which sets a background image to be used as the icon for this button (defaults to undefined).
6415      */
6416     iconCls : undefined,
6417     /**
6418      * @cfg {String} type
6419      * The button's type, corresponding to the DOM input element type attribute.  Either "submit," "reset" or "button" (default).
6420      */
6421     type : 'button',
6422
6423     // private
6424     menuClassTarget: 'tr',
6425
6426     /**
6427      * @cfg {String} clickEvent
6428      * The type of event to map to the button's event handler (defaults to 'click')
6429      */
6430     clickEvent : 'click',
6431
6432     /**
6433      * @cfg {Boolean} handleMouseEvents
6434      * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
6435      */
6436     handleMouseEvents : true,
6437
6438     /**
6439      * @cfg {String} tooltipType
6440      * The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
6441      */
6442     tooltipType : 'qtip',
6443
6444     /**
6445      * @cfg {String} cls
6446      * A CSS class to apply to the button's main element.
6447      */
6448     
6449     /**
6450      * @cfg {Roo.Template} template (Optional)
6451      * An {@link Roo.Template} with which to create the Button's main element. This Template must
6452      * contain numeric substitution parameter 0 if it is to display the tRoo property. Changing the template could
6453      * require code modifications if required elements (e.g. a button) aren't present.
6454      */
6455
6456     // private
6457     render : function(renderTo){
6458         var btn;
6459         if(this.hideParent){
6460             this.parentEl = Roo.get(renderTo);
6461         }
6462         if(!this.dhconfig){
6463             if(!this.template){
6464                 if(!Roo.Button.buttonTemplate){
6465                     // hideous table template
6466                     Roo.Button.buttonTemplate = new Roo.Template(
6467                         '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
6468                         '<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>',
6469                         "</tr></tbody></table>");
6470                 }
6471                 this.template = Roo.Button.buttonTemplate;
6472             }
6473             btn = this.template.append(renderTo, [this.text || '&#160;', this.type], true);
6474             var btnEl = btn.child("button:first");
6475             btnEl.on('focus', this.onFocus, this);
6476             btnEl.on('blur', this.onBlur, this);
6477             if(this.cls){
6478                 btn.addClass(this.cls);
6479             }
6480             if(this.icon){
6481                 btnEl.setStyle('background-image', 'url(' +this.icon +')');
6482             }
6483             if(this.iconCls){
6484                 btnEl.addClass(this.iconCls);
6485                 if(!this.cls){
6486                     btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
6487                 }
6488             }
6489             if(this.tabIndex !== undefined){
6490                 btnEl.dom.tabIndex = this.tabIndex;
6491             }
6492             if(this.tooltip){
6493                 if(typeof this.tooltip == 'object'){
6494                     Roo.QuickTips.tips(Roo.apply({
6495                           target: btnEl.id
6496                     }, this.tooltip));
6497                 } else {
6498                     btnEl.dom[this.tooltipType] = this.tooltip;
6499                 }
6500             }
6501         }else{
6502             btn = Roo.DomHelper.append(Roo.get(renderTo).dom, this.dhconfig, true);
6503         }
6504         this.el = btn;
6505         if(this.id){
6506             this.el.dom.id = this.el.id = this.id;
6507         }
6508         if(this.menu){
6509             this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
6510             this.menu.on("show", this.onMenuShow, this);
6511             this.menu.on("hide", this.onMenuHide, this);
6512         }
6513         btn.addClass("x-btn");
6514         if(Roo.isIE && !Roo.isIE7){
6515             this.autoWidth.defer(1, this);
6516         }else{
6517             this.autoWidth();
6518         }
6519         if(this.handleMouseEvents){
6520             btn.on("mouseover", this.onMouseOver, this);
6521             btn.on("mouseout", this.onMouseOut, this);
6522             btn.on("mousedown", this.onMouseDown, this);
6523         }
6524         btn.on(this.clickEvent, this.onClick, this);
6525         //btn.on("mouseup", this.onMouseUp, this);
6526         if(this.hidden){
6527             this.hide();
6528         }
6529         if(this.disabled){
6530             this.disable();
6531         }
6532         Roo.ButtonToggleMgr.register(this);
6533         if(this.pressed){
6534             this.el.addClass("x-btn-pressed");
6535         }
6536         if(this.repeat){
6537             var repeater = new Roo.util.ClickRepeater(btn,
6538                 typeof this.repeat == "object" ? this.repeat : {}
6539             );
6540             repeater.on("click", this.onClick,  this);
6541         }
6542         
6543         this.fireEvent('render', this);
6544         
6545     },
6546     /**
6547      * Returns the button's underlying element
6548      * @return {Roo.Element} The element
6549      */
6550     getEl : function(){
6551         return this.el;  
6552     },
6553     
6554     /**
6555      * Destroys this Button and removes any listeners.
6556      */
6557     destroy : function(){
6558         Roo.ButtonToggleMgr.unregister(this);
6559         this.el.removeAllListeners();
6560         this.purgeListeners();
6561         this.el.remove();
6562     },
6563
6564     // private
6565     autoWidth : function(){
6566         if(this.el){
6567             this.el.setWidth("auto");
6568             if(Roo.isIE7 && Roo.isStrict){
6569                 var ib = this.el.child('button');
6570                 if(ib && ib.getWidth() > 20){
6571                     ib.clip();
6572                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
6573                 }
6574             }
6575             if(this.minWidth){
6576                 if(this.hidden){
6577                     this.el.beginMeasure();
6578                 }
6579                 if(this.el.getWidth() < this.minWidth){
6580                     this.el.setWidth(this.minWidth);
6581                 }
6582                 if(this.hidden){
6583                     this.el.endMeasure();
6584                 }
6585             }
6586         }
6587     },
6588
6589     /**
6590      * Assigns this button's click handler
6591      * @param {Function} handler The function to call when the button is clicked
6592      * @param {Object} scope (optional) Scope for the function passed in
6593      */
6594     setHandler : function(handler, scope){
6595         this.handler = handler;
6596         this.scope = scope;  
6597     },
6598     
6599     /**
6600      * Sets this button's text
6601      * @param {String} text The button text
6602      */
6603     setText : function(text){
6604         this.text = text;
6605         if(this.el){
6606             this.el.child("td.x-btn-center button.x-btn-text").update(text);
6607         }
6608         this.autoWidth();
6609     },
6610     
6611     /**
6612      * Gets the text for this button
6613      * @return {String} The button text
6614      */
6615     getText : function(){
6616         return this.text;  
6617     },
6618     
6619     /**
6620      * Show this button
6621      */
6622     show: function(){
6623         this.hidden = false;
6624         if(this.el){
6625             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
6626         }
6627     },
6628     
6629     /**
6630      * Hide this button
6631      */
6632     hide: function(){
6633         this.hidden = true;
6634         if(this.el){
6635             this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
6636         }
6637     },
6638     
6639     /**
6640      * Convenience function for boolean show/hide
6641      * @param {Boolean} visible True to show, false to hide
6642      */
6643     setVisible: function(visible){
6644         if(visible) {
6645             this.show();
6646         }else{
6647             this.hide();
6648         }
6649     },
6650     /**
6651          * Similar to toggle, but does not trigger event.
6652          * @param {Boolean} state [required] Force a particular state
6653          */
6654         setPressed : function(state)
6655         {
6656             if(state != this.pressed){
6657             if(state){
6658                 this.el.addClass("x-btn-pressed");
6659                 this.pressed = true;
6660             }else{
6661                 this.el.removeClass("x-btn-pressed");
6662                 this.pressed = false;
6663             }
6664         }
6665         },
6666         
6667     /**
6668      * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
6669      * @param {Boolean} state (optional) Force a particular state
6670      */
6671     toggle : function(state){
6672         state = state === undefined ? !this.pressed : state;
6673         if(state != this.pressed){
6674             if(state){
6675                 this.el.addClass("x-btn-pressed");
6676                 this.pressed = true;
6677                 this.fireEvent("toggle", this, true);
6678             }else{
6679                 this.el.removeClass("x-btn-pressed");
6680                 this.pressed = false;
6681                 this.fireEvent("toggle", this, false);
6682             }
6683             if(this.toggleHandler){
6684                 this.toggleHandler.call(this.scope || this, this, state);
6685             }
6686         }
6687     },
6688     
6689         
6690         
6691     /**
6692      * Focus the button
6693      */
6694     focus : function(){
6695         this.el.child('button:first').focus();
6696     },
6697     
6698     /**
6699      * Disable this button
6700      */
6701     disable : function(){
6702         if(this.el){
6703             this.el.addClass("x-btn-disabled");
6704         }
6705         this.disabled = true;
6706     },
6707     
6708     /**
6709      * Enable this button
6710      */
6711     enable : function(){
6712         if(this.el){
6713             this.el.removeClass("x-btn-disabled");
6714         }
6715         this.disabled = false;
6716     },
6717
6718     /**
6719      * Convenience function for boolean enable/disable
6720      * @param {Boolean} enabled True to enable, false to disable
6721      */
6722     setDisabled : function(v){
6723         this[v !== true ? "enable" : "disable"]();
6724     },
6725
6726     // private
6727     onClick : function(e)
6728     {
6729         if(e){
6730             e.preventDefault();
6731         }
6732         if(e.button != 0){
6733             return;
6734         }
6735         if(!this.disabled){
6736             if(this.enableToggle){
6737                 this.toggle();
6738             }
6739             if(this.menu && !this.menu.isVisible()){
6740                 this.menu.show(this.el, this.menuAlign);
6741             }
6742             this.fireEvent("click", this, e);
6743             if(this.handler){
6744                 this.el.removeClass("x-btn-over");
6745                 this.handler.call(this.scope || this, this, e);
6746             }
6747         }
6748     },
6749     // private
6750     onMouseOver : function(e){
6751         if(!this.disabled){
6752             this.el.addClass("x-btn-over");
6753             this.fireEvent('mouseover', this, e);
6754         }
6755     },
6756     // private
6757     onMouseOut : function(e){
6758         if(!e.within(this.el,  true)){
6759             this.el.removeClass("x-btn-over");
6760             this.fireEvent('mouseout', this, e);
6761         }
6762     },
6763     // private
6764     onFocus : function(e){
6765         if(!this.disabled){
6766             this.el.addClass("x-btn-focus");
6767         }
6768     },
6769     // private
6770     onBlur : function(e){
6771         this.el.removeClass("x-btn-focus");
6772     },
6773     // private
6774     onMouseDown : function(e){
6775         if(!this.disabled && e.button == 0){
6776             this.el.addClass("x-btn-click");
6777             Roo.get(document).on('mouseup', this.onMouseUp, this);
6778         }
6779     },
6780     // private
6781     onMouseUp : function(e){
6782         if(e.button == 0){
6783             this.el.removeClass("x-btn-click");
6784             Roo.get(document).un('mouseup', this.onMouseUp, this);
6785         }
6786     },
6787     // private
6788     onMenuShow : function(e){
6789         this.el.addClass("x-btn-menu-active");
6790     },
6791     // private
6792     onMenuHide : function(e){
6793         this.el.removeClass("x-btn-menu-active");
6794     }   
6795 });
6796
6797 // Private utility class used by Button
6798 Roo.ButtonToggleMgr = function(){
6799    var groups = {};
6800    
6801    function toggleGroup(btn, state){
6802        if(state){
6803            var g = groups[btn.toggleGroup];
6804            for(var i = 0, l = g.length; i < l; i++){
6805                if(g[i] != btn){
6806                    g[i].toggle(false);
6807                }
6808            }
6809        }
6810    }
6811    
6812    return {
6813        register : function(btn){
6814            if(!btn.toggleGroup){
6815                return;
6816            }
6817            var g = groups[btn.toggleGroup];
6818            if(!g){
6819                g = groups[btn.toggleGroup] = [];
6820            }
6821            g.push(btn);
6822            btn.on("toggle", toggleGroup);
6823        },
6824        
6825        unregister : function(btn){
6826            if(!btn.toggleGroup){
6827                return;
6828            }
6829            var g = groups[btn.toggleGroup];
6830            if(g){
6831                g.remove(btn);
6832                btn.un("toggle", toggleGroup);
6833            }
6834        }
6835    };
6836 }();/*
6837  * Based on:
6838  * Ext JS Library 1.1.1
6839  * Copyright(c) 2006-2007, Ext JS, LLC.
6840  *
6841  * Originally Released Under LGPL - original licence link has changed is not relivant.
6842  *
6843  * Fork - LGPL
6844  * <script type="text/javascript">
6845  */
6846  
6847 /**
6848  * @class Roo.SplitButton
6849  * @extends Roo.Button
6850  * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
6851  * click event of the button.  Typically this would be used to display a dropdown menu that provides additional
6852  * options to the primary button action, but any custom handler can provide the arrowclick implementation.
6853  * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
6854  * @cfg {String} arrowTooltip The title attribute of the arrow
6855  * @constructor
6856  * Create a new menu button
6857  * @param {String/HTMLElement/Element} renderTo The element to append the button to
6858  * @param {Object} config The config object
6859  */
6860 Roo.SplitButton = function(renderTo, config){
6861     Roo.SplitButton.superclass.constructor.call(this, renderTo, config);
6862     /**
6863      * @event arrowclick
6864      * Fires when this button's arrow is clicked
6865      * @param {SplitButton} this
6866      * @param {EventObject} e The click event
6867      */
6868     this.addEvents({"arrowclick":true});
6869 };
6870
6871 Roo.extend(Roo.SplitButton, Roo.Button, {
6872     render : function(renderTo){
6873         // this is one sweet looking template!
6874         var tpl = new Roo.Template(
6875             '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>',
6876             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>',
6877             '<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>',
6878             "</tbody></table></td><td>",
6879             '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>',
6880             '<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>',
6881             "</tbody></table></td></tr></table>"
6882         );
6883         var btn = tpl.append(renderTo, [this.text, this.type], true);
6884         var btnEl = btn.child("button");
6885         if(this.cls){
6886             btn.addClass(this.cls);
6887         }
6888         if(this.icon){
6889             btnEl.setStyle('background-image', 'url(' +this.icon +')');
6890         }
6891         if(this.iconCls){
6892             btnEl.addClass(this.iconCls);
6893             if(!this.cls){
6894                 btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
6895             }
6896         }
6897         this.el = btn;
6898         if(this.handleMouseEvents){
6899             btn.on("mouseover", this.onMouseOver, this);
6900             btn.on("mouseout", this.onMouseOut, this);
6901             btn.on("mousedown", this.onMouseDown, this);
6902             btn.on("mouseup", this.onMouseUp, this);
6903         }
6904         btn.on(this.clickEvent, this.onClick, this);
6905         if(this.tooltip){
6906             if(typeof this.tooltip == 'object'){
6907                 Roo.QuickTips.tips(Roo.apply({
6908                       target: btnEl.id
6909                 }, this.tooltip));
6910             } else {
6911                 btnEl.dom[this.tooltipType] = this.tooltip;
6912             }
6913         }
6914         if(this.arrowTooltip){
6915             btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip;
6916         }
6917         if(this.hidden){
6918             this.hide();
6919         }
6920         if(this.disabled){
6921             this.disable();
6922         }
6923         if(this.pressed){
6924             this.el.addClass("x-btn-pressed");
6925         }
6926         if(Roo.isIE && !Roo.isIE7){
6927             this.autoWidth.defer(1, this);
6928         }else{
6929             this.autoWidth();
6930         }
6931         if(this.menu){
6932             this.menu.on("show", this.onMenuShow, this);
6933             this.menu.on("hide", this.onMenuHide, this);
6934         }
6935         this.fireEvent('render', this);
6936     },
6937
6938     // private
6939     autoWidth : function(){
6940         if(this.el){
6941             var tbl = this.el.child("table:first");
6942             var tbl2 = this.el.child("table:last");
6943             this.el.setWidth("auto");
6944             tbl.setWidth("auto");
6945             if(Roo.isIE7 && Roo.isStrict){
6946                 var ib = this.el.child('button:first');
6947                 if(ib && ib.getWidth() > 20){
6948                     ib.clip();
6949                     ib.setWidth(Roo.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
6950                 }
6951             }
6952             if(this.minWidth){
6953                 if(this.hidden){
6954                     this.el.beginMeasure();
6955                 }
6956                 if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){
6957                     tbl.setWidth(this.minWidth-tbl2.getWidth());
6958                 }
6959                 if(this.hidden){
6960                     this.el.endMeasure();
6961                 }
6962             }
6963             this.el.setWidth(tbl.getWidth()+tbl2.getWidth());
6964         } 
6965     },
6966     /**
6967      * Sets this button's click handler
6968      * @param {Function} handler The function to call when the button is clicked
6969      * @param {Object} scope (optional) Scope for the function passed above
6970      */
6971     setHandler : function(handler, scope){
6972         this.handler = handler;
6973         this.scope = scope;  
6974     },
6975     
6976     /**
6977      * Sets this button's arrow click handler
6978      * @param {Function} handler The function to call when the arrow is clicked
6979      * @param {Object} scope (optional) Scope for the function passed above
6980      */
6981     setArrowHandler : function(handler, scope){
6982         this.arrowHandler = handler;
6983         this.scope = scope;  
6984     },
6985     
6986     /**
6987      * Focus the button
6988      */
6989     focus : function(){
6990         if(this.el){
6991             this.el.child("button:first").focus();
6992         }
6993     },
6994
6995     // private
6996     onClick : function(e){
6997         e.preventDefault();
6998         if(!this.disabled){
6999             if(e.getTarget(".x-btn-menu-arrow-wrap")){
7000                 if(this.menu && !this.menu.isVisible()){
7001                     this.menu.show(this.el, this.menuAlign);
7002                 }
7003                 this.fireEvent("arrowclick", this, e);
7004                 if(this.arrowHandler){
7005                     this.arrowHandler.call(this.scope || this, this, e);
7006                 }
7007             }else{
7008                 this.fireEvent("click", this, e);
7009                 if(this.handler){
7010                     this.handler.call(this.scope || this, this, e);
7011                 }
7012             }
7013         }
7014     },
7015     // private
7016     onMouseDown : function(e){
7017         if(!this.disabled){
7018             Roo.fly(e.getTarget("table")).addClass("x-btn-click");
7019         }
7020     },
7021     // private
7022     onMouseUp : function(e){
7023         Roo.fly(e.getTarget("table")).removeClass("x-btn-click");
7024     }   
7025 });
7026
7027
7028 // backwards compat
7029 Roo.MenuButton = Roo.SplitButton;/*
7030  * Based on:
7031  * Ext JS Library 1.1.1
7032  * Copyright(c) 2006-2007, Ext JS, LLC.
7033  *
7034  * Originally Released Under LGPL - original licence link has changed is not relivant.
7035  *
7036  * Fork - LGPL
7037  * <script type="text/javascript">
7038  */
7039
7040 /**
7041  * @class Roo.Toolbar
7042  * @children   Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field 
7043  * Basic Toolbar class.
7044  * @constructor
7045  * Creates a new Toolbar
7046  * @param {Object} container The config object
7047  */ 
7048 Roo.Toolbar = function(container, buttons, config)
7049 {
7050     /// old consturctor format still supported..
7051     if(container instanceof Array){ // omit the container for later rendering
7052         buttons = container;
7053         config = buttons;
7054         container = null;
7055     }
7056     if (typeof(container) == 'object' && container.xtype) {
7057         config = container;
7058         container = config.container;
7059         buttons = config.buttons || []; // not really - use items!!
7060     }
7061     var xitems = [];
7062     if (config && config.items) {
7063         xitems = config.items;
7064         delete config.items;
7065     }
7066     Roo.apply(this, config);
7067     this.buttons = buttons;
7068     
7069     if(container){
7070         this.render(container);
7071     }
7072     this.xitems = xitems;
7073     Roo.each(xitems, function(b) {
7074         this.add(b);
7075     }, this);
7076     
7077 };
7078
7079 Roo.Toolbar.prototype = {
7080     /**
7081      * @cfg {Array} items
7082      * array of button configs or elements to add (will be converted to a MixedCollection)
7083      */
7084     items: false,
7085     /**
7086      * @cfg {String/HTMLElement/Element} container
7087      * The id or element that will contain the toolbar
7088      */
7089     // private
7090     render : function(ct){
7091         this.el = Roo.get(ct);
7092         if(this.cls){
7093             this.el.addClass(this.cls);
7094         }
7095         // using a table allows for vertical alignment
7096         // 100% width is needed by Safari...
7097         this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>');
7098         this.tr = this.el.child("tr", true);
7099         var autoId = 0;
7100         this.items = new Roo.util.MixedCollection(false, function(o){
7101             return o.id || ("item" + (++autoId));
7102         });
7103         if(this.buttons){
7104             this.add.apply(this, this.buttons);
7105             delete this.buttons;
7106         }
7107     },
7108
7109     /**
7110      * Adds element(s) to the toolbar -- this function takes a variable number of 
7111      * arguments of mixed type and adds them to the toolbar.
7112      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
7113      * <ul>
7114      * <li>{@link Roo.Toolbar.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
7115      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
7116      * <li>Field: Any form field (equivalent to {@link #addField})</li>
7117      * <li>Item: Any subclass of {@link Roo.Toolbar.Item} (equivalent to {@link #addItem})</li>
7118      * <li>String: Any generic string (gets wrapped in a {@link Roo.Toolbar.TextItem}, equivalent to {@link #addText}).
7119      * Note that there are a few special strings that are treated differently as explained nRoo.</li>
7120      * <li>'separator' or '-': Creates a separator element (equivalent to {@link #addSeparator})</li>
7121      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
7122      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
7123      * </ul>
7124      * @param {Mixed} arg2
7125      * @param {Mixed} etc.
7126      */
7127     add : function(){
7128         var a = arguments, l = a.length;
7129         for(var i = 0; i < l; i++){
7130             this._add(a[i]);
7131         }
7132     },
7133     // private..
7134     _add : function(el) {
7135         
7136         if (el.xtype) {
7137             el = Roo.factory(el, typeof(Roo.Toolbar[el.xtype]) == 'undefined' ? Roo.form : Roo.Toolbar);
7138         }
7139         
7140         if (el.applyTo){ // some kind of form field
7141             return this.addField(el);
7142         } 
7143         if (el.render){ // some kind of Toolbar.Item
7144             return this.addItem(el);
7145         }
7146         if (typeof el == "string"){ // string
7147             if(el == "separator" || el == "-"){
7148                 return this.addSeparator();
7149             }
7150             if (el == " "){
7151                 return this.addSpacer();
7152             }
7153             if(el == "->"){
7154                 return this.addFill();
7155             }
7156             return this.addText(el);
7157             
7158         }
7159         if(el.tagName){ // element
7160             return this.addElement(el);
7161         }
7162         if(typeof el == "object"){ // must be button config?
7163             return this.addButton(el);
7164         }
7165         // and now what?!?!
7166         return false;
7167         
7168     },
7169     
7170     /**
7171      * Add an Xtype element
7172      * @param {Object} xtype Xtype Object
7173      * @return {Object} created Object
7174      */
7175     addxtype : function(e){
7176         return this.add(e);  
7177     },
7178     
7179     /**
7180      * Returns the Element for this toolbar.
7181      * @return {Roo.Element}
7182      */
7183     getEl : function(){
7184         return this.el;  
7185     },
7186     
7187     /**
7188      * Adds a separator
7189      * @return {Roo.Toolbar.Item} The separator item
7190      */
7191     addSeparator : function(){
7192         return this.addItem(new Roo.Toolbar.Separator());
7193     },
7194
7195     /**
7196      * Adds a spacer element
7197      * @return {Roo.Toolbar.Spacer} The spacer item
7198      */
7199     addSpacer : function(){
7200         return this.addItem(new Roo.Toolbar.Spacer());
7201     },
7202
7203     /**
7204      * Adds a fill element that forces subsequent additions to the right side of the toolbar
7205      * @return {Roo.Toolbar.Fill} The fill item
7206      */
7207     addFill : function(){
7208         return this.addItem(new Roo.Toolbar.Fill());
7209     },
7210
7211     /**
7212      * Adds any standard HTML element to the toolbar
7213      * @param {String/HTMLElement/Element} el The element or id of the element to add
7214      * @return {Roo.Toolbar.Item} The element's item
7215      */
7216     addElement : function(el){
7217         return this.addItem(new Roo.Toolbar.Item(el));
7218     },
7219     /**
7220      * Collection of items on the toolbar.. (only Toolbar Items, so use fields to retrieve fields)
7221      * @type Roo.util.MixedCollection  
7222      */
7223     items : false,
7224      
7225     /**
7226      * Adds any Toolbar.Item or subclass
7227      * @param {Roo.Toolbar.Item} item
7228      * @return {Roo.Toolbar.Item} The item
7229      */
7230     addItem : function(item){
7231         var td = this.nextBlock();
7232         item.render(td);
7233         this.items.add(item);
7234         return item;
7235     },
7236     
7237     /**
7238      * Adds a button (or buttons). See {@link Roo.Toolbar.Button} for more info on the config.
7239      * @param {Object/Array} config A button config or array of configs
7240      * @return {Roo.Toolbar.Button/Array}
7241      */
7242     addButton : function(config){
7243         if(config instanceof Array){
7244             var buttons = [];
7245             for(var i = 0, len = config.length; i < len; i++) {
7246                 buttons.push(this.addButton(config[i]));
7247             }
7248             return buttons;
7249         }
7250         var b = config;
7251         if(!(config instanceof Roo.Toolbar.Button)){
7252             b = config.split ?
7253                 new Roo.Toolbar.SplitButton(config) :
7254                 new Roo.Toolbar.Button(config);
7255         }
7256         var td = this.nextBlock();
7257         b.render(td);
7258         this.items.add(b);
7259         return b;
7260     },
7261     
7262     /**
7263      * Adds text to the toolbar
7264      * @param {String} text The text to add
7265      * @return {Roo.Toolbar.Item} The element's item
7266      */
7267     addText : function(text){
7268         return this.addItem(new Roo.Toolbar.TextItem(text));
7269     },
7270     
7271     /**
7272      * Inserts any {@link Roo.Toolbar.Item}/{@link Roo.Toolbar.Button} at the specified index.
7273      * @param {Number} index The index where the item is to be inserted
7274      * @param {Object/Roo.Toolbar.Item/Roo.Toolbar.Button (may be Array)} item The button, or button config object to be inserted.
7275      * @return {Roo.Toolbar.Button/Item}
7276      */
7277     insertButton : function(index, item){
7278         if(item instanceof Array){
7279             var buttons = [];
7280             for(var i = 0, len = item.length; i < len; i++) {
7281                buttons.push(this.insertButton(index + i, item[i]));
7282             }
7283             return buttons;
7284         }
7285         if (!(item instanceof Roo.Toolbar.Button)){
7286            item = new Roo.Toolbar.Button(item);
7287         }
7288         var td = document.createElement("td");
7289         this.tr.insertBefore(td, this.tr.childNodes[index]);
7290         item.render(td);
7291         this.items.insert(index, item);
7292         return item;
7293     },
7294     
7295     /**
7296      * Adds a new element to the toolbar from the passed {@link Roo.DomHelper} config.
7297      * @param {Object} config
7298      * @return {Roo.Toolbar.Item} The element's item
7299      */
7300     addDom : function(config, returnEl){
7301         var td = this.nextBlock();
7302         Roo.DomHelper.overwrite(td, config);
7303         var ti = new Roo.Toolbar.Item(td.firstChild);
7304         ti.render(td);
7305         this.items.add(ti);
7306         return ti;
7307     },
7308
7309     /**
7310      * Collection of fields on the toolbar.. usefull for quering (value is false if there are no fields)
7311      * @type Roo.util.MixedCollection  
7312      */
7313     fields : false,
7314     
7315     /**
7316      * Adds a dynamically rendered Roo.form field (TextField, ComboBox, etc).
7317      * Note: the field should not have been rendered yet. For a field that has already been
7318      * rendered, use {@link #addElement}.
7319      * @param {Roo.form.Field} field
7320      * @return {Roo.ToolbarItem}
7321      */
7322      
7323       
7324     addField : function(field) {
7325         if (!this.fields) {
7326             var autoId = 0;
7327             this.fields = new Roo.util.MixedCollection(false, function(o){
7328                 return o.id || ("item" + (++autoId));
7329             });
7330
7331         }
7332         
7333         var td = this.nextBlock();
7334         field.render(td);
7335         var ti = new Roo.Toolbar.Item(td.firstChild);
7336         ti.render(td);
7337         this.items.add(ti);
7338         this.fields.add(field);
7339         return ti;
7340     },
7341     /**
7342      * Hide the toolbar
7343      * @method hide
7344      */
7345      
7346       
7347     hide : function()
7348     {
7349         this.el.child('div').setVisibilityMode(Roo.Element.DISPLAY);
7350         this.el.child('div').hide();
7351     },
7352     /**
7353      * Show the toolbar
7354      * @method show
7355      */
7356     show : function()
7357     {
7358         this.el.child('div').show();
7359     },
7360       
7361     // private
7362     nextBlock : function(){
7363         var td = document.createElement("td");
7364         this.tr.appendChild(td);
7365         return td;
7366     },
7367
7368     // private
7369     destroy : function(){
7370         if(this.items){ // rendered?
7371             Roo.destroy.apply(Roo, this.items.items);
7372         }
7373         if(this.fields){ // rendered?
7374             Roo.destroy.apply(Roo, this.fields.items);
7375         }
7376         Roo.Element.uncache(this.el, this.tr);
7377     }
7378 };
7379
7380 /**
7381  * @class Roo.Toolbar.Item
7382  * The base class that other classes should extend in order to get some basic common toolbar item functionality.
7383  * @constructor
7384  * Creates a new Item
7385  * @param {HTMLElement} el 
7386  */
7387 Roo.Toolbar.Item = function(el){
7388     var cfg = {};
7389     if (typeof (el.xtype) != 'undefined') {
7390         cfg = el;
7391         el = cfg.el;
7392     }
7393     
7394     this.el = Roo.getDom(el);
7395     this.id = Roo.id(this.el);
7396     this.hidden = false;
7397     
7398     this.addEvents({
7399          /**
7400              * @event render
7401              * Fires when the button is rendered
7402              * @param {Button} this
7403              */
7404         'render': true
7405     });
7406     Roo.Toolbar.Item.superclass.constructor.call(this,cfg);
7407 };
7408 Roo.extend(Roo.Toolbar.Item, Roo.util.Observable, {
7409 //Roo.Toolbar.Item.prototype = {
7410     
7411     /**
7412      * Get this item's HTML Element
7413      * @return {HTMLElement}
7414      */
7415     getEl : function(){
7416        return this.el;  
7417     },
7418
7419     // private
7420     render : function(td){
7421         
7422          this.td = td;
7423         td.appendChild(this.el);
7424         
7425         this.fireEvent('render', this);
7426     },
7427     
7428     /**
7429      * Removes and destroys this item.
7430      */
7431     destroy : function(){
7432         this.td.parentNode.removeChild(this.td);
7433     },
7434     
7435     /**
7436      * Shows this item.
7437      */
7438     show: function(){
7439         this.hidden = false;
7440         this.td.style.display = "";
7441     },
7442     
7443     /**
7444      * Hides this item.
7445      */
7446     hide: function(){
7447         this.hidden = true;
7448         this.td.style.display = "none";
7449     },
7450     
7451     /**
7452      * Convenience function for boolean show/hide.
7453      * @param {Boolean} visible true to show/false to hide
7454      */
7455     setVisible: function(visible){
7456         if(visible) {
7457             this.show();
7458         }else{
7459             this.hide();
7460         }
7461     },
7462     
7463     /**
7464      * Try to focus this item.
7465      */
7466     focus : function(){
7467         Roo.fly(this.el).focus();
7468     },
7469     
7470     /**
7471      * Disables this item.
7472      */
7473     disable : function(){
7474         Roo.fly(this.td).addClass("x-item-disabled");
7475         this.disabled = true;
7476         this.el.disabled = true;
7477     },
7478     
7479     /**
7480      * Enables this item.
7481      */
7482     enable : function(){
7483         Roo.fly(this.td).removeClass("x-item-disabled");
7484         this.disabled = false;
7485         this.el.disabled = false;
7486     }
7487 });
7488
7489
7490 /**
7491  * @class Roo.Toolbar.Separator
7492  * @extends Roo.Toolbar.Item
7493  * A simple toolbar separator class
7494  * @constructor
7495  * Creates a new Separator
7496  */
7497 Roo.Toolbar.Separator = function(cfg){
7498     
7499     var s = document.createElement("span");
7500     s.className = "ytb-sep";
7501     if (cfg) {
7502         cfg.el = s;
7503     }
7504     
7505     Roo.Toolbar.Separator.superclass.constructor.call(this, cfg || s);
7506 };
7507 Roo.extend(Roo.Toolbar.Separator, Roo.Toolbar.Item, {
7508     enable:Roo.emptyFn,
7509     disable:Roo.emptyFn,
7510     focus:Roo.emptyFn
7511 });
7512
7513 /**
7514  * @class Roo.Toolbar.Spacer
7515  * @extends Roo.Toolbar.Item
7516  * A simple element that adds extra horizontal space to a toolbar.
7517  * @constructor
7518  * Creates a new Spacer
7519  */
7520 Roo.Toolbar.Spacer = function(cfg){
7521     var s = document.createElement("div");
7522     s.className = "ytb-spacer";
7523     if (cfg) {
7524         cfg.el = s;
7525     }
7526     Roo.Toolbar.Spacer.superclass.constructor.call(this, cfg || s);
7527 };
7528 Roo.extend(Roo.Toolbar.Spacer, Roo.Toolbar.Item, {
7529     enable:Roo.emptyFn,
7530     disable:Roo.emptyFn,
7531     focus:Roo.emptyFn
7532 });
7533
7534 /**
7535  * @class Roo.Toolbar.Fill
7536  * @extends Roo.Toolbar.Spacer
7537  * A simple element that adds a greedy (100% width) horizontal space to a toolbar.
7538  * @constructor
7539  * Creates a new Spacer
7540  */
7541 Roo.Toolbar.Fill = Roo.extend(Roo.Toolbar.Spacer, {
7542     // private
7543     render : function(td){
7544         td.style.width = '100%';
7545         Roo.Toolbar.Fill.superclass.render.call(this, td);
7546     }
7547 });
7548
7549 /**
7550  * @class Roo.Toolbar.TextItem
7551  * @extends Roo.Toolbar.Item
7552  * A simple class that renders text directly into a toolbar.
7553  * @constructor
7554  * Creates a new TextItem
7555  * @cfg {string} text 
7556  */
7557 Roo.Toolbar.TextItem = function(cfg){
7558     var  text = cfg || "";
7559     if (typeof(cfg) == 'object') {
7560         text = cfg.text || "";
7561     }  else {
7562         cfg = null;
7563     }
7564     var s = document.createElement("span");
7565     s.className = "ytb-text";
7566     s.innerHTML = text;
7567     if (cfg) {
7568         cfg.el  = s;
7569     }
7570     
7571     Roo.Toolbar.TextItem.superclass.constructor.call(this, cfg ||  s);
7572 };
7573 Roo.extend(Roo.Toolbar.TextItem, Roo.Toolbar.Item, {
7574     
7575      
7576     enable:Roo.emptyFn,
7577     disable:Roo.emptyFn,
7578     focus:Roo.emptyFn,
7579      /**
7580      * Shows this button
7581      */
7582     show: function(){
7583         this.hidden = false;
7584         this.el.style.display = "";
7585     },
7586     
7587     /**
7588      * Hides this button
7589      */
7590     hide: function(){
7591         this.hidden = true;
7592         this.el.style.display = "none";
7593     }
7594     
7595 });
7596
7597 /**
7598  * @class Roo.Toolbar.Button
7599  * @extends Roo.Button
7600  * A button that renders into a toolbar.
7601  * @constructor
7602  * Creates a new Button
7603  * @param {Object} config A standard {@link Roo.Button} config object
7604  */
7605 Roo.Toolbar.Button = function(config){
7606     Roo.Toolbar.Button.superclass.constructor.call(this, null, config);
7607 };
7608 Roo.extend(Roo.Toolbar.Button, Roo.Button,
7609 {
7610     
7611     
7612     render : function(td){
7613         this.td = td;
7614         Roo.Toolbar.Button.superclass.render.call(this, td);
7615     },
7616     
7617     /**
7618      * Removes and destroys this button
7619      */
7620     destroy : function(){
7621         Roo.Toolbar.Button.superclass.destroy.call(this);
7622         this.td.parentNode.removeChild(this.td);
7623     },
7624     
7625     /**
7626      * Shows this button
7627      */
7628     show: function(){
7629         this.hidden = false;
7630         this.td.style.display = "";
7631     },
7632     
7633     /**
7634      * Hides this button
7635      */
7636     hide: function(){
7637         this.hidden = true;
7638         this.td.style.display = "none";
7639     },
7640
7641     /**
7642      * Disables this item
7643      */
7644     disable : function(){
7645         Roo.fly(this.td).addClass("x-item-disabled");
7646         this.disabled = true;
7647     },
7648
7649     /**
7650      * Enables this item
7651      */
7652     enable : function(){
7653         Roo.fly(this.td).removeClass("x-item-disabled");
7654         this.disabled = false;
7655     }
7656 });
7657 // backwards compat
7658 Roo.ToolbarButton = Roo.Toolbar.Button;
7659
7660 /**
7661  * @class Roo.Toolbar.SplitButton
7662  * @extends Roo.SplitButton
7663  * A menu button that renders into a toolbar.
7664  * @constructor
7665  * Creates a new SplitButton
7666  * @param {Object} config A standard {@link Roo.SplitButton} config object
7667  */
7668 Roo.Toolbar.SplitButton = function(config){
7669     Roo.Toolbar.SplitButton.superclass.constructor.call(this, null, config);
7670 };
7671 Roo.extend(Roo.Toolbar.SplitButton, Roo.SplitButton, {
7672     render : function(td){
7673         this.td = td;
7674         Roo.Toolbar.SplitButton.superclass.render.call(this, td);
7675     },
7676     
7677     /**
7678      * Removes and destroys this button
7679      */
7680     destroy : function(){
7681         Roo.Toolbar.SplitButton.superclass.destroy.call(this);
7682         this.td.parentNode.removeChild(this.td);
7683     },
7684     
7685     /**
7686      * Shows this button
7687      */
7688     show: function(){
7689         this.hidden = false;
7690         this.td.style.display = "";
7691     },
7692     
7693     /**
7694      * Hides this button
7695      */
7696     hide: function(){
7697         this.hidden = true;
7698         this.td.style.display = "none";
7699     }
7700 });
7701
7702 // backwards compat
7703 Roo.Toolbar.MenuButton = Roo.Toolbar.SplitButton;/*
7704  * Based on:
7705  * Ext JS Library 1.1.1
7706  * Copyright(c) 2006-2007, Ext JS, LLC.
7707  *
7708  * Originally Released Under LGPL - original licence link has changed is not relivant.
7709  *
7710  * Fork - LGPL
7711  * <script type="text/javascript">
7712  */
7713  
7714 /**
7715  * @class Roo.PagingToolbar
7716  * @extends Roo.Toolbar
7717  * @children   Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field
7718  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
7719  * @constructor
7720  * Create a new PagingToolbar
7721  * @param {Object} config The config object
7722  */
7723 Roo.PagingToolbar = function(el, ds, config)
7724 {
7725     // old args format still supported... - xtype is prefered..
7726     if (typeof(el) == 'object' && el.xtype) {
7727         // created from xtype...
7728         config = el;
7729         ds = el.dataSource;
7730         el = config.container;
7731     }
7732     var items = [];
7733     if (config.items) {
7734         items = config.items;
7735         config.items = [];
7736     }
7737     
7738     Roo.PagingToolbar.superclass.constructor.call(this, el, null, config);
7739     this.ds = ds;
7740     this.cursor = 0;
7741     this.renderButtons(this.el);
7742     this.bind(ds);
7743     
7744     // supprot items array.
7745    
7746     Roo.each(items, function(e) {
7747         this.add(Roo.factory(e));
7748     },this);
7749     
7750 };
7751
7752 Roo.extend(Roo.PagingToolbar, Roo.Toolbar, {
7753    
7754     /**
7755      * @cfg {String/HTMLElement/Element} container
7756      * container The id or element that will contain the toolbar
7757      */
7758     /**
7759      * @cfg {Boolean} displayInfo
7760      * True to display the displayMsg (defaults to false)
7761      */
7762     
7763     
7764     /**
7765      * @cfg {Number} pageSize
7766      * The number of records to display per page (defaults to 20)
7767      */
7768     pageSize: 20,
7769     /**
7770      * @cfg {String} displayMsg
7771      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
7772      */
7773     displayMsg : 'Displaying {0} - {1} of {2}',
7774     /**
7775      * @cfg {String} emptyMsg
7776      * The message to display when no records are found (defaults to "No data to display")
7777      */
7778     emptyMsg : 'No data to display',
7779     /**
7780      * Customizable piece of the default paging text (defaults to "Page")
7781      * @type String
7782      */
7783     beforePageText : "Page",
7784     /**
7785      * Customizable piece of the default paging text (defaults to "of %0")
7786      * @type String
7787      */
7788     afterPageText : "of {0}",
7789     /**
7790      * Customizable piece of the default paging text (defaults to "First Page")
7791      * @type String
7792      */
7793     firstText : "First Page",
7794     /**
7795      * Customizable piece of the default paging text (defaults to "Previous Page")
7796      * @type String
7797      */
7798     prevText : "Previous Page",
7799     /**
7800      * Customizable piece of the default paging text (defaults to "Next Page")
7801      * @type String
7802      */
7803     nextText : "Next Page",
7804     /**
7805      * Customizable piece of the default paging text (defaults to "Last Page")
7806      * @type String
7807      */
7808     lastText : "Last Page",
7809     /**
7810      * Customizable piece of the default paging text (defaults to "Refresh")
7811      * @type String
7812      */
7813     refreshText : "Refresh",
7814
7815     // private
7816     renderButtons : function(el){
7817         Roo.PagingToolbar.superclass.render.call(this, el);
7818         this.first = this.addButton({
7819             tooltip: this.firstText,
7820             cls: "x-btn-icon x-grid-page-first",
7821             disabled: true,
7822             handler: this.onClick.createDelegate(this, ["first"])
7823         });
7824         this.prev = this.addButton({
7825             tooltip: this.prevText,
7826             cls: "x-btn-icon x-grid-page-prev",
7827             disabled: true,
7828             handler: this.onClick.createDelegate(this, ["prev"])
7829         });
7830         //this.addSeparator();
7831         this.add(this.beforePageText);
7832         this.field = Roo.get(this.addDom({
7833            tag: "input",
7834            type: "text",
7835            size: "3",
7836            value: "1",
7837            cls: "x-grid-page-number"
7838         }).el);
7839         this.field.on("keydown", this.onPagingKeydown, this);
7840         this.field.on("focus", function(){this.dom.select();});
7841         this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
7842         this.field.setHeight(18);
7843         //this.addSeparator();
7844         this.next = this.addButton({
7845             tooltip: this.nextText,
7846             cls: "x-btn-icon x-grid-page-next",
7847             disabled: true,
7848             handler: this.onClick.createDelegate(this, ["next"])
7849         });
7850         this.last = this.addButton({
7851             tooltip: this.lastText,
7852             cls: "x-btn-icon x-grid-page-last",
7853             disabled: true,
7854             handler: this.onClick.createDelegate(this, ["last"])
7855         });
7856         //this.addSeparator();
7857         this.loading = this.addButton({
7858             tooltip: this.refreshText,
7859             cls: "x-btn-icon x-grid-loading",
7860             handler: this.onClick.createDelegate(this, ["refresh"])
7861         });
7862
7863         if(this.displayInfo){
7864             this.displayEl = Roo.fly(this.el.dom.firstChild).createChild({cls:'x-paging-info'});
7865         }
7866     },
7867
7868     // private
7869     updateInfo : function(){
7870         if(this.displayEl){
7871             var count = this.ds.getCount();
7872             var msg = count == 0 ?
7873                 this.emptyMsg :
7874                 String.format(
7875                     this.displayMsg,
7876                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
7877                 );
7878             this.displayEl.update(msg);
7879         }
7880     },
7881
7882     // private
7883     onLoad : function(ds, r, o){
7884        this.cursor = o.params ? o.params.start : 0;
7885        var d = this.getPageData(), ap = d.activePage, ps = d.pages;
7886
7887        this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
7888        this.field.dom.value = ap;
7889        this.first.setDisabled(ap == 1);
7890        this.prev.setDisabled(ap == 1);
7891        this.next.setDisabled(ap == ps);
7892        this.last.setDisabled(ap == ps);
7893        this.loading.enable();
7894        this.updateInfo();
7895     },
7896
7897     // private
7898     getPageData : function(){
7899         var total = this.ds.getTotalCount();
7900         return {
7901             total : total,
7902             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
7903             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
7904         };
7905     },
7906
7907     // private
7908     onLoadError : function(){
7909         this.loading.enable();
7910     },
7911
7912     // private
7913     onPagingKeydown : function(e){
7914         var k = e.getKey();
7915         var d = this.getPageData();
7916         if(k == e.RETURN){
7917             var v = this.field.dom.value, pageNum;
7918             if(!v || isNaN(pageNum = parseInt(v, 10))){
7919                 this.field.dom.value = d.activePage;
7920                 return;
7921             }
7922             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
7923             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
7924             e.stopEvent();
7925         }
7926         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))
7927         {
7928           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
7929           this.field.dom.value = pageNum;
7930           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
7931           e.stopEvent();
7932         }
7933         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
7934         {
7935           var v = this.field.dom.value, pageNum; 
7936           var increment = (e.shiftKey) ? 10 : 1;
7937           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
7938             increment *= -1;
7939           }
7940           if(!v || isNaN(pageNum = parseInt(v, 10))) {
7941             this.field.dom.value = d.activePage;
7942             return;
7943           }
7944           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
7945           {
7946             this.field.dom.value = parseInt(v, 10) + increment;
7947             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
7948             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
7949           }
7950           e.stopEvent();
7951         }
7952     },
7953
7954     // private
7955     beforeLoad : function(){
7956         if(this.loading){
7957             this.loading.disable();
7958         }
7959     },
7960     /**
7961      * event that occurs when you click on the navigation buttons - can be used to trigger load of a grid.
7962      * @param {String} which (first|prev|next|last|refresh)  which button to press.
7963      *
7964      */
7965     // private
7966     onClick : function(which){
7967         var ds = this.ds;
7968         switch(which){
7969             case "first":
7970                 ds.load({params:{start: 0, limit: this.pageSize}});
7971             break;
7972             case "prev":
7973                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
7974             break;
7975             case "next":
7976                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
7977             break;
7978             case "last":
7979                 var total = ds.getTotalCount();
7980                 var extra = total % this.pageSize;
7981                 var lastStart = extra ? (total - extra) : total-this.pageSize;
7982                 ds.load({params:{start: lastStart, limit: this.pageSize}});
7983             break;
7984             case "refresh":
7985                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
7986             break;
7987         }
7988     },
7989
7990     /**
7991      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
7992      * @param {Roo.data.Store} store The data store to unbind
7993      */
7994     unbind : function(ds){
7995         ds.un("beforeload", this.beforeLoad, this);
7996         ds.un("load", this.onLoad, this);
7997         ds.un("loadexception", this.onLoadError, this);
7998         ds.un("remove", this.updateInfo, this);
7999         ds.un("add", this.updateInfo, this);
8000         this.ds = undefined;
8001     },
8002
8003     /**
8004      * Binds the paging toolbar to the specified {@link Roo.data.Store}
8005      * @param {Roo.data.Store} store The data store to bind
8006      */
8007     bind : function(ds){
8008         ds.on("beforeload", this.beforeLoad, this);
8009         ds.on("load", this.onLoad, this);
8010         ds.on("loadexception", this.onLoadError, this);
8011         ds.on("remove", this.updateInfo, this);
8012         ds.on("add", this.updateInfo, this);
8013         this.ds = ds;
8014     }
8015 });/*
8016  * Based on:
8017  * Ext JS Library 1.1.1
8018  * Copyright(c) 2006-2007, Ext JS, LLC.
8019  *
8020  * Originally Released Under LGPL - original licence link has changed is not relivant.
8021  *
8022  * Fork - LGPL
8023  * <script type="text/javascript">
8024  */
8025
8026 /**
8027  * @class Roo.Resizable
8028  * @extends Roo.util.Observable
8029  * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
8030  * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
8031  * 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
8032  * the element will be wrapped for you automatically.</p>
8033  * <p>Here is the list of valid resize handles:</p>
8034  * <pre>
8035 Value   Description
8036 ------  -------------------
8037  'n'     north
8038  's'     south
8039  'e'     east
8040  'w'     west
8041  'nw'    northwest
8042  'sw'    southwest
8043  'se'    southeast
8044  'ne'    northeast
8045  'hd'    horizontal drag
8046  'all'   all
8047 </pre>
8048  * <p>Here's an example showing the creation of a typical Resizable:</p>
8049  * <pre><code>
8050 var resizer = new Roo.Resizable("element-id", {
8051     handles: 'all',
8052     minWidth: 200,
8053     minHeight: 100,
8054     maxWidth: 500,
8055     maxHeight: 400,
8056     pinned: true
8057 });
8058 resizer.on("resize", myHandler);
8059 </code></pre>
8060  * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
8061  * resizer.east.setDisplayed(false);</p>
8062  * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
8063  * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
8064  * resize operation's new size (defaults to [0, 0])
8065  * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
8066  * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
8067  * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
8068  * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
8069  * @cfg {Boolean} enabled False to disable resizing (defaults to true)
8070  * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
8071  * @cfg {Number} width The width of the element in pixels (defaults to null)
8072  * @cfg {Number} height The height of the element in pixels (defaults to null)
8073  * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
8074  * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
8075  * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
8076  * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
8077  * @cfg {Boolean} multiDirectional <b>Deprecated</b>.  The old style of adding multi-direction resize handles, deprecated
8078  * in favor of the handles config option (defaults to false)
8079  * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
8080  * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
8081  * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
8082  * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
8083  * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
8084  * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
8085  * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
8086  * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
8087  * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
8088  * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
8089  * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
8090  * @constructor
8091  * Create a new resizable component
8092  * @param {String/HTMLElement/Roo.Element} el The id or element to resize
8093  * @param {Object} config configuration options
8094   */
8095 Roo.Resizable = function(el, config)
8096 {
8097     this.el = Roo.get(el);
8098
8099     if(config && config.wrap){
8100         config.resizeChild = this.el;
8101         this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
8102         this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
8103         this.el.setStyle("overflow", "hidden");
8104         this.el.setPositioning(config.resizeChild.getPositioning());
8105         config.resizeChild.clearPositioning();
8106         if(!config.width || !config.height){
8107             var csize = config.resizeChild.getSize();
8108             this.el.setSize(csize.width, csize.height);
8109         }
8110         if(config.pinned && !config.adjustments){
8111             config.adjustments = "auto";
8112         }
8113     }
8114
8115     this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
8116     this.proxy.unselectable();
8117     this.proxy.enableDisplayMode('block');
8118
8119     Roo.apply(this, config);
8120
8121     if(this.pinned){
8122         this.disableTrackOver = true;
8123         this.el.addClass("x-resizable-pinned");
8124     }
8125     // if the element isn't positioned, make it relative
8126     var position = this.el.getStyle("position");
8127     if(position != "absolute" && position != "fixed"){
8128         this.el.setStyle("position", "relative");
8129     }
8130     if(!this.handles){ // no handles passed, must be legacy style
8131         this.handles = 's,e,se';
8132         if(this.multiDirectional){
8133             this.handles += ',n,w';
8134         }
8135     }
8136     if(this.handles == "all"){
8137         this.handles = "n s e w ne nw se sw";
8138     }
8139     var hs = this.handles.split(/\s*?[,;]\s*?| /);
8140     var ps = Roo.Resizable.positions;
8141     for(var i = 0, len = hs.length; i < len; i++){
8142         if(hs[i] && ps[hs[i]]){
8143             var pos = ps[hs[i]];
8144             this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
8145         }
8146     }
8147     // legacy
8148     this.corner = this.southeast;
8149     
8150     // updateBox = the box can move..
8151     if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
8152         this.updateBox = true;
8153     }
8154
8155     this.activeHandle = null;
8156
8157     if(this.resizeChild){
8158         if(typeof this.resizeChild == "boolean"){
8159             this.resizeChild = Roo.get(this.el.dom.firstChild, true);
8160         }else{
8161             this.resizeChild = Roo.get(this.resizeChild, true);
8162         }
8163     }
8164     
8165     if(this.adjustments == "auto"){
8166         var rc = this.resizeChild;
8167         var hw = this.west, he = this.east, hn = this.north, hs = this.south;
8168         if(rc && (hw || hn)){
8169             rc.position("relative");
8170             rc.setLeft(hw ? hw.el.getWidth() : 0);
8171             rc.setTop(hn ? hn.el.getHeight() : 0);
8172         }
8173         this.adjustments = [
8174             (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
8175             (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
8176         ];
8177     }
8178
8179     if(this.draggable){
8180         this.dd = this.dynamic ?
8181             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
8182         this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
8183     }
8184
8185     // public events
8186     this.addEvents({
8187         /**
8188          * @event beforeresize
8189          * Fired before resize is allowed. Set enabled to false to cancel resize.
8190          * @param {Roo.Resizable} this
8191          * @param {Roo.EventObject} e The mousedown event
8192          */
8193         "beforeresize" : true,
8194         /**
8195          * @event resizing
8196          * Fired a resizing.
8197          * @param {Roo.Resizable} this
8198          * @param {Number} x The new x position
8199          * @param {Number} y The new y position
8200          * @param {Number} w The new w width
8201          * @param {Number} h The new h hight
8202          * @param {Roo.EventObject} e The mouseup event
8203          */
8204         "resizing" : true,
8205         /**
8206          * @event resize
8207          * Fired after a resize.
8208          * @param {Roo.Resizable} this
8209          * @param {Number} width The new width
8210          * @param {Number} height The new height
8211          * @param {Roo.EventObject} e The mouseup event
8212          */
8213         "resize" : true
8214     });
8215
8216     if(this.width !== null && this.height !== null){
8217         this.resizeTo(this.width, this.height);
8218     }else{
8219         this.updateChildSize();
8220     }
8221     if(Roo.isIE){
8222         this.el.dom.style.zoom = 1;
8223     }
8224     Roo.Resizable.superclass.constructor.call(this);
8225 };
8226
8227 Roo.extend(Roo.Resizable, Roo.util.Observable, {
8228         resizeChild : false,
8229         adjustments : [0, 0],
8230         minWidth : 5,
8231         minHeight : 5,
8232         maxWidth : 10000,
8233         maxHeight : 10000,
8234         enabled : true,
8235         animate : false,
8236         duration : .35,
8237         dynamic : false,
8238         handles : false,
8239         multiDirectional : false,
8240         disableTrackOver : false,
8241         easing : 'easeOutStrong',
8242         widthIncrement : 0,
8243         heightIncrement : 0,
8244         pinned : false,
8245         width : null,
8246         height : null,
8247         preserveRatio : false,
8248         transparent: false,
8249         minX: 0,
8250         minY: 0,
8251         draggable: false,
8252
8253         /**
8254          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
8255          */
8256         constrainTo: undefined,
8257         /**
8258          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
8259          */
8260         resizeRegion: undefined,
8261
8262
8263     /**
8264      * Perform a manual resize
8265      * @param {Number} width
8266      * @param {Number} height
8267      */
8268     resizeTo : function(width, height){
8269         this.el.setSize(width, height);
8270         this.updateChildSize();
8271         this.fireEvent("resize", this, width, height, null);
8272     },
8273
8274     // private
8275     startSizing : function(e, handle){
8276         this.fireEvent("beforeresize", this, e);
8277         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
8278
8279             if(!this.overlay){
8280                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
8281                 this.overlay.unselectable();
8282                 this.overlay.enableDisplayMode("block");
8283                 this.overlay.on("mousemove", this.onMouseMove, this);
8284                 this.overlay.on("mouseup", this.onMouseUp, this);
8285             }
8286             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
8287
8288             this.resizing = true;
8289             this.startBox = this.el.getBox();
8290             this.startPoint = e.getXY();
8291             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
8292                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
8293
8294             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
8295             this.overlay.show();
8296
8297             if(this.constrainTo) {
8298                 var ct = Roo.get(this.constrainTo);
8299                 this.resizeRegion = ct.getRegion().adjust(
8300                     ct.getFrameWidth('t'),
8301                     ct.getFrameWidth('l'),
8302                     -ct.getFrameWidth('b'),
8303                     -ct.getFrameWidth('r')
8304                 );
8305             }
8306
8307             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
8308             this.proxy.show();
8309             this.proxy.setBox(this.startBox);
8310             if(!this.dynamic){
8311                 this.proxy.setStyle('visibility', 'visible');
8312             }
8313         }
8314     },
8315
8316     // private
8317     onMouseDown : function(handle, e){
8318         if(this.enabled){
8319             e.stopEvent();
8320             this.activeHandle = handle;
8321             this.startSizing(e, handle);
8322         }
8323     },
8324
8325     // private
8326     onMouseUp : function(e){
8327         var size = this.resizeElement();
8328         this.resizing = false;
8329         this.handleOut();
8330         this.overlay.hide();
8331         this.proxy.hide();
8332         this.fireEvent("resize", this, size.width, size.height, e);
8333     },
8334
8335     // private
8336     updateChildSize : function(){
8337         
8338         if(this.resizeChild){
8339             var el = this.el;
8340             var child = this.resizeChild;
8341             var adj = this.adjustments;
8342             if(el.dom.offsetWidth){
8343                 var b = el.getSize(true);
8344                 child.setSize(b.width+adj[0], b.height+adj[1]);
8345             }
8346             // Second call here for IE
8347             // The first call enables instant resizing and
8348             // the second call corrects scroll bars if they
8349             // exist
8350             if(Roo.isIE){
8351                 setTimeout(function(){
8352                     if(el.dom.offsetWidth){
8353                         var b = el.getSize(true);
8354                         child.setSize(b.width+adj[0], b.height+adj[1]);
8355                     }
8356                 }, 10);
8357             }
8358         }
8359     },
8360
8361     // private
8362     snap : function(value, inc, min){
8363         if(!inc || !value) {
8364             return value;
8365         }
8366         var newValue = value;
8367         var m = value % inc;
8368         if(m > 0){
8369             if(m > (inc/2)){
8370                 newValue = value + (inc-m);
8371             }else{
8372                 newValue = value - m;
8373             }
8374         }
8375         return Math.max(min, newValue);
8376     },
8377
8378     // private
8379     resizeElement : function(){
8380         var box = this.proxy.getBox();
8381         if(this.updateBox){
8382             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
8383         }else{
8384             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
8385         }
8386         this.updateChildSize();
8387         if(!this.dynamic){
8388             this.proxy.hide();
8389         }
8390         return box;
8391     },
8392
8393     // private
8394     constrain : function(v, diff, m, mx){
8395         if(v - diff < m){
8396             diff = v - m;
8397         }else if(v - diff > mx){
8398             diff = mx - v;
8399         }
8400         return diff;
8401     },
8402
8403     // private
8404     onMouseMove : function(e){
8405         
8406         if(this.enabled){
8407             try{// try catch so if something goes wrong the user doesn't get hung
8408
8409             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
8410                 return;
8411             }
8412
8413             //var curXY = this.startPoint;
8414             var curSize = this.curSize || this.startBox;
8415             var x = this.startBox.x, y = this.startBox.y;
8416             var ox = x, oy = y;
8417             var w = curSize.width, h = curSize.height;
8418             var ow = w, oh = h;
8419             var mw = this.minWidth, mh = this.minHeight;
8420             var mxw = this.maxWidth, mxh = this.maxHeight;
8421             var wi = this.widthIncrement;
8422             var hi = this.heightIncrement;
8423
8424             var eventXY = e.getXY();
8425             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
8426             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
8427
8428             var pos = this.activeHandle.position;
8429
8430             switch(pos){
8431                 case "east":
8432                     w += diffX;
8433                     w = Math.min(Math.max(mw, w), mxw);
8434                     break;
8435              
8436                 case "south":
8437                     h += diffY;
8438                     h = Math.min(Math.max(mh, h), mxh);
8439                     break;
8440                 case "southeast":
8441                     w += diffX;
8442                     h += diffY;
8443                     w = Math.min(Math.max(mw, w), mxw);
8444                     h = Math.min(Math.max(mh, h), mxh);
8445                     break;
8446                 case "north":
8447                     diffY = this.constrain(h, diffY, mh, mxh);
8448                     y += diffY;
8449                     h -= diffY;
8450                     break;
8451                 case "hdrag":
8452                     
8453                     if (wi) {
8454                         var adiffX = Math.abs(diffX);
8455                         var sub = (adiffX % wi); // how much 
8456                         if (sub > (wi/2)) { // far enough to snap
8457                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
8458                         } else {
8459                             // remove difference.. 
8460                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
8461                         }
8462                     }
8463                     x += diffX;
8464                     x = Math.max(this.minX, x);
8465                     break;
8466                 case "west":
8467                     diffX = this.constrain(w, diffX, mw, mxw);
8468                     x += diffX;
8469                     w -= diffX;
8470                     break;
8471                 case "northeast":
8472                     w += diffX;
8473                     w = Math.min(Math.max(mw, w), mxw);
8474                     diffY = this.constrain(h, diffY, mh, mxh);
8475                     y += diffY;
8476                     h -= diffY;
8477                     break;
8478                 case "northwest":
8479                     diffX = this.constrain(w, diffX, mw, mxw);
8480                     diffY = this.constrain(h, diffY, mh, mxh);
8481                     y += diffY;
8482                     h -= diffY;
8483                     x += diffX;
8484                     w -= diffX;
8485                     break;
8486                case "southwest":
8487                     diffX = this.constrain(w, diffX, mw, mxw);
8488                     h += diffY;
8489                     h = Math.min(Math.max(mh, h), mxh);
8490                     x += diffX;
8491                     w -= diffX;
8492                     break;
8493             }
8494
8495             var sw = this.snap(w, wi, mw);
8496             var sh = this.snap(h, hi, mh);
8497             if(sw != w || sh != h){
8498                 switch(pos){
8499                     case "northeast":
8500                         y -= sh - h;
8501                     break;
8502                     case "north":
8503                         y -= sh - h;
8504                         break;
8505                     case "southwest":
8506                         x -= sw - w;
8507                     break;
8508                     case "west":
8509                         x -= sw - w;
8510                         break;
8511                     case "northwest":
8512                         x -= sw - w;
8513                         y -= sh - h;
8514                     break;
8515                 }
8516                 w = sw;
8517                 h = sh;
8518             }
8519
8520             if(this.preserveRatio){
8521                 switch(pos){
8522                     case "southeast":
8523                     case "east":
8524                         h = oh * (w/ow);
8525                         h = Math.min(Math.max(mh, h), mxh);
8526                         w = ow * (h/oh);
8527                        break;
8528                     case "south":
8529                         w = ow * (h/oh);
8530                         w = Math.min(Math.max(mw, w), mxw);
8531                         h = oh * (w/ow);
8532                         break;
8533                     case "northeast":
8534                         w = ow * (h/oh);
8535                         w = Math.min(Math.max(mw, w), mxw);
8536                         h = oh * (w/ow);
8537                     break;
8538                     case "north":
8539                         var tw = w;
8540                         w = ow * (h/oh);
8541                         w = Math.min(Math.max(mw, w), mxw);
8542                         h = oh * (w/ow);
8543                         x += (tw - w) / 2;
8544                         break;
8545                     case "southwest":
8546                         h = oh * (w/ow);
8547                         h = Math.min(Math.max(mh, h), mxh);
8548                         var tw = w;
8549                         w = ow * (h/oh);
8550                         x += tw - w;
8551                         break;
8552                     case "west":
8553                         var th = h;
8554                         h = oh * (w/ow);
8555                         h = Math.min(Math.max(mh, h), mxh);
8556                         y += (th - h) / 2;
8557                         var tw = w;
8558                         w = ow * (h/oh);
8559                         x += tw - w;
8560                        break;
8561                     case "northwest":
8562                         var tw = w;
8563                         var th = h;
8564                         h = oh * (w/ow);
8565                         h = Math.min(Math.max(mh, h), mxh);
8566                         w = ow * (h/oh);
8567                         y += th - h;
8568                         x += tw - w;
8569                        break;
8570
8571                 }
8572             }
8573             if (pos == 'hdrag') {
8574                 w = ow;
8575             }
8576             this.proxy.setBounds(x, y, w, h);
8577             if(this.dynamic){
8578                 this.resizeElement();
8579             }
8580             }catch(e){}
8581         }
8582         this.fireEvent("resizing", this, x, y, w, h, e);
8583     },
8584
8585     // private
8586     handleOver : function(){
8587         if(this.enabled){
8588             this.el.addClass("x-resizable-over");
8589         }
8590     },
8591
8592     // private
8593     handleOut : function(){
8594         if(!this.resizing){
8595             this.el.removeClass("x-resizable-over");
8596         }
8597     },
8598
8599     /**
8600      * Returns the element this component is bound to.
8601      * @return {Roo.Element}
8602      */
8603     getEl : function(){
8604         return this.el;
8605     },
8606
8607     /**
8608      * Returns the resizeChild element (or null).
8609      * @return {Roo.Element}
8610      */
8611     getResizeChild : function(){
8612         return this.resizeChild;
8613     },
8614     groupHandler : function()
8615     {
8616         
8617     },
8618     /**
8619      * Destroys this resizable. If the element was wrapped and
8620      * removeEl is not true then the element remains.
8621      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
8622      */
8623     destroy : function(removeEl){
8624         this.proxy.remove();
8625         if(this.overlay){
8626             this.overlay.removeAllListeners();
8627             this.overlay.remove();
8628         }
8629         var ps = Roo.Resizable.positions;
8630         for(var k in ps){
8631             if(typeof ps[k] != "function" && this[ps[k]]){
8632                 var h = this[ps[k]];
8633                 h.el.removeAllListeners();
8634                 h.el.remove();
8635             }
8636         }
8637         if(removeEl){
8638             this.el.update("");
8639             this.el.remove();
8640         }
8641     }
8642 });
8643
8644 // private
8645 // hash to map config positions to true positions
8646 Roo.Resizable.positions = {
8647     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
8648     hd: "hdrag"
8649 };
8650
8651 // private
8652 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
8653     if(!this.tpl){
8654         // only initialize the template if resizable is used
8655         var tpl = Roo.DomHelper.createTemplate(
8656             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
8657         );
8658         tpl.compile();
8659         Roo.Resizable.Handle.prototype.tpl = tpl;
8660     }
8661     this.position = pos;
8662     this.rz = rz;
8663     // show north drag fro topdra
8664     var handlepos = pos == 'hdrag' ? 'north' : pos;
8665     
8666     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
8667     if (pos == 'hdrag') {
8668         this.el.setStyle('cursor', 'pointer');
8669     }
8670     this.el.unselectable();
8671     if(transparent){
8672         this.el.setOpacity(0);
8673     }
8674     this.el.on("mousedown", this.onMouseDown, this);
8675     if(!disableTrackOver){
8676         this.el.on("mouseover", this.onMouseOver, this);
8677         this.el.on("mouseout", this.onMouseOut, this);
8678     }
8679 };
8680
8681 // private
8682 Roo.Resizable.Handle.prototype = {
8683     afterResize : function(rz){
8684         Roo.log('after?');
8685         // do nothing
8686     },
8687     // private
8688     onMouseDown : function(e){
8689         this.rz.onMouseDown(this, e);
8690     },
8691     // private
8692     onMouseOver : function(e){
8693         this.rz.handleOver(this, e);
8694     },
8695     // private
8696     onMouseOut : function(e){
8697         this.rz.handleOut(this, e);
8698     }
8699 };/*
8700  * Based on:
8701  * Ext JS Library 1.1.1
8702  * Copyright(c) 2006-2007, Ext JS, LLC.
8703  *
8704  * Originally Released Under LGPL - original licence link has changed is not relivant.
8705  *
8706  * Fork - LGPL
8707  * <script type="text/javascript">
8708  */
8709
8710 /**
8711  * @class Roo.Editor
8712  * @extends Roo.Component
8713  * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
8714  * @constructor
8715  * Create a new Editor
8716  * @param {Roo.form.Field} field The Field object (or descendant)
8717  * @param {Object} config The config object
8718  */
8719 Roo.Editor = function(field, config){
8720     Roo.Editor.superclass.constructor.call(this, config);
8721     this.field = field;
8722     this.addEvents({
8723         /**
8724              * @event beforestartedit
8725              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
8726              * false from the handler of this event.
8727              * @param {Editor} this
8728              * @param {Roo.Element} boundEl The underlying element bound to this editor
8729              * @param {Mixed} value The field value being set
8730              */
8731         "beforestartedit" : true,
8732         /**
8733              * @event startedit
8734              * Fires when this editor is displayed
8735              * @param {Roo.Element} boundEl The underlying element bound to this editor
8736              * @param {Mixed} value The starting field value
8737              */
8738         "startedit" : true,
8739         /**
8740              * @event beforecomplete
8741              * Fires after a change has been made to the field, but before the change is reflected in the underlying
8742              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
8743              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
8744              * event will not fire since no edit actually occurred.
8745              * @param {Editor} this
8746              * @param {Mixed} value The current field value
8747              * @param {Mixed} startValue The original field value
8748              */
8749         "beforecomplete" : true,
8750         /**
8751              * @event complete
8752              * Fires after editing is complete and any changed value has been written to the underlying field.
8753              * @param {Editor} this
8754              * @param {Mixed} value The current field value
8755              * @param {Mixed} startValue The original field value
8756              */
8757         "complete" : true,
8758         /**
8759          * @event specialkey
8760          * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
8761          * {@link Roo.EventObject#getKey} to determine which key was pressed.
8762          * @param {Roo.form.Field} this
8763          * @param {Roo.EventObject} e The event object
8764          */
8765         "specialkey" : true
8766     });
8767 };
8768
8769 Roo.extend(Roo.Editor, Roo.Component, {
8770     /**
8771      * @cfg {Boolean/String} autosize
8772      * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
8773      * or "height" to adopt the height only (defaults to false)
8774      */
8775     /**
8776      * @cfg {Boolean} revertInvalid
8777      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
8778      * validation fails (defaults to true)
8779      */
8780     /**
8781      * @cfg {Boolean} ignoreNoChange
8782      * True to skip the the edit completion process (no save, no events fired) if the user completes an edit and
8783      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
8784      * will never be ignored.
8785      */
8786     /**
8787      * @cfg {Boolean} hideEl
8788      * False to keep the bound element visible while the editor is displayed (defaults to true)
8789      */
8790     /**
8791      * @cfg {Mixed} value
8792      * The data value of the underlying field (defaults to "")
8793      */
8794     value : "",
8795     /**
8796      * @cfg {String} alignment
8797      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "c-c?").
8798      */
8799     alignment: "c-c?",
8800     /**
8801      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
8802      * for bottom-right shadow (defaults to "frame")
8803      */
8804     shadow : "frame",
8805     /**
8806      * @cfg {Boolean} constrain True to constrain the editor to the viewport
8807      */
8808     constrain : false,
8809     /**
8810      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed (defaults to false)
8811      */
8812     completeOnEnter : false,
8813     /**
8814      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed (defaults to false)
8815      */
8816     cancelOnEsc : false,
8817     /**
8818      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
8819      */
8820     updateEl : false,
8821
8822     // private
8823     onRender : function(ct, position){
8824         this.el = new Roo.Layer({
8825             shadow: this.shadow,
8826             cls: "x-editor",
8827             parentEl : ct,
8828             shim : this.shim,
8829             shadowOffset:4,
8830             id: this.id,
8831             constrain: this.constrain
8832         });
8833         this.el.setStyle("overflow", Roo.isGecko ? "auto" : "hidden");
8834         if(this.field.msgTarget != 'title'){
8835             this.field.msgTarget = 'qtip';
8836         }
8837         this.field.render(this.el);
8838         if(Roo.isGecko){
8839             this.field.el.dom.setAttribute('autocomplete', 'off');
8840         }
8841         this.field.on("specialkey", this.onSpecialKey, this);
8842         if(this.swallowKeys){
8843             this.field.el.swallowEvent(['keydown','keypress']);
8844         }
8845         this.field.show();
8846         this.field.on("blur", this.onBlur, this);
8847         if(this.field.grow){
8848             this.field.on("autosize", this.el.sync,  this.el, {delay:1});
8849         }
8850     },
8851
8852     onSpecialKey : function(field, e)
8853     {
8854         //Roo.log('editor onSpecialKey');
8855         if(this.completeOnEnter && e.getKey() == e.ENTER){
8856             e.stopEvent();
8857             this.completeEdit();
8858             return;
8859         }
8860         // do not fire special key otherwise it might hide close the editor...
8861         if(e.getKey() == e.ENTER){    
8862             return;
8863         }
8864         if(this.cancelOnEsc && e.getKey() == e.ESC){
8865             this.cancelEdit();
8866             return;
8867         } 
8868         this.fireEvent('specialkey', field, e);
8869     
8870     },
8871
8872     /**
8873      * Starts the editing process and shows the editor.
8874      * @param {String/HTMLElement/Element} el The element to edit
8875      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
8876       * to the innerHTML of el.
8877      */
8878     startEdit : function(el, value){
8879         if(this.editing){
8880             this.completeEdit();
8881         }
8882         this.boundEl = Roo.get(el);
8883         var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
8884         if(!this.rendered){
8885             this.render(this.parentEl || document.body);
8886         }
8887         if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
8888             return;
8889         }
8890         this.startValue = v;
8891         this.field.setValue(v);
8892         if(this.autoSize){
8893             var sz = this.boundEl.getSize();
8894             switch(this.autoSize){
8895                 case "width":
8896                 this.setSize(sz.width,  "");
8897                 break;
8898                 case "height":
8899                 this.setSize("",  sz.height);
8900                 break;
8901                 default:
8902                 this.setSize(sz.width,  sz.height);
8903             }
8904         }
8905         this.el.alignTo(this.boundEl, this.alignment);
8906         this.editing = true;
8907         if(Roo.QuickTips){
8908             Roo.QuickTips.disable();
8909         }
8910         this.show();
8911     },
8912
8913     /**
8914      * Sets the height and width of this editor.
8915      * @param {Number} width The new width
8916      * @param {Number} height The new height
8917      */
8918     setSize : function(w, h){
8919         this.field.setSize(w, h);
8920         if(this.el){
8921             this.el.sync();
8922         }
8923     },
8924
8925     /**
8926      * Realigns the editor to the bound field based on the current alignment config value.
8927      */
8928     realign : function(){
8929         this.el.alignTo(this.boundEl, this.alignment);
8930     },
8931
8932     /**
8933      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
8934      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
8935      */
8936     completeEdit : function(remainVisible){
8937         if(!this.editing){
8938             return;
8939         }
8940         var v = this.getValue();
8941         if(this.revertInvalid !== false && !this.field.isValid()){
8942             v = this.startValue;
8943             this.cancelEdit(true);
8944         }
8945         if(String(v) === String(this.startValue) && this.ignoreNoChange){
8946             this.editing = false;
8947             this.hide();
8948             return;
8949         }
8950         if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
8951             this.editing = false;
8952             if(this.updateEl && this.boundEl){
8953                 this.boundEl.update(v);
8954             }
8955             if(remainVisible !== true){
8956                 this.hide();
8957             }
8958             this.fireEvent("complete", this, v, this.startValue);
8959         }
8960     },
8961
8962     // private
8963     onShow : function(){
8964         this.el.show();
8965         if(this.hideEl !== false){
8966             this.boundEl.hide();
8967         }
8968         this.field.show();
8969         if(Roo.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
8970             this.fixIEFocus = true;
8971             this.deferredFocus.defer(50, this);
8972         }else{
8973             this.field.focus();
8974         }
8975         this.fireEvent("startedit", this.boundEl, this.startValue);
8976     },
8977
8978     deferredFocus : function(){
8979         if(this.editing){
8980             this.field.focus();
8981         }
8982     },
8983
8984     /**
8985      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
8986      * reverted to the original starting value.
8987      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
8988      * cancel (defaults to false)
8989      */
8990     cancelEdit : function(remainVisible){
8991         if(this.editing){
8992             this.setValue(this.startValue);
8993             if(remainVisible !== true){
8994                 this.hide();
8995             }
8996         }
8997     },
8998
8999     // private
9000     onBlur : function(){
9001         if(this.allowBlur !== true && this.editing){
9002             this.completeEdit();
9003         }
9004     },
9005
9006     // private
9007     onHide : function(){
9008         if(this.editing){
9009             this.completeEdit();
9010             return;
9011         }
9012         this.field.blur();
9013         if(this.field.collapse){
9014             this.field.collapse();
9015         }
9016         this.el.hide();
9017         if(this.hideEl !== false){
9018             this.boundEl.show();
9019         }
9020         if(Roo.QuickTips){
9021             Roo.QuickTips.enable();
9022         }
9023     },
9024
9025     /**
9026      * Sets the data value of the editor
9027      * @param {Mixed} value Any valid value supported by the underlying field
9028      */
9029     setValue : function(v){
9030         this.field.setValue(v);
9031     },
9032
9033     /**
9034      * Gets the data value of the editor
9035      * @return {Mixed} The data value
9036      */
9037     getValue : function(){
9038         return this.field.getValue();
9039     }
9040 });/*
9041  * Based on:
9042  * Ext JS Library 1.1.1
9043  * Copyright(c) 2006-2007, Ext JS, LLC.
9044  *
9045  * Originally Released Under LGPL - original licence link has changed is not relivant.
9046  *
9047  * Fork - LGPL
9048  * <script type="text/javascript">
9049  */
9050  
9051 /**
9052  * @class Roo.BasicDialog
9053  * @extends Roo.util.Observable
9054  * @parent none builder
9055  * Lightweight Dialog Class.  The code below shows the creation of a typical dialog using existing HTML markup:
9056  * <pre><code>
9057 var dlg = new Roo.BasicDialog("my-dlg", {
9058     height: 200,
9059     width: 300,
9060     minHeight: 100,
9061     minWidth: 150,
9062     modal: true,
9063     proxyDrag: true,
9064     shadow: true
9065 });
9066 dlg.addKeyListener(27, dlg.hide, dlg); // ESC can also close the dialog
9067 dlg.addButton('OK', dlg.hide, dlg);    // Could call a save function instead of hiding
9068 dlg.addButton('Cancel', dlg.hide, dlg);
9069 dlg.show();
9070 </code></pre>
9071   <b>A Dialog should always be a direct child of the body element.</b>
9072  * @cfg {Boolean/DomHelper} autoCreate True to auto create from scratch, or using a DomHelper Object (defaults to false)
9073  * @cfg {String} title Default text to display in the title bar (defaults to null)
9074  * @cfg {Number} width Width of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9075  * @cfg {Number} height Height of the dialog in pixels (can also be set via CSS).  Determined by browser if unspecified.
9076  * @cfg {Number} x The default left page coordinate of the dialog (defaults to center screen)
9077  * @cfg {Number} y The default top page coordinate of the dialog (defaults to center screen)
9078  * @cfg {String/Element} animateTarget Id or element from which the dialog should animate while opening
9079  * (defaults to null with no animation)
9080  * @cfg {Boolean} resizable False to disable manual dialog resizing (defaults to true)
9081  * @cfg {String} resizeHandles Which resize handles to display - see the {@link Roo.Resizable} handles config
9082  * property for valid values (defaults to 'all')
9083  * @cfg {Number} minHeight The minimum allowable height for a resizable dialog (defaults to 80)
9084  * @cfg {Number} minWidth The minimum allowable width for a resizable dialog (defaults to 200)
9085  * @cfg {Boolean} modal True to show the dialog modally, preventing user interaction with the rest of the page (defaults to false)
9086  * @cfg {Boolean} autoScroll True to allow the dialog body contents to overflow and display scrollbars (defaults to false)
9087  * @cfg {Boolean} closable False to remove the built-in top-right corner close button (defaults to true)
9088  * @cfg {Boolean} collapsible False to remove the built-in top-right corner collapse button (defaults to true)
9089  * @cfg {Boolean} constraintoviewport True to keep the dialog constrained within the visible viewport boundaries (defaults to true)
9090  * @cfg {Boolean} syncHeightBeforeShow True to cause the dimensions to be recalculated before the dialog is shown (defaults to false)
9091  * @cfg {Boolean} draggable False to disable dragging of the dialog within the viewport (defaults to true)
9092  * @cfg {Boolean} autoTabs If true, all elements with class 'x-dlg-tab' will get automatically converted to tabs (defaults to false)
9093  * @cfg {String} tabTag The tag name of tab elements, used when autoTabs = true (defaults to 'div')
9094  * @cfg {Boolean} proxyDrag True to drag a lightweight proxy element rather than the dialog itself, used when
9095  * draggable = true (defaults to false)
9096  * @cfg {Boolean} fixedcenter True to ensure that anytime the dialog is shown or resized it gets centered (defaults to false)
9097  * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
9098  * shadow (defaults to false)
9099  * @cfg {Number} shadowOffset The number of pixels to offset the shadow if displayed (defaults to 5)
9100  * @cfg {String} buttonAlign Valid values are "left," "center" and "right" (defaults to "right")
9101  * @cfg {Number} minButtonWidth Minimum width of all dialog buttons (defaults to 75)
9102  * @cfg {Array} buttons Array of buttons
9103  * @cfg {Boolean} shim True to create an iframe shim that prevents selects from showing through (defaults to false)
9104  * @constructor
9105  * Create a new BasicDialog.
9106  * @param {String/HTMLElement/Roo.Element} el The container element or DOM node, or its id
9107  * @param {Object} config Configuration options
9108  */
9109 Roo.BasicDialog = function(el, config){
9110     this.el = Roo.get(el);
9111     var dh = Roo.DomHelper;
9112     if(!this.el && config && config.autoCreate){
9113         if(typeof config.autoCreate == "object"){
9114             if(!config.autoCreate.id){
9115                 config.autoCreate.id = el;
9116             }
9117             this.el = dh.append(document.body,
9118                         config.autoCreate, true);
9119         }else{
9120             this.el = dh.append(document.body,
9121                         {tag: "div", id: el, style:'visibility:hidden;'}, true);
9122         }
9123     }
9124     el = this.el;
9125     el.setDisplayed(true);
9126     el.hide = this.hideAction;
9127     this.id = el.id;
9128     el.addClass("x-dlg");
9129
9130     Roo.apply(this, config);
9131
9132     this.proxy = el.createProxy("x-dlg-proxy");
9133     this.proxy.hide = this.hideAction;
9134     this.proxy.setOpacity(.5);
9135     this.proxy.hide();
9136
9137     if(config.width){
9138         el.setWidth(config.width);
9139     }
9140     if(config.height){
9141         el.setHeight(config.height);
9142     }
9143     this.size = el.getSize();
9144     if(typeof config.x != "undefined" && typeof config.y != "undefined"){
9145         this.xy = [config.x,config.y];
9146     }else{
9147         this.xy = el.getCenterXY(true);
9148     }
9149     /** The header element @type Roo.Element */
9150     this.header = el.child("> .x-dlg-hd");
9151     /** The body element @type Roo.Element */
9152     this.body = el.child("> .x-dlg-bd");
9153     /** The footer element @type Roo.Element */
9154     this.footer = el.child("> .x-dlg-ft");
9155
9156     if(!this.header){
9157         this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: "&#160;"}, this.body ? this.body.dom : null);
9158     }
9159     if(!this.body){
9160         this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
9161     }
9162
9163     this.header.unselectable();
9164     if(this.title){
9165         this.header.update(this.title);
9166     }
9167     // this element allows the dialog to be focused for keyboard event
9168     this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
9169     this.focusEl.swallowEvent("click", true);
9170
9171     this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
9172
9173     // wrap the body and footer for special rendering
9174     this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
9175     if(this.footer){
9176         this.bwrap.dom.appendChild(this.footer.dom);
9177     }
9178
9179     this.bg = this.el.createChild({
9180         tag: "div", cls:"x-dlg-bg",
9181         html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center">&#160;</div></div></div>'
9182     });
9183     this.centerBg = this.bg.child("div.x-dlg-bg-center");
9184
9185
9186     if(this.autoScroll !== false && !this.autoTabs){
9187         this.body.setStyle("overflow", "auto");
9188     }
9189
9190     this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
9191
9192     if(this.closable !== false){
9193         this.el.addClass("x-dlg-closable");
9194         this.close = this.toolbox.createChild({cls:"x-dlg-close"});
9195         this.close.on("click", this.closeClick, this);
9196         this.close.addClassOnOver("x-dlg-close-over");
9197     }
9198     if(this.collapsible !== false){
9199         this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
9200         this.collapseBtn.on("click", this.collapseClick, this);
9201         this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
9202         this.header.on("dblclick", this.collapseClick, this);
9203     }
9204     if(this.resizable !== false){
9205         this.el.addClass("x-dlg-resizable");
9206         this.resizer = new Roo.Resizable(el, {
9207             minWidth: this.minWidth || 80,
9208             minHeight:this.minHeight || 80,
9209             handles: this.resizeHandles || "all",
9210             pinned: true
9211         });
9212         this.resizer.on("beforeresize", this.beforeResize, this);
9213         this.resizer.on("resize", this.onResize, this);
9214     }
9215     if(this.draggable !== false){
9216         el.addClass("x-dlg-draggable");
9217         if (!this.proxyDrag) {
9218             var dd = new Roo.dd.DD(el.dom.id, "WindowDrag");
9219         }
9220         else {
9221             var dd = new Roo.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
9222         }
9223         dd.setHandleElId(this.header.id);
9224         dd.endDrag = this.endMove.createDelegate(this);
9225         dd.startDrag = this.startMove.createDelegate(this);
9226         dd.onDrag = this.onDrag.createDelegate(this);
9227         dd.scroll = false;
9228         this.dd = dd;
9229     }
9230     if(this.modal){
9231         this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
9232         this.mask.enableDisplayMode("block");
9233         this.mask.hide();
9234         this.el.addClass("x-dlg-modal");
9235     }
9236     if(this.shadow){
9237         this.shadow = new Roo.Shadow({
9238             mode : typeof this.shadow == "string" ? this.shadow : "sides",
9239             offset : this.shadowOffset
9240         });
9241     }else{
9242         this.shadowOffset = 0;
9243     }
9244     if(Roo.useShims && this.shim !== false){
9245         this.shim = this.el.createShim();
9246         this.shim.hide = this.hideAction;
9247         this.shim.hide();
9248     }else{
9249         this.shim = false;
9250     }
9251     if(this.autoTabs){
9252         this.initTabs();
9253     }
9254     if (this.buttons) { 
9255         var bts= this.buttons;
9256         this.buttons = [];
9257         Roo.each(bts, function(b) {
9258             this.addButton(b);
9259         }, this);
9260     }
9261     
9262     
9263     this.addEvents({
9264         /**
9265          * @event keydown
9266          * Fires when a key is pressed
9267          * @param {Roo.BasicDialog} this
9268          * @param {Roo.EventObject} e
9269          */
9270         "keydown" : true,
9271         /**
9272          * @event move
9273          * Fires when this dialog is moved by the user.
9274          * @param {Roo.BasicDialog} this
9275          * @param {Number} x The new page X
9276          * @param {Number} y The new page Y
9277          */
9278         "move" : true,
9279         /**
9280          * @event resize
9281          * Fires when this dialog is resized by the user.
9282          * @param {Roo.BasicDialog} this
9283          * @param {Number} width The new width
9284          * @param {Number} height The new height
9285          */
9286         "resize" : true,
9287         /**
9288          * @event beforehide
9289          * Fires before this dialog is hidden.
9290          * @param {Roo.BasicDialog} this
9291          */
9292         "beforehide" : true,
9293         /**
9294          * @event hide
9295          * Fires when this dialog is hidden.
9296          * @param {Roo.BasicDialog} this
9297          */
9298         "hide" : true,
9299         /**
9300          * @event beforeshow
9301          * Fires before this dialog is shown.
9302          * @param {Roo.BasicDialog} this
9303          */
9304         "beforeshow" : true,
9305         /**
9306          * @event show
9307          * Fires when this dialog is shown.
9308          * @param {Roo.BasicDialog} this
9309          */
9310         "show" : true
9311     });
9312     el.on("keydown", this.onKeyDown, this);
9313     el.on("mousedown", this.toFront, this);
9314     Roo.EventManager.onWindowResize(this.adjustViewport, this, true);
9315     this.el.hide();
9316     Roo.DialogManager.register(this);
9317     Roo.BasicDialog.superclass.constructor.call(this);
9318 };
9319
9320 Roo.extend(Roo.BasicDialog, Roo.util.Observable, {
9321     shadowOffset: Roo.isIE ? 6 : 5,
9322     minHeight: 80,
9323     minWidth: 200,
9324     minButtonWidth: 75,
9325     defaultButton: null,
9326     buttonAlign: "right",
9327     tabTag: 'div',
9328     firstShow: true,
9329
9330     /**
9331      * Sets the dialog title text
9332      * @param {String} text The title text to display
9333      * @return {Roo.BasicDialog} this
9334      */
9335     setTitle : function(text){
9336         this.header.update(text);
9337         return this;
9338     },
9339
9340     // private
9341     closeClick : function(){
9342         this.hide();
9343     },
9344
9345     // private
9346     collapseClick : function(){
9347         this[this.collapsed ? "expand" : "collapse"]();
9348     },
9349
9350     /**
9351      * Collapses the dialog to its minimized state (only the title bar is visible).
9352      * Equivalent to the user clicking the collapse dialog button.
9353      */
9354     collapse : function(){
9355         if(!this.collapsed){
9356             this.collapsed = true;
9357             this.el.addClass("x-dlg-collapsed");
9358             this.restoreHeight = this.el.getHeight();
9359             this.resizeTo(this.el.getWidth(), this.header.getHeight());
9360         }
9361     },
9362
9363     /**
9364      * Expands a collapsed dialog back to its normal state.  Equivalent to the user
9365      * clicking the expand dialog button.
9366      */
9367     expand : function(){
9368         if(this.collapsed){
9369             this.collapsed = false;
9370             this.el.removeClass("x-dlg-collapsed");
9371             this.resizeTo(this.el.getWidth(), this.restoreHeight);
9372         }
9373     },
9374
9375     /**
9376      * Reinitializes the tabs component, clearing out old tabs and finding new ones.
9377      * @return {Roo.TabPanel} The tabs component
9378      */
9379     initTabs : function(){
9380         var tabs = this.getTabs();
9381         while(tabs.getTab(0)){
9382             tabs.removeTab(0);
9383         }
9384         this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
9385             var dom = el.dom;
9386             tabs.addTab(Roo.id(dom), dom.title);
9387             dom.title = "";
9388         });
9389         tabs.activate(0);
9390         return tabs;
9391     },
9392
9393     // private
9394     beforeResize : function(){
9395         this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
9396     },
9397
9398     // private
9399     onResize : function(){
9400         this.refreshSize();
9401         this.syncBodyHeight();
9402         this.adjustAssets();
9403         this.focus();
9404         this.fireEvent("resize", this, this.size.width, this.size.height);
9405     },
9406
9407     // private
9408     onKeyDown : function(e){
9409         if(this.isVisible()){
9410             this.fireEvent("keydown", this, e);
9411         }
9412     },
9413
9414     /**
9415      * Resizes the dialog.
9416      * @param {Number} width
9417      * @param {Number} height
9418      * @return {Roo.BasicDialog} this
9419      */
9420     resizeTo : function(width, height){
9421         this.el.setSize(width, height);
9422         this.size = {width: width, height: height};
9423         this.syncBodyHeight();
9424         if(this.fixedcenter){
9425             this.center();
9426         }
9427         if(this.isVisible()){
9428             this.constrainXY();
9429             this.adjustAssets();
9430         }
9431         this.fireEvent("resize", this, width, height);
9432         return this;
9433     },
9434
9435
9436     /**
9437      * Resizes the dialog to fit the specified content size.
9438      * @param {Number} width
9439      * @param {Number} height
9440      * @return {Roo.BasicDialog} this
9441      */
9442     setContentSize : function(w, h){
9443         h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
9444         w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
9445         //if(!this.el.isBorderBox()){
9446             h +=  this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
9447             w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
9448         //}
9449         if(this.tabs){
9450             h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
9451             w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
9452         }
9453         this.resizeTo(w, h);
9454         return this;
9455     },
9456
9457     /**
9458      * Adds a key listener for when this dialog is displayed.  This allows you to hook in a function that will be
9459      * executed in response to a particular key being pressed while the dialog is active.
9460      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the following options:
9461      *                                  {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9462      * @param {Function} fn The function to call
9463      * @param {Object} scope (optional) The scope of the function
9464      * @return {Roo.BasicDialog} this
9465      */
9466     addKeyListener : function(key, fn, scope){
9467         var keyCode, shift, ctrl, alt;
9468         if(typeof key == "object" && !(key instanceof Array)){
9469             keyCode = key["key"];
9470             shift = key["shift"];
9471             ctrl = key["ctrl"];
9472             alt = key["alt"];
9473         }else{
9474             keyCode = key;
9475         }
9476         var handler = function(dlg, e){
9477             if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
9478                 var k = e.getKey();
9479                 if(keyCode instanceof Array){
9480                     for(var i = 0, len = keyCode.length; i < len; i++){
9481                         if(keyCode[i] == k){
9482                           fn.call(scope || window, dlg, k, e);
9483                           return;
9484                         }
9485                     }
9486                 }else{
9487                     if(k == keyCode){
9488                         fn.call(scope || window, dlg, k, e);
9489                     }
9490                 }
9491             }
9492         };
9493         this.on("keydown", handler);
9494         return this;
9495     },
9496
9497     /**
9498      * Returns the TabPanel component (creates it if it doesn't exist).
9499      * Note: If you wish to simply check for the existence of tabs without creating them,
9500      * check for a null 'tabs' property.
9501      * @return {Roo.TabPanel} The tabs component
9502      */
9503     getTabs : function(){
9504         if(!this.tabs){
9505             this.el.addClass("x-dlg-auto-tabs");
9506             this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
9507             this.tabs = new Roo.TabPanel(this.body.dom, this.tabPosition == "bottom");
9508         }
9509         return this.tabs;
9510     },
9511
9512     /**
9513      * Adds a button to the footer section of the dialog.
9514      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
9515      * object or a valid Roo.DomHelper element config
9516      * @param {Function} handler The function called when the button is clicked
9517      * @param {Object} scope (optional) The scope of the handler function (accepts position as a property)
9518      * @return {Roo.Button} The new button
9519      */
9520     addButton : function(config, handler, scope){
9521         var dh = Roo.DomHelper;
9522         if(!this.footer){
9523             this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
9524         }
9525         if(!this.btnContainer){
9526             var tb = this.footer.createChild({
9527
9528                 cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
9529                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
9530             }, null, true);
9531             this.btnContainer = tb.firstChild.firstChild.firstChild;
9532         }
9533         var bconfig = {
9534             handler: handler,
9535             scope: scope,
9536             minWidth: this.minButtonWidth,
9537             hideParent:true
9538         };
9539         if(typeof config == "string"){
9540             bconfig.text = config;
9541         }else{
9542             if(config.tag){
9543                 bconfig.dhconfig = config;
9544             }else{
9545                 Roo.apply(bconfig, config);
9546             }
9547         }
9548         var fc = false;
9549         if ((typeof(bconfig.position) != 'undefined') && bconfig.position < this.btnContainer.childNodes.length-1) {
9550             bconfig.position = Math.max(0, bconfig.position);
9551             fc = this.btnContainer.childNodes[bconfig.position];
9552         }
9553          
9554         var btn = new Roo.Button(
9555             fc ? 
9556                 this.btnContainer.insertBefore(document.createElement("td"),fc)
9557                 : this.btnContainer.appendChild(document.createElement("td")),
9558             //Roo.get(this.btnContainer).createChild( { tag: 'td'},  fc ),
9559             bconfig
9560         );
9561         this.syncBodyHeight();
9562         if(!this.buttons){
9563             /**
9564              * Array of all the buttons that have been added to this dialog via addButton
9565              * @type Array
9566              */
9567             this.buttons = [];
9568         }
9569         this.buttons.push(btn);
9570         return btn;
9571     },
9572
9573     /**
9574      * Sets the default button to be focused when the dialog is displayed.
9575      * @param {Roo.BasicDialog.Button} btn The button object returned by {@link #addButton}
9576      * @return {Roo.BasicDialog} this
9577      */
9578     setDefaultButton : function(btn){
9579         this.defaultButton = btn;
9580         return this;
9581     },
9582
9583     // private
9584     getHeaderFooterHeight : function(safe){
9585         var height = 0;
9586         if(this.header){
9587            height += this.header.getHeight();
9588         }
9589         if(this.footer){
9590            var fm = this.footer.getMargins();
9591             height += (this.footer.getHeight()+fm.top+fm.bottom);
9592         }
9593         height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
9594         height += this.centerBg.getPadding("tb");
9595         return height;
9596     },
9597
9598     // private
9599     syncBodyHeight : function()
9600     {
9601         var bd = this.body, // the text
9602             cb = this.centerBg, // wrapper around bottom.. but does not seem to be used..
9603             bw = this.bwrap;
9604         var height = this.size.height - this.getHeaderFooterHeight(false);
9605         bd.setHeight(height-bd.getMargins("tb"));
9606         var hh = this.header.getHeight();
9607         var h = this.size.height-hh;
9608         cb.setHeight(h);
9609         
9610         bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
9611         bw.setHeight(h-cb.getPadding("tb"));
9612         
9613         bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
9614         bd.setWidth(bw.getWidth(true));
9615         if(this.tabs){
9616             this.tabs.syncHeight();
9617             if(Roo.isIE){
9618                 this.tabs.el.repaint();
9619             }
9620         }
9621     },
9622
9623     /**
9624      * Restores the previous state of the dialog if Roo.state is configured.
9625      * @return {Roo.BasicDialog} this
9626      */
9627     restoreState : function(){
9628         var box = Roo.state.Manager.get(this.stateId || (this.el.id + "-state"));
9629         if(box && box.width){
9630             this.xy = [box.x, box.y];
9631             this.resizeTo(box.width, box.height);
9632         }
9633         return this;
9634     },
9635
9636     // private
9637     beforeShow : function(){
9638         this.expand();
9639         if(this.fixedcenter){
9640             this.xy = this.el.getCenterXY(true);
9641         }
9642         if(this.modal){
9643             Roo.get(document.body).addClass("x-body-masked");
9644             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
9645             this.mask.show();
9646         }
9647         this.constrainXY();
9648     },
9649
9650     // private
9651     animShow : function(){
9652         var b = Roo.get(this.animateTarget).getBox();
9653         this.proxy.setSize(b.width, b.height);
9654         this.proxy.setLocation(b.x, b.y);
9655         this.proxy.show();
9656         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
9657                     true, .35, this.showEl.createDelegate(this));
9658     },
9659
9660     /**
9661      * Shows the dialog.
9662      * @param {String/HTMLElement/Roo.Element} animateTarget (optional) Reset the animation target
9663      * @return {Roo.BasicDialog} this
9664      */
9665     show : function(animateTarget){
9666         if (this.fireEvent("beforeshow", this) === false){
9667             return;
9668         }
9669         if(this.syncHeightBeforeShow){
9670             this.syncBodyHeight();
9671         }else if(this.firstShow){
9672             this.firstShow = false;
9673             this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
9674         }
9675         this.animateTarget = animateTarget || this.animateTarget;
9676         if(!this.el.isVisible()){
9677             this.beforeShow();
9678             if(this.animateTarget && Roo.get(this.animateTarget)){
9679                 this.animShow();
9680             }else{
9681                 this.showEl();
9682             }
9683         }
9684         return this;
9685     },
9686
9687     // private
9688     showEl : function(){
9689         this.proxy.hide();
9690         this.el.setXY(this.xy);
9691         this.el.show();
9692         this.adjustAssets(true);
9693         this.toFront();
9694         this.focus();
9695         // IE peekaboo bug - fix found by Dave Fenwick
9696         if(Roo.isIE){
9697             this.el.repaint();
9698         }
9699         this.fireEvent("show", this);
9700     },
9701
9702     /**
9703      * Focuses the dialog.  If a defaultButton is set, it will receive focus, otherwise the
9704      * dialog itself will receive focus.
9705      */
9706     focus : function(){
9707         if(this.defaultButton){
9708             this.defaultButton.focus();
9709         }else{
9710             this.focusEl.focus();
9711         }
9712     },
9713
9714     // private
9715     constrainXY : function(){
9716         if(this.constraintoviewport !== false){
9717             if(!this.viewSize){
9718                 if(this.container){
9719                     var s = this.container.getSize();
9720                     this.viewSize = [s.width, s.height];
9721                 }else{
9722                     this.viewSize = [Roo.lib.Dom.getViewWidth(),Roo.lib.Dom.getViewHeight()];
9723                 }
9724             }
9725             var s = Roo.get(this.container||document).getScroll();
9726
9727             var x = this.xy[0], y = this.xy[1];
9728             var w = this.size.width, h = this.size.height;
9729             var vw = this.viewSize[0], vh = this.viewSize[1];
9730             // only move it if it needs it
9731             var moved = false;
9732             // first validate right/bottom
9733             if(x + w > vw+s.left){
9734                 x = vw - w;
9735                 moved = true;
9736             }
9737             if(y + h > vh+s.top){
9738                 y = vh - h;
9739                 moved = true;
9740             }
9741             // then make sure top/left isn't negative
9742             if(x < s.left){
9743                 x = s.left;
9744                 moved = true;
9745             }
9746             if(y < s.top){
9747                 y = s.top;
9748                 moved = true;
9749             }
9750             if(moved){
9751                 // cache xy
9752                 this.xy = [x, y];
9753                 if(this.isVisible()){
9754                     this.el.setLocation(x, y);
9755                     this.adjustAssets();
9756                 }
9757             }
9758         }
9759     },
9760
9761     // private
9762     onDrag : function(){
9763         if(!this.proxyDrag){
9764             this.xy = this.el.getXY();
9765             this.adjustAssets();
9766         }
9767     },
9768
9769     // private
9770     adjustAssets : function(doShow){
9771         var x = this.xy[0], y = this.xy[1];
9772         var w = this.size.width, h = this.size.height;
9773         if(doShow === true){
9774             if(this.shadow){
9775                 this.shadow.show(this.el);
9776             }
9777             if(this.shim){
9778                 this.shim.show();
9779             }
9780         }
9781         if(this.shadow && this.shadow.isVisible()){
9782             this.shadow.show(this.el);
9783         }
9784         if(this.shim && this.shim.isVisible()){
9785             this.shim.setBounds(x, y, w, h);
9786         }
9787     },
9788
9789     // private
9790     adjustViewport : function(w, h){
9791         if(!w || !h){
9792             w = Roo.lib.Dom.getViewWidth();
9793             h = Roo.lib.Dom.getViewHeight();
9794         }
9795         // cache the size
9796         this.viewSize = [w, h];
9797         if(this.modal && this.mask.isVisible()){
9798             this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
9799             this.mask.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
9800         }
9801         if(this.isVisible()){
9802             this.constrainXY();
9803         }
9804     },
9805
9806     /**
9807      * Destroys this dialog and all its supporting elements (including any tabs, shim,
9808      * shadow, proxy, mask, etc.)  Also removes all event listeners.
9809      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
9810      */
9811     destroy : function(removeEl){
9812         if(this.isVisible()){
9813             this.animateTarget = null;
9814             this.hide();
9815         }
9816         Roo.EventManager.removeResizeListener(this.adjustViewport, this);
9817         if(this.tabs){
9818             this.tabs.destroy(removeEl);
9819         }
9820         Roo.destroy(
9821              this.shim,
9822              this.proxy,
9823              this.resizer,
9824              this.close,
9825              this.mask
9826         );
9827         if(this.dd){
9828             this.dd.unreg();
9829         }
9830         if(this.buttons){
9831            for(var i = 0, len = this.buttons.length; i < len; i++){
9832                this.buttons[i].destroy();
9833            }
9834         }
9835         this.el.removeAllListeners();
9836         if(removeEl === true){
9837             this.el.update("");
9838             this.el.remove();
9839         }
9840         Roo.DialogManager.unregister(this);
9841     },
9842
9843     // private
9844     startMove : function(){
9845         if(this.proxyDrag){
9846             this.proxy.show();
9847         }
9848         if(this.constraintoviewport !== false){
9849             this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
9850         }
9851     },
9852
9853     // private
9854     endMove : function(){
9855         if(!this.proxyDrag){
9856             Roo.dd.DD.prototype.endDrag.apply(this.dd, arguments);
9857         }else{
9858             Roo.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
9859             this.proxy.hide();
9860         }
9861         this.refreshSize();
9862         this.adjustAssets();
9863         this.focus();
9864         this.fireEvent("move", this, this.xy[0], this.xy[1]);
9865     },
9866
9867     /**
9868      * Brings this dialog to the front of any other visible dialogs
9869      * @return {Roo.BasicDialog} this
9870      */
9871     toFront : function(){
9872         Roo.DialogManager.bringToFront(this);
9873         return this;
9874     },
9875
9876     /**
9877      * Sends this dialog to the back (under) of any other visible dialogs
9878      * @return {Roo.BasicDialog} this
9879      */
9880     toBack : function(){
9881         Roo.DialogManager.sendToBack(this);
9882         return this;
9883     },
9884
9885     /**
9886      * Centers this dialog in the viewport
9887      * @return {Roo.BasicDialog} this
9888      */
9889     center : function(){
9890         var xy = this.el.getCenterXY(true);
9891         this.moveTo(xy[0], xy[1]);
9892         return this;
9893     },
9894
9895     /**
9896      * Moves the dialog's top-left corner to the specified point
9897      * @param {Number} x
9898      * @param {Number} y
9899      * @return {Roo.BasicDialog} this
9900      */
9901     moveTo : function(x, y){
9902         this.xy = [x,y];
9903         if(this.isVisible()){
9904             this.el.setXY(this.xy);
9905             this.adjustAssets();
9906         }
9907         return this;
9908     },
9909
9910     /**
9911      * Aligns the dialog to the specified element
9912      * @param {String/HTMLElement/Roo.Element} element The element to align to.
9913      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details).
9914      * @param {Array} offsets (optional) Offset the positioning by [x, y]
9915      * @return {Roo.BasicDialog} this
9916      */
9917     alignTo : function(element, position, offsets){
9918         this.xy = this.el.getAlignToXY(element, position, offsets);
9919         if(this.isVisible()){
9920             this.el.setXY(this.xy);
9921             this.adjustAssets();
9922         }
9923         return this;
9924     },
9925
9926     /**
9927      * Anchors an element to another element and realigns it when the window is resized.
9928      * @param {String/HTMLElement/Roo.Element} element The element to align to.
9929      * @param {String} position The position to align to (see {@link Roo.Element#alignTo} for more details)
9930      * @param {Array} offsets (optional) Offset the positioning by [x, y]
9931      * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
9932      * is a number, it is used as the buffer delay (defaults to 50ms).
9933      * @return {Roo.BasicDialog} this
9934      */
9935     anchorTo : function(el, alignment, offsets, monitorScroll){
9936         var action = function(){
9937             this.alignTo(el, alignment, offsets);
9938         };
9939         Roo.EventManager.onWindowResize(action, this);
9940         var tm = typeof monitorScroll;
9941         if(tm != 'undefined'){
9942             Roo.EventManager.on(window, 'scroll', action, this,
9943                 {buffer: tm == 'number' ? monitorScroll : 50});
9944         }
9945         action.call(this);
9946         return this;
9947     },
9948
9949     /**
9950      * Returns true if the dialog is visible
9951      * @return {Boolean}
9952      */
9953     isVisible : function(){
9954         return this.el.isVisible();
9955     },
9956
9957     // private
9958     animHide : function(callback){
9959         var b = Roo.get(this.animateTarget).getBox();
9960         this.proxy.show();
9961         this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
9962         this.el.hide();
9963         this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
9964                     this.hideEl.createDelegate(this, [callback]));
9965     },
9966
9967     /**
9968      * Hides the dialog.
9969      * @param {Function} callback (optional) Function to call when the dialog is hidden
9970      * @return {Roo.BasicDialog} this
9971      */
9972     hide : function(callback){
9973         if (this.fireEvent("beforehide", this) === false){
9974             return;
9975         }
9976         if(this.shadow){
9977             this.shadow.hide();
9978         }
9979         if(this.shim) {
9980           this.shim.hide();
9981         }
9982         // sometimes animateTarget seems to get set.. causing problems...
9983         // this just double checks..
9984         if(this.animateTarget && Roo.get(this.animateTarget)) {
9985            this.animHide(callback);
9986         }else{
9987             this.el.hide();
9988             this.hideEl(callback);
9989         }
9990         return this;
9991     },
9992
9993     // private
9994     hideEl : function(callback){
9995         this.proxy.hide();
9996         if(this.modal){
9997             this.mask.hide();
9998             Roo.get(document.body).removeClass("x-body-masked");
9999         }
10000         this.fireEvent("hide", this);
10001         if(typeof callback == "function"){
10002             callback();
10003         }
10004     },
10005
10006     // private
10007     hideAction : function(){
10008         this.setLeft("-10000px");
10009         this.setTop("-10000px");
10010         this.setStyle("visibility", "hidden");
10011     },
10012
10013     // private
10014     refreshSize : function(){
10015         this.size = this.el.getSize();
10016         this.xy = this.el.getXY();
10017         Roo.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
10018     },
10019
10020     // private
10021     // z-index is managed by the DialogManager and may be overwritten at any time
10022     setZIndex : function(index){
10023         if(this.modal){
10024             this.mask.setStyle("z-index", index);
10025         }
10026         if(this.shim){
10027             this.shim.setStyle("z-index", ++index);
10028         }
10029         if(this.shadow){
10030             this.shadow.setZIndex(++index);
10031         }
10032         this.el.setStyle("z-index", ++index);
10033         if(this.proxy){
10034             this.proxy.setStyle("z-index", ++index);
10035         }
10036         if(this.resizer){
10037             this.resizer.proxy.setStyle("z-index", ++index);
10038         }
10039
10040         this.lastZIndex = index;
10041     },
10042
10043     /**
10044      * Returns the element for this dialog
10045      * @return {Roo.Element} The underlying dialog Element
10046      */
10047     getEl : function(){
10048         return this.el;
10049     }
10050 });
10051
10052 /**
10053  * @class Roo.DialogManager
10054  * Provides global access to BasicDialogs that have been created and
10055  * support for z-indexing (layering) multiple open dialogs.
10056  */
10057 Roo.DialogManager = function(){
10058     var list = {};
10059     var accessList = [];
10060     var front = null;
10061
10062     // private
10063     var sortDialogs = function(d1, d2){
10064         return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
10065     };
10066
10067     // private
10068     var orderDialogs = function(){
10069         accessList.sort(sortDialogs);
10070         var seed = Roo.DialogManager.zseed;
10071         for(var i = 0, len = accessList.length; i < len; i++){
10072             var dlg = accessList[i];
10073             if(dlg){
10074                 dlg.setZIndex(seed + (i*10));
10075             }
10076         }
10077     };
10078
10079     return {
10080         /**
10081          * The starting z-index for BasicDialogs (defaults to 9000)
10082          * @type Number The z-index value
10083          */
10084         zseed : 9000,
10085
10086         // private
10087         register : function(dlg){
10088             list[dlg.id] = dlg;
10089             accessList.push(dlg);
10090         },
10091
10092         // private
10093         unregister : function(dlg){
10094             delete list[dlg.id];
10095             var i=0;
10096             var len=0;
10097             if(!accessList.indexOf){
10098                 for(  i = 0, len = accessList.length; i < len; i++){
10099                     if(accessList[i] == dlg){
10100                         accessList.splice(i, 1);
10101                         return;
10102                     }
10103                 }
10104             }else{
10105                  i = accessList.indexOf(dlg);
10106                 if(i != -1){
10107                     accessList.splice(i, 1);
10108                 }
10109             }
10110         },
10111
10112         /**
10113          * Gets a registered dialog by id
10114          * @param {String/Object} id The id of the dialog or a dialog
10115          * @return {Roo.BasicDialog} this
10116          */
10117         get : function(id){
10118             return typeof id == "object" ? id : list[id];
10119         },
10120
10121         /**
10122          * Brings the specified dialog to the front
10123          * @param {String/Object} dlg The id of the dialog or a dialog
10124          * @return {Roo.BasicDialog} this
10125          */
10126         bringToFront : function(dlg){
10127             dlg = this.get(dlg);
10128             if(dlg != front){
10129                 front = dlg;
10130                 dlg._lastAccess = new Date().getTime();
10131                 orderDialogs();
10132             }
10133             return dlg;
10134         },
10135
10136         /**
10137          * Sends the specified dialog to the back
10138          * @param {String/Object} dlg The id of the dialog or a dialog
10139          * @return {Roo.BasicDialog} this
10140          */
10141         sendToBack : function(dlg){
10142             dlg = this.get(dlg);
10143             dlg._lastAccess = -(new Date().getTime());
10144             orderDialogs();
10145             return dlg;
10146         },
10147
10148         /**
10149          * Hides all dialogs
10150          */
10151         hideAll : function(){
10152             for(var id in list){
10153                 if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
10154                     list[id].hide();
10155                 }
10156             }
10157         }
10158     };
10159 }();
10160
10161 /**
10162  * @class Roo.LayoutDialog
10163  * @extends Roo.BasicDialog
10164  * @children Roo.ContentPanel
10165  * @parent builder none
10166  * Dialog which provides adjustments for working with a layout in a Dialog.
10167  * Add your necessary layout config options to the dialog's config.<br>
10168  * Example usage (including a nested layout):
10169  * <pre><code>
10170 if(!dialog){
10171     dialog = new Roo.LayoutDialog("download-dlg", {
10172         modal: true,
10173         width:600,
10174         height:450,
10175         shadow:true,
10176         minWidth:500,
10177         minHeight:350,
10178         autoTabs:true,
10179         proxyDrag:true,
10180         // layout config merges with the dialog config
10181         center:{
10182             tabPosition: "top",
10183             alwaysShowTabs: true
10184         }
10185     });
10186     dialog.addKeyListener(27, dialog.hide, dialog);
10187     dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
10188     dialog.addButton("Build It!", this.getDownload, this);
10189
10190     // we can even add nested layouts
10191     var innerLayout = new Roo.BorderLayout("dl-inner", {
10192         east: {
10193             initialSize: 200,
10194             autoScroll:true,
10195             split:true
10196         },
10197         center: {
10198             autoScroll:true
10199         }
10200     });
10201     innerLayout.beginUpdate();
10202     innerLayout.add("east", new Roo.ContentPanel("dl-details"));
10203     innerLayout.add("center", new Roo.ContentPanel("selection-panel"));
10204     innerLayout.endUpdate(true);
10205
10206     var layout = dialog.getLayout();
10207     layout.beginUpdate();
10208     layout.add("center", new Roo.ContentPanel("standard-panel",
10209                         {title: "Download the Source", fitToFrame:true}));
10210     layout.add("center", new Roo.NestedLayoutPanel(innerLayout,
10211                {title: "Build your own roo.js"}));
10212     layout.getRegion("center").showPanel(sp);
10213     layout.endUpdate();
10214 }
10215 </code></pre>
10216     * @constructor
10217     * @param {String/HTMLElement/Roo.Element} el The id of or container element, or config
10218     * @param {Object} config configuration options
10219   */
10220 Roo.LayoutDialog = function(el, cfg){
10221     
10222     var config=  cfg;
10223     if (typeof(cfg) == 'undefined') {
10224         config = Roo.apply({}, el);
10225         // not sure why we use documentElement here.. - it should always be body.
10226         // IE7 borks horribly if we use documentElement.
10227         // webkit also does not like documentElement - it creates a body element...
10228         el = Roo.get( document.body || document.documentElement ).createChild();
10229         //config.autoCreate = true;
10230     }
10231     
10232     
10233     config.autoTabs = false;
10234     Roo.LayoutDialog.superclass.constructor.call(this, el, config);
10235     this.body.setStyle({overflow:"hidden", position:"relative"});
10236     this.layout = new Roo.BorderLayout(this.body.dom, config);
10237     this.layout.monitorWindowResize = false;
10238     this.el.addClass("x-dlg-auto-layout");
10239     // fix case when center region overwrites center function
10240     this.center = Roo.BasicDialog.prototype.center;
10241     this.on("show", this.layout.layout, this.layout, true);
10242     if (config.items) {
10243         var xitems = config.items;
10244         delete config.items;
10245         Roo.each(xitems, this.addxtype, this);
10246     }
10247     
10248     
10249 };
10250 Roo.extend(Roo.LayoutDialog, Roo.BasicDialog, {
10251     
10252     
10253     /**
10254      * @cfg {Roo.LayoutRegion} east  
10255      */
10256     /**
10257      * @cfg {Roo.LayoutRegion} west
10258      */
10259     /**
10260      * @cfg {Roo.LayoutRegion} south
10261      */
10262     /**
10263      * @cfg {Roo.LayoutRegion} north
10264      */
10265     /**
10266      * @cfg {Roo.LayoutRegion} center
10267      */
10268     /**
10269      * @cfg {Roo.Button} buttons[]  Bottom buttons..
10270      */
10271     
10272     
10273     /**
10274      * Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
10275      * @deprecated
10276      */
10277     endUpdate : function(){
10278         this.layout.endUpdate();
10279     },
10280
10281     /**
10282      * Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
10283      *  @deprecated
10284      */
10285     beginUpdate : function(){
10286         this.layout.beginUpdate();
10287     },
10288
10289     /**
10290      * Get the BorderLayout for this dialog
10291      * @return {Roo.BorderLayout}
10292      */
10293     getLayout : function(){
10294         return this.layout;
10295     },
10296
10297     showEl : function(){
10298         Roo.LayoutDialog.superclass.showEl.apply(this, arguments);
10299         if(Roo.isIE7){
10300             this.layout.layout();
10301         }
10302     },
10303
10304     // private
10305     // Use the syncHeightBeforeShow config option to control this automatically
10306     syncBodyHeight : function(){
10307         Roo.LayoutDialog.superclass.syncBodyHeight.call(this);
10308         if(this.layout){this.layout.layout();}
10309     },
10310     
10311       /**
10312      * Add an xtype element (actually adds to the layout.)
10313      * @return {Object} xdata xtype object data.
10314      */
10315     
10316     addxtype : function(c) {
10317         return this.layout.addxtype(c);
10318     }
10319 });/*
10320  * Based on:
10321  * Ext JS Library 1.1.1
10322  * Copyright(c) 2006-2007, Ext JS, LLC.
10323  *
10324  * Originally Released Under LGPL - original licence link has changed is not relivant.
10325  *
10326  * Fork - LGPL
10327  * <script type="text/javascript">
10328  */
10329  
10330 /**
10331  * @class Roo.MessageBox
10332  * @static
10333  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
10334  * Example usage:
10335  *<pre><code>
10336 // Basic alert:
10337 Roo.Msg.alert('Status', 'Changes saved successfully.');
10338
10339 // Prompt for user data:
10340 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
10341     if (btn == 'ok'){
10342         // process text value...
10343     }
10344 });
10345
10346 // Show a dialog using config options:
10347 Roo.Msg.show({
10348    title:'Save Changes?',
10349    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
10350    buttons: Roo.Msg.YESNOCANCEL,
10351    fn: processResult,
10352    animEl: 'elId'
10353 });
10354 </code></pre>
10355  * @static
10356  */
10357 Roo.MessageBox = function(){
10358     var dlg, opt, mask, waitTimer;
10359     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
10360     var buttons, activeTextEl, bwidth;
10361
10362     // private
10363     var handleButton = function(button){
10364         dlg.hide();
10365         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
10366     };
10367
10368     // private
10369     var handleHide = function(){
10370         if(opt && opt.cls){
10371             dlg.el.removeClass(opt.cls);
10372         }
10373         if(waitTimer){
10374             Roo.TaskMgr.stop(waitTimer);
10375             waitTimer = null;
10376         }
10377     };
10378
10379     // private
10380     var updateButtons = function(b){
10381         var width = 0;
10382         if(!b){
10383             buttons["ok"].hide();
10384             buttons["cancel"].hide();
10385             buttons["yes"].hide();
10386             buttons["no"].hide();
10387             dlg.footer.dom.style.display = 'none';
10388             return width;
10389         }
10390         dlg.footer.dom.style.display = '';
10391         for(var k in buttons){
10392             if(typeof buttons[k] != "function"){
10393                 if(b[k]){
10394                     buttons[k].show();
10395                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.MessageBox.buttonText[k]);
10396                     width += buttons[k].el.getWidth()+15;
10397                 }else{
10398                     buttons[k].hide();
10399                 }
10400             }
10401         }
10402         return width;
10403     };
10404
10405     // private
10406     var handleEsc = function(d, k, e){
10407         if(opt && opt.closable !== false){
10408             dlg.hide();
10409         }
10410         if(e){
10411             e.stopEvent();
10412         }
10413     };
10414
10415     return {
10416         /**
10417          * Returns a reference to the underlying {@link Roo.BasicDialog} element
10418          * @return {Roo.BasicDialog} The BasicDialog element
10419          */
10420         getDialog : function(){
10421            if(!dlg){
10422                 dlg = new Roo.BasicDialog("x-msg-box", {
10423                     autoCreate : true,
10424                     shadow: true,
10425                     draggable: true,
10426                     resizable:false,
10427                     constraintoviewport:false,
10428                     fixedcenter:true,
10429                     collapsible : false,
10430                     shim:true,
10431                     modal: true,
10432                     width:400, height:100,
10433                     buttonAlign:"center",
10434                     closeClick : function(){
10435                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
10436                             handleButton("no");
10437                         }else{
10438                             handleButton("cancel");
10439                         }
10440                     }
10441                 });
10442               
10443                 dlg.on("hide", handleHide);
10444                 mask = dlg.mask;
10445                 dlg.addKeyListener(27, handleEsc);
10446                 buttons = {};
10447                 var bt = this.buttonText;
10448                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
10449                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
10450                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
10451                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
10452                 bodyEl = dlg.body.createChild({
10453
10454                     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>'
10455                 });
10456                 msgEl = bodyEl.dom.firstChild;
10457                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
10458                 textboxEl.enableDisplayMode();
10459                 textboxEl.addKeyListener([10,13], function(){
10460                     if(dlg.isVisible() && opt && opt.buttons){
10461                         if(opt.buttons.ok){
10462                             handleButton("ok");
10463                         }else if(opt.buttons.yes){
10464                             handleButton("yes");
10465                         }
10466                     }
10467                 });
10468                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
10469                 textareaEl.enableDisplayMode();
10470                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
10471                 progressEl.enableDisplayMode();
10472                 var pf = progressEl.dom.firstChild;
10473                 if (pf) {
10474                     pp = Roo.get(pf.firstChild);
10475                     pp.setHeight(pf.offsetHeight);
10476                 }
10477                 
10478             }
10479             return dlg;
10480         },
10481
10482         /**
10483          * Updates the message box body text
10484          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
10485          * the XHTML-compliant non-breaking space character '&amp;#160;')
10486          * @return {Roo.MessageBox} This message box
10487          */
10488         updateText : function(text){
10489             if(!dlg.isVisible() && !opt.width){
10490                 dlg.resizeTo(this.maxWidth, 100); // resize first so content is never clipped from previous shows
10491             }
10492             msgEl.innerHTML = text || '&#160;';
10493       
10494             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
10495             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
10496             var w = Math.max(
10497                     Math.min(opt.width || cw , this.maxWidth), 
10498                     Math.max(opt.minWidth || this.minWidth, bwidth)
10499             );
10500             if(opt.prompt){
10501                 activeTextEl.setWidth(w);
10502             }
10503             if(dlg.isVisible()){
10504                 dlg.fixedcenter = false;
10505             }
10506             // to big, make it scroll. = But as usual stupid IE does not support
10507             // !important..
10508             
10509             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
10510                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
10511                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
10512             } else {
10513                 bodyEl.dom.style.height = '';
10514                 bodyEl.dom.style.overflowY = '';
10515             }
10516             if (cw > w) {
10517                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
10518             } else {
10519                 bodyEl.dom.style.overflowX = '';
10520             }
10521             
10522             dlg.setContentSize(w, bodyEl.getHeight());
10523             if(dlg.isVisible()){
10524                 dlg.fixedcenter = true;
10525             }
10526             return this;
10527         },
10528
10529         /**
10530          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
10531          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
10532          * @param {Number} value Any number between 0 and 1 (e.g., .5)
10533          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
10534          * @return {Roo.MessageBox} This message box
10535          */
10536         updateProgress : function(value, text){
10537             if(text){
10538                 this.updateText(text);
10539             }
10540             if (pp) { // weird bug on my firefox - for some reason this is not defined
10541                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
10542             }
10543             return this;
10544         },        
10545
10546         /**
10547          * Returns true if the message box is currently displayed
10548          * @return {Boolean} True if the message box is visible, else false
10549          */
10550         isVisible : function(){
10551             return dlg && dlg.isVisible();  
10552         },
10553
10554         /**
10555          * Hides the message box if it is displayed
10556          */
10557         hide : function(){
10558             if(this.isVisible()){
10559                 dlg.hide();
10560             }  
10561         },
10562
10563         /**
10564          * Displays a new message box, or reinitializes an existing message box, based on the config options
10565          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
10566          * The following config object properties are supported:
10567          * <pre>
10568 Property    Type             Description
10569 ----------  ---------------  ------------------------------------------------------------------------------------
10570 animEl            String/Element   An id or Element from which the message box should animate as it opens and
10571                                    closes (defaults to undefined)
10572 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
10573                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
10574 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
10575                                    progress and wait dialogs will ignore this property and always hide the
10576                                    close button as they can only be closed programmatically.
10577 cls               String           A custom CSS class to apply to the message box element
10578 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
10579                                    displayed (defaults to 75)
10580 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
10581                                    function will be btn (the name of the button that was clicked, if applicable,
10582                                    e.g. "ok"), and text (the value of the active text field, if applicable).
10583                                    Progress and wait dialogs will ignore this option since they do not respond to
10584                                    user actions and can only be closed programmatically, so any required function
10585                                    should be called by the same code after it closes the dialog.
10586 icon              String           A CSS class that provides a background image to be used as an icon for
10587                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
10588 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
10589 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
10590 modal             Boolean          False to allow user interaction with the page while the message box is
10591                                    displayed (defaults to true)
10592 msg               String           A string that will replace the existing message box body text (defaults
10593                                    to the XHTML-compliant non-breaking space character '&#160;')
10594 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
10595 progress          Boolean          True to display a progress bar (defaults to false)
10596 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
10597 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
10598 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
10599 title             String           The title text
10600 value             String           The string value to set into the active textbox element if displayed
10601 wait              Boolean          True to display a progress bar (defaults to false)
10602 width             Number           The width of the dialog in pixels
10603 </pre>
10604          *
10605          * Example usage:
10606          * <pre><code>
10607 Roo.Msg.show({
10608    title: 'Address',
10609    msg: 'Please enter your address:',
10610    width: 300,
10611    buttons: Roo.MessageBox.OKCANCEL,
10612    multiline: true,
10613    fn: saveAddress,
10614    animEl: 'addAddressBtn'
10615 });
10616 </code></pre>
10617          * @param {Object} config Configuration options
10618          * @return {Roo.MessageBox} This message box
10619          */
10620         show : function(options)
10621         {
10622             
10623             // this causes nightmares if you show one dialog after another
10624             // especially on callbacks..
10625              
10626             if(this.isVisible()){
10627                 
10628                 this.hide();
10629                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
10630                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
10631                 Roo.log("New Dialog Message:" +  options.msg )
10632                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
10633                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
10634                 
10635             }
10636             var d = this.getDialog();
10637             opt = options;
10638             d.setTitle(opt.title || "&#160;");
10639             d.close.setDisplayed(opt.closable !== false);
10640             activeTextEl = textboxEl;
10641             opt.prompt = opt.prompt || (opt.multiline ? true : false);
10642             if(opt.prompt){
10643                 if(opt.multiline){
10644                     textboxEl.hide();
10645                     textareaEl.show();
10646                     textareaEl.setHeight(typeof opt.multiline == "number" ?
10647                         opt.multiline : this.defaultTextHeight);
10648                     activeTextEl = textareaEl;
10649                 }else{
10650                     textboxEl.show();
10651                     textareaEl.hide();
10652                 }
10653             }else{
10654                 textboxEl.hide();
10655                 textareaEl.hide();
10656             }
10657             progressEl.setDisplayed(opt.progress === true);
10658             this.updateProgress(0);
10659             activeTextEl.dom.value = opt.value || "";
10660             if(opt.prompt){
10661                 dlg.setDefaultButton(activeTextEl);
10662             }else{
10663                 var bs = opt.buttons;
10664                 var db = null;
10665                 if(bs && bs.ok){
10666                     db = buttons["ok"];
10667                 }else if(bs && bs.yes){
10668                     db = buttons["yes"];
10669                 }
10670                 dlg.setDefaultButton(db);
10671             }
10672             bwidth = updateButtons(opt.buttons);
10673             this.updateText(opt.msg);
10674             if(opt.cls){
10675                 d.el.addClass(opt.cls);
10676             }
10677             d.proxyDrag = opt.proxyDrag === true;
10678             d.modal = opt.modal !== false;
10679             d.mask = opt.modal !== false ? mask : false;
10680             if(!d.isVisible()){
10681                 // force it to the end of the z-index stack so it gets a cursor in FF
10682                 document.body.appendChild(dlg.el.dom);
10683                 d.animateTarget = null;
10684                 d.show(options.animEl);
10685             }
10686             dlg.toFront();
10687             return this;
10688         },
10689
10690         /**
10691          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
10692          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
10693          * and closing the message box when the process is complete.
10694          * @param {String} title The title bar text
10695          * @param {String} msg The message box body text
10696          * @return {Roo.MessageBox} This message box
10697          */
10698         progress : function(title, msg){
10699             this.show({
10700                 title : title,
10701                 msg : msg,
10702                 buttons: false,
10703                 progress:true,
10704                 closable:false,
10705                 minWidth: this.minProgressWidth,
10706                 modal : true
10707             });
10708             return this;
10709         },
10710
10711         /**
10712          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
10713          * If a callback function is passed it will be called after the user clicks the button, and the
10714          * id of the button that was clicked will be passed as the only parameter to the callback
10715          * (could also be the top-right close button).
10716          * @param {String} title The title bar text
10717          * @param {String} msg The message box body text
10718          * @param {Function} fn (optional) The callback function invoked after the message box is closed
10719          * @param {Object} scope (optional) The scope of the callback function
10720          * @return {Roo.MessageBox} This message box
10721          */
10722         alert : function(title, msg, fn, scope){
10723             this.show({
10724                 title : title,
10725                 msg : msg,
10726                 buttons: this.OK,
10727                 fn: fn,
10728                 scope : scope,
10729                 modal : true
10730             });
10731             return this;
10732         },
10733
10734         /**
10735          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
10736          * interaction while waiting for a long-running process to complete that does not have defined intervals.
10737          * You are responsible for closing the message box when the process is complete.
10738          * @param {String} msg The message box body text
10739          * @param {String} title (optional) The title bar text
10740          * @return {Roo.MessageBox} This message box
10741          */
10742         wait : function(msg, title){
10743             this.show({
10744                 title : title,
10745                 msg : msg,
10746                 buttons: false,
10747                 closable:false,
10748                 progress:true,
10749                 modal:true,
10750                 width:300,
10751                 wait:true
10752             });
10753             waitTimer = Roo.TaskMgr.start({
10754                 run: function(i){
10755                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
10756                 },
10757                 interval: 1000
10758             });
10759             return this;
10760         },
10761
10762         /**
10763          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
10764          * If a callback function is passed it will be called after the user clicks either button, and the id of the
10765          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
10766          * @param {String} title The title bar text
10767          * @param {String} msg The message box body text
10768          * @param {Function} fn (optional) The callback function invoked after the message box is closed
10769          * @param {Object} scope (optional) The scope of the callback function
10770          * @return {Roo.MessageBox} This message box
10771          */
10772         confirm : function(title, msg, fn, scope){
10773             this.show({
10774                 title : title,
10775                 msg : msg,
10776                 buttons: this.YESNO,
10777                 fn: fn,
10778                 scope : scope,
10779                 modal : true
10780             });
10781             return this;
10782         },
10783
10784         /**
10785          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
10786          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
10787          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
10788          * (could also be the top-right close button) and the text that was entered will be passed as the two
10789          * parameters to the callback.
10790          * @param {String} title The title bar text
10791          * @param {String} msg The message box body text
10792          * @param {Function} fn (optional) The callback function invoked after the message box is closed
10793          * @param {Object} scope (optional) The scope of the callback function
10794          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
10795          * property, or the height in pixels to create the textbox (defaults to false / single-line)
10796          * @return {Roo.MessageBox} This message box
10797          */
10798         prompt : function(title, msg, fn, scope, multiline){
10799             this.show({
10800                 title : title,
10801                 msg : msg,
10802                 buttons: this.OKCANCEL,
10803                 fn: fn,
10804                 minWidth:250,
10805                 scope : scope,
10806                 prompt:true,
10807                 multiline: multiline,
10808                 modal : true
10809             });
10810             return this;
10811         },
10812
10813         /**
10814          * Button config that displays a single OK button
10815          * @type Object
10816          */
10817         OK : {ok:true},
10818         /**
10819          * Button config that displays Yes and No buttons
10820          * @type Object
10821          */
10822         YESNO : {yes:true, no:true},
10823         /**
10824          * Button config that displays OK and Cancel buttons
10825          * @type Object
10826          */
10827         OKCANCEL : {ok:true, cancel:true},
10828         /**
10829          * Button config that displays Yes, No and Cancel buttons
10830          * @type Object
10831          */
10832         YESNOCANCEL : {yes:true, no:true, cancel:true},
10833
10834         /**
10835          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
10836          * @type Number
10837          */
10838         defaultTextHeight : 75,
10839         /**
10840          * The maximum width in pixels of the message box (defaults to 600)
10841          * @type Number
10842          */
10843         maxWidth : 600,
10844         /**
10845          * The minimum width in pixels of the message box (defaults to 100)
10846          * @type Number
10847          */
10848         minWidth : 100,
10849         /**
10850          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
10851          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
10852          * @type Number
10853          */
10854         minProgressWidth : 250,
10855         /**
10856          * An object containing the default button text strings that can be overriden for localized language support.
10857          * Supported properties are: ok, cancel, yes and no.
10858          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
10859          * @type Object
10860          */
10861         buttonText : {
10862             ok : "OK",
10863             cancel : "Cancel",
10864             yes : "Yes",
10865             no : "No"
10866         }
10867     };
10868 }();
10869
10870 /**
10871  * Shorthand for {@link Roo.MessageBox}
10872  */
10873 Roo.Msg = Roo.MessageBox;/*
10874  * Based on:
10875  * Ext JS Library 1.1.1
10876  * Copyright(c) 2006-2007, Ext JS, LLC.
10877  *
10878  * Originally Released Under LGPL - original licence link has changed is not relivant.
10879  *
10880  * Fork - LGPL
10881  * <script type="text/javascript">
10882  */
10883 /**
10884  * @class Roo.QuickTips
10885  * Provides attractive and customizable tooltips for any element.
10886  * @static
10887  */
10888 Roo.QuickTips = function(){
10889     var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight;
10890     var ce, bd, xy, dd;
10891     var visible = false, disabled = true, inited = false;
10892     var showProc = 1, hideProc = 1, dismissProc = 1, locks = [];
10893     
10894     var onOver = function(e){
10895         if(disabled){
10896             return;
10897         }
10898         var t = e.getTarget();
10899         if(!t || t.nodeType !== 1 || t == document || t == document.body){
10900             return;
10901         }
10902         if(ce && t == ce.el){
10903             clearTimeout(hideProc);
10904             return;
10905         }
10906         if(t && tagEls[t.id]){
10907             tagEls[t.id].el = t;
10908             showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]);
10909             return;
10910         }
10911         var ttp, et = Roo.fly(t);
10912         var ns = cfg.namespace;
10913         if(tm.interceptTitles && t.title){
10914             ttp = t.title;
10915             t.qtip = ttp;
10916             t.removeAttribute("title");
10917             e.preventDefault();
10918         }else{
10919             ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute) || et.getAttributeNS(cfg.alt_namespace, cfg.attribute) ;
10920         }
10921         if(ttp){
10922             showProc = show.defer(tm.showDelay, tm, [{
10923                 el: t, 
10924                 text: ttp.replace(/\\n/g,'<br/>'),
10925                 width: et.getAttributeNS(ns, cfg.width),
10926                 autoHide: et.getAttributeNS(ns, cfg.hide) != "user",
10927                 title: et.getAttributeNS(ns, cfg.title),
10928                     cls: et.getAttributeNS(ns, cfg.cls)
10929             }]);
10930         }
10931     };
10932     
10933     var onOut = function(e){
10934         clearTimeout(showProc);
10935         var t = e.getTarget();
10936         if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){
10937             hideProc = setTimeout(hide, tm.hideDelay);
10938         }
10939     };
10940     
10941     var onMove = function(e){
10942         if(disabled){
10943             return;
10944         }
10945         xy = e.getXY();
10946         xy[1] += 18;
10947         if(tm.trackMouse && ce){
10948             el.setXY(xy);
10949         }
10950     };
10951     
10952     var onDown = function(e){
10953         clearTimeout(showProc);
10954         clearTimeout(hideProc);
10955         if(!e.within(el)){
10956             if(tm.hideOnClick){
10957                 hide();
10958                 tm.disable();
10959                 tm.enable.defer(100, tm);
10960             }
10961         }
10962     };
10963     
10964     var getPad = function(){
10965         return 2;//bdLeft.getPadding('l')+bdRight.getPadding('r');
10966     };
10967
10968     var show = function(o){
10969         if(disabled){
10970             return;
10971         }
10972         clearTimeout(dismissProc);
10973         ce = o;
10974         if(removeCls){ // in case manually hidden
10975             el.removeClass(removeCls);
10976             removeCls = null;
10977         }
10978         if(ce.cls){
10979             el.addClass(ce.cls);
10980             removeCls = ce.cls;
10981         }
10982         if(ce.title){
10983             tipTitle.update(ce.title);
10984             tipTitle.show();
10985         }else{
10986             tipTitle.update('');
10987             tipTitle.hide();
10988         }
10989         el.dom.style.width  = tm.maxWidth+'px';
10990         //tipBody.dom.style.width = '';
10991         tipBodyText.update(o.text);
10992         var p = getPad(), w = ce.width;
10993         if(!w){
10994             var td = tipBodyText.dom;
10995             var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth);
10996             if(aw > tm.maxWidth){
10997                 w = tm.maxWidth;
10998             }else if(aw < tm.minWidth){
10999                 w = tm.minWidth;
11000             }else{
11001                 w = aw;
11002             }
11003         }
11004         //tipBody.setWidth(w);
11005         el.setWidth(parseInt(w, 10) + p);
11006         if(ce.autoHide === false){
11007             close.setDisplayed(true);
11008             if(dd){
11009                 dd.unlock();
11010             }
11011         }else{
11012             close.setDisplayed(false);
11013             if(dd){
11014                 dd.lock();
11015             }
11016         }
11017         if(xy){
11018             el.avoidY = xy[1]-18;
11019             el.setXY(xy);
11020         }
11021         if(tm.animate){
11022             el.setOpacity(.1);
11023             el.setStyle("visibility", "visible");
11024             el.fadeIn({callback: afterShow});
11025         }else{
11026             afterShow();
11027         }
11028     };
11029     
11030     var afterShow = function(){
11031         if(ce){
11032             el.show();
11033             esc.enable();
11034             if(tm.autoDismiss && ce.autoHide !== false){
11035                 dismissProc = setTimeout(hide, tm.autoDismissDelay);
11036             }
11037         }
11038     };
11039     
11040     var hide = function(noanim){
11041         clearTimeout(dismissProc);
11042         clearTimeout(hideProc);
11043         ce = null;
11044         if(el.isVisible()){
11045             esc.disable();
11046             if(noanim !== true && tm.animate){
11047                 el.fadeOut({callback: afterHide});
11048             }else{
11049                 afterHide();
11050             } 
11051         }
11052     };
11053     
11054     var afterHide = function(){
11055         el.hide();
11056         if(removeCls){
11057             el.removeClass(removeCls);
11058             removeCls = null;
11059         }
11060     };
11061     
11062     return {
11063         /**
11064         * @cfg {Number} minWidth
11065         * The minimum width of the quick tip (defaults to 40)
11066         */
11067        minWidth : 40,
11068         /**
11069         * @cfg {Number} maxWidth
11070         * The maximum width of the quick tip (defaults to 300)
11071         */
11072        maxWidth : 300,
11073         /**
11074         * @cfg {Boolean} interceptTitles
11075         * True to automatically use the element's DOM title value if available (defaults to false)
11076         */
11077        interceptTitles : false,
11078         /**
11079         * @cfg {Boolean} trackMouse
11080         * True to have the quick tip follow the mouse as it moves over the target element (defaults to false)
11081         */
11082        trackMouse : false,
11083         /**
11084         * @cfg {Boolean} hideOnClick
11085         * True to hide the quick tip if the user clicks anywhere in the document (defaults to true)
11086         */
11087        hideOnClick : true,
11088         /**
11089         * @cfg {Number} showDelay
11090         * Delay in milliseconds before the quick tip displays after the mouse enters the target element (defaults to 500)
11091         */
11092        showDelay : 500,
11093         /**
11094         * @cfg {Number} hideDelay
11095         * Delay in milliseconds before the quick tip hides when autoHide = true (defaults to 200)
11096         */
11097        hideDelay : 200,
11098         /**
11099         * @cfg {Boolean} autoHide
11100         * True to automatically hide the quick tip after the mouse exits the target element (defaults to true).
11101         * Used in conjunction with hideDelay.
11102         */
11103        autoHide : true,
11104         /**
11105         * @cfg {Boolean}
11106         * True to automatically hide the quick tip after a set period of time, regardless of the user's actions
11107         * (defaults to true).  Used in conjunction with autoDismissDelay.
11108         */
11109        autoDismiss : true,
11110         /**
11111         * @cfg {Number}
11112         * Delay in milliseconds before the quick tip hides when autoDismiss = true (defaults to 5000)
11113         */
11114        autoDismissDelay : 5000,
11115        /**
11116         * @cfg {Boolean} animate
11117         * True to turn on fade animation. Defaults to false (ClearType/scrollbar flicker issues in IE7).
11118         */
11119        animate : false,
11120
11121        /**
11122         * @cfg {String} title
11123         * Title text to display (defaults to '').  This can be any valid HTML markup.
11124         */
11125         title: '',
11126        /**
11127         * @cfg {String} text
11128         * Body text to display (defaults to '').  This can be any valid HTML markup.
11129         */
11130         text : '',
11131        /**
11132         * @cfg {String} cls
11133         * A CSS class to apply to the base quick tip element (defaults to '').
11134         */
11135         cls : '',
11136        /**
11137         * @cfg {Number} width
11138         * Width in pixels of the quick tip (defaults to auto).  Width will be ignored if it exceeds the bounds of
11139         * minWidth or maxWidth.
11140         */
11141         width : null,
11142
11143     /**
11144      * Initialize and enable QuickTips for first use.  This should be called once before the first attempt to access
11145      * or display QuickTips in a page.
11146      */
11147        init : function(){
11148           tm = Roo.QuickTips;
11149           cfg = tm.tagConfig;
11150           if(!inited){
11151               if(!Roo.isReady){ // allow calling of init() before onReady
11152                   Roo.onReady(Roo.QuickTips.init, Roo.QuickTips);
11153                   return;
11154               }
11155               el = new Roo.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4});
11156               el.fxDefaults = {stopFx: true};
11157               // maximum custom styling
11158               //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>');
11159               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>');              
11160               tipTitle = el.child('h3');
11161               tipTitle.enableDisplayMode("block");
11162               tipBody = el.child('div.x-tip-bd');
11163               tipBodyText = el.child('div.x-tip-bd-inner');
11164               //bdLeft = el.child('div.x-tip-bd-left');
11165               //bdRight = el.child('div.x-tip-bd-right');
11166               close = el.child('div.x-tip-close');
11167               close.enableDisplayMode("block");
11168               close.on("click", hide);
11169               var d = Roo.get(document);
11170               d.on("mousedown", onDown);
11171               d.on("mouseover", onOver);
11172               d.on("mouseout", onOut);
11173               d.on("mousemove", onMove);
11174               esc = d.addKeyListener(27, hide);
11175               esc.disable();
11176               if(Roo.dd.DD){
11177                   dd = el.initDD("default", null, {
11178                       onDrag : function(){
11179                           el.sync();  
11180                       }
11181                   });
11182                   dd.setHandleElId(tipTitle.id);
11183                   dd.lock();
11184               }
11185               inited = true;
11186           }
11187           this.enable(); 
11188        },
11189
11190     /**
11191      * Configures a new quick tip instance and assigns it to a target element.  The following config options
11192      * are supported:
11193      * <pre>
11194 Property    Type                   Description
11195 ----------  ---------------------  ------------------------------------------------------------------------
11196 target      Element/String/Array   An Element, id or array of ids that this quick tip should be tied to
11197      * </ul>
11198      * @param {Object} config The config object
11199      */
11200        register : function(config){
11201            var cs = config instanceof Array ? config : arguments;
11202            for(var i = 0, len = cs.length; i < len; i++) {
11203                var c = cs[i];
11204                var target = c.target;
11205                if(target){
11206                    if(target instanceof Array){
11207                        for(var j = 0, jlen = target.length; j < jlen; j++){
11208                            tagEls[target[j]] = c;
11209                        }
11210                    }else{
11211                        tagEls[typeof target == 'string' ? target : Roo.id(target)] = c;
11212                    }
11213                }
11214            }
11215        },
11216
11217     /**
11218      * Removes this quick tip from its element and destroys it.
11219      * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
11220      */
11221        unregister : function(el){
11222            delete tagEls[Roo.id(el)];
11223        },
11224
11225     /**
11226      * Enable this quick tip.
11227      */
11228        enable : function(){
11229            if(inited && disabled){
11230                locks.pop();
11231                if(locks.length < 1){
11232                    disabled = false;
11233                }
11234            }
11235        },
11236
11237     /**
11238      * Disable this quick tip.
11239      */
11240        disable : function(){
11241           disabled = true;
11242           clearTimeout(showProc);
11243           clearTimeout(hideProc);
11244           clearTimeout(dismissProc);
11245           if(ce){
11246               hide(true);
11247           }
11248           locks.push(1);
11249        },
11250
11251     /**
11252      * Returns true if the quick tip is enabled, else false.
11253      */
11254        isEnabled : function(){
11255             return !disabled;
11256        },
11257
11258         // private
11259        tagConfig : {
11260            namespace : "roo", // was ext?? this may break..
11261            alt_namespace : "ext",
11262            attribute : "qtip",
11263            width : "width",
11264            target : "target",
11265            title : "qtitle",
11266            hide : "hide",
11267            cls : "qclass"
11268        }
11269    };
11270 }();
11271
11272 // backwards compat
11273 Roo.QuickTips.tips = Roo.QuickTips.register;/*
11274  * Based on:
11275  * Ext JS Library 1.1.1
11276  * Copyright(c) 2006-2007, Ext JS, LLC.
11277  *
11278  * Originally Released Under LGPL - original licence link has changed is not relivant.
11279  *
11280  * Fork - LGPL
11281  * <script type="text/javascript">
11282  */
11283  
11284
11285 /**
11286  * @class Roo.tree.TreePanel
11287  * @extends Roo.data.Tree
11288  * @cfg {Roo.tree.TreeNode} root The root node
11289  * @cfg {Boolean} rootVisible false to hide the root node (defaults to true)
11290  * @cfg {Boolean} lines false to disable tree lines (defaults to true)
11291  * @cfg {Boolean} enableDD true to enable drag and drop
11292  * @cfg {Boolean} enableDrag true to enable just drag
11293  * @cfg {Boolean} enableDrop true to enable just drop
11294  * @cfg {Object} dragConfig Custom config to pass to the {@link Roo.tree.TreeDragZone} instance
11295  * @cfg {Object} dropConfig Custom config to pass to the {@link Roo.tree.TreeDropZone} instance
11296  * @cfg {String} ddGroup The DD group this TreePanel belongs to
11297  * @cfg {String} ddAppendOnly True if the tree should only allow append drops (use for trees which are sorted)
11298  * @cfg {Boolean} ddScroll true to enable YUI body scrolling
11299  * @cfg {Boolean} containerScroll true to register this container with ScrollManager
11300  * @cfg {Boolean} hlDrop false to disable node highlight on drop (defaults to the value of Roo.enableFx)
11301  * @cfg {String} hlColor The color of the node highlight (defaults to C3DAF9)
11302  * @cfg {Boolean} animate true to enable animated expand/collapse (defaults to the value of Roo.enableFx)
11303  * @cfg {Boolean} singleExpand true if only 1 node per branch may be expanded
11304  * @cfg {Boolean} selModel A tree selection model to use with this TreePanel (defaults to a {@link Roo.tree.DefaultSelectionModel})
11305  * @cfg {Roo.tree.TreeLoader} loader A TreeLoader for use with this TreePanel
11306  * @cfg {Roo.tree.TreeEditor} editor The TreeEditor to display when clicked.
11307  * @cfg {String} pathSeparator The token used to separate sub-paths in path strings (defaults to '/')
11308  * @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>
11309  * @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>
11310  * 
11311  * @constructor
11312  * @param {String/HTMLElement/Element} el The container element
11313  * @param {Object} config
11314  */
11315 Roo.tree.TreePanel = function(el, config){
11316     var root = false;
11317     var loader = false;
11318     if (config.root) {
11319         root = config.root;
11320         delete config.root;
11321     }
11322     if (config.loader) {
11323         loader = config.loader;
11324         delete config.loader;
11325     }
11326     
11327     Roo.apply(this, config);
11328     Roo.tree.TreePanel.superclass.constructor.call(this);
11329     this.el = Roo.get(el);
11330     this.el.addClass('x-tree');
11331     //console.log(root);
11332     if (root) {
11333         this.setRootNode( Roo.factory(root, Roo.tree));
11334     }
11335     if (loader) {
11336         this.loader = Roo.factory(loader, Roo.tree);
11337     }
11338    /**
11339     * Read-only. The id of the container element becomes this TreePanel's id.
11340     */
11341     this.id = this.el.id;
11342     this.addEvents({
11343         /**
11344         * @event beforeload
11345         * Fires before a node is loaded, return false to cancel
11346         * @param {Node} node The node being loaded
11347         */
11348         "beforeload" : true,
11349         /**
11350         * @event load
11351         * Fires when a node is loaded
11352         * @param {Node} node The node that was loaded
11353         */
11354         "load" : true,
11355         /**
11356         * @event textchange
11357         * Fires when the text for a node is changed
11358         * @param {Node} node The node
11359         * @param {String} text The new text
11360         * @param {String} oldText The old text
11361         */
11362         "textchange" : true,
11363         /**
11364         * @event beforeexpand
11365         * Fires before a node is expanded, return false to cancel.
11366         * @param {Node} node The node
11367         * @param {Boolean} deep
11368         * @param {Boolean} anim
11369         */
11370         "beforeexpand" : true,
11371         /**
11372         * @event beforecollapse
11373         * Fires before a node is collapsed, return false to cancel.
11374         * @param {Node} node The node
11375         * @param {Boolean} deep
11376         * @param {Boolean} anim
11377         */
11378         "beforecollapse" : true,
11379         /**
11380         * @event expand
11381         * Fires when a node is expanded
11382         * @param {Node} node The node
11383         */
11384         "expand" : true,
11385         /**
11386         * @event disabledchange
11387         * Fires when the disabled status of a node changes
11388         * @param {Node} node The node
11389         * @param {Boolean} disabled
11390         */
11391         "disabledchange" : true,
11392         /**
11393         * @event collapse
11394         * Fires when a node is collapsed
11395         * @param {Node} node The node
11396         */
11397         "collapse" : true,
11398         /**
11399         * @event beforeclick
11400         * Fires before click processing on a node. Return false to cancel the default action.
11401         * @param {Node} node The node
11402         * @param {Roo.EventObject} e The event object
11403         */
11404         "beforeclick":true,
11405         /**
11406         * @event checkchange
11407         * Fires when a node with a checkbox's checked property changes
11408         * @param {Node} this This node
11409         * @param {Boolean} checked
11410         */
11411         "checkchange":true,
11412         /**
11413         * @event click
11414         * Fires when a node is clicked
11415         * @param {Node} node The node
11416         * @param {Roo.EventObject} e The event object
11417         */
11418         "click":true,
11419         /**
11420         * @event dblclick
11421         * Fires when a node is double clicked
11422         * @param {Node} node The node
11423         * @param {Roo.EventObject} e The event object
11424         */
11425         "dblclick":true,
11426         /**
11427         * @event contextmenu
11428         * Fires when a node is right clicked
11429         * @param {Node} node The node
11430         * @param {Roo.EventObject} e The event object
11431         */
11432         "contextmenu":true,
11433         /**
11434         * @event beforechildrenrendered
11435         * Fires right before the child nodes for a node are rendered
11436         * @param {Node} node The node
11437         */
11438         "beforechildrenrendered":true,
11439         /**
11440         * @event startdrag
11441         * Fires when a node starts being dragged
11442         * @param {Roo.tree.TreePanel} this
11443         * @param {Roo.tree.TreeNode} node
11444         * @param {event} e The raw browser event
11445         */ 
11446        "startdrag" : true,
11447        /**
11448         * @event enddrag
11449         * Fires when a drag operation is complete
11450         * @param {Roo.tree.TreePanel} this
11451         * @param {Roo.tree.TreeNode} node
11452         * @param {event} e The raw browser event
11453         */
11454        "enddrag" : true,
11455        /**
11456         * @event dragdrop
11457         * Fires when a dragged node is dropped on a valid DD target
11458         * @param {Roo.tree.TreePanel} this
11459         * @param {Roo.tree.TreeNode} node
11460         * @param {DD} dd The dd it was dropped on
11461         * @param {event} e The raw browser event
11462         */
11463        "dragdrop" : true,
11464        /**
11465         * @event beforenodedrop
11466         * Fires when a DD object is dropped on a node in this tree for preprocessing. Return false to cancel the drop. The dropEvent
11467         * passed to handlers has the following properties:<br />
11468         * <ul style="padding:5px;padding-left:16px;">
11469         * <li>tree - The TreePanel</li>
11470         * <li>target - The node being targeted for the drop</li>
11471         * <li>data - The drag data from the drag source</li>
11472         * <li>point - The point of the drop - append, above or below</li>
11473         * <li>source - The drag source</li>
11474         * <li>rawEvent - Raw mouse event</li>
11475         * <li>dropNode - Drop node(s) provided by the source <b>OR</b> you can supply node(s)
11476         * to be inserted by setting them on this object.</li>
11477         * <li>cancel - Set this to true to cancel the drop.</li>
11478         * </ul>
11479         * @param {Object} dropEvent
11480         */
11481        "beforenodedrop" : true,
11482        /**
11483         * @event nodedrop
11484         * Fires after a DD object is dropped on a node in this tree. The dropEvent
11485         * passed to handlers has the following properties:<br />
11486         * <ul style="padding:5px;padding-left:16px;">
11487         * <li>tree - The TreePanel</li>
11488         * <li>target - The node being targeted for the drop</li>
11489         * <li>data - The drag data from the drag source</li>
11490         * <li>point - The point of the drop - append, above or below</li>
11491         * <li>source - The drag source</li>
11492         * <li>rawEvent - Raw mouse event</li>
11493         * <li>dropNode - Dropped node(s).</li>
11494         * </ul>
11495         * @param {Object} dropEvent
11496         */
11497        "nodedrop" : true,
11498         /**
11499         * @event nodedragover
11500         * Fires when a tree node is being targeted for a drag drop, return false to signal drop not allowed. The dragOverEvent
11501         * passed to handlers has the following properties:<br />
11502         * <ul style="padding:5px;padding-left:16px;">
11503         * <li>tree - The TreePanel</li>
11504         * <li>target - The node being targeted for the drop</li>
11505         * <li>data - The drag data from the drag source</li>
11506         * <li>point - The point of the drop - append, above or below</li>
11507         * <li>source - The drag source</li>
11508         * <li>rawEvent - Raw mouse event</li>
11509         * <li>dropNode - Drop node(s) provided by the source.</li>
11510         * <li>cancel - Set this to true to signal drop not allowed.</li>
11511         * </ul>
11512         * @param {Object} dragOverEvent
11513         */
11514        "nodedragover" : true,
11515        /**
11516         * @event appendnode
11517         * Fires when append node to the tree
11518         * @param {Roo.tree.TreePanel} this
11519         * @param {Roo.tree.TreeNode} node
11520         * @param {Number} index The index of the newly appended node
11521         */
11522        "appendnode" : true
11523         
11524     });
11525     if(this.singleExpand){
11526        this.on("beforeexpand", this.restrictExpand, this);
11527     }
11528     if (this.editor) {
11529         this.editor.tree = this;
11530         this.editor = Roo.factory(this.editor, Roo.tree);
11531     }
11532     
11533     if (this.selModel) {
11534         this.selModel = Roo.factory(this.selModel, Roo.tree);
11535     }
11536    
11537 };
11538 Roo.extend(Roo.tree.TreePanel, Roo.data.Tree, {
11539     rootVisible : true,
11540     animate: Roo.enableFx,
11541     lines : true,
11542     enableDD : false,
11543     hlDrop : Roo.enableFx,
11544   
11545     renderer: false,
11546     
11547     rendererTip: false,
11548     // private
11549     restrictExpand : function(node){
11550         var p = node.parentNode;
11551         if(p){
11552             if(p.expandedChild && p.expandedChild.parentNode == p){
11553                 p.expandedChild.collapse();
11554             }
11555             p.expandedChild = node;
11556         }
11557     },
11558
11559     // private override
11560     setRootNode : function(node){
11561         Roo.tree.TreePanel.superclass.setRootNode.call(this, node);
11562         if(!this.rootVisible){
11563             node.ui = new Roo.tree.RootTreeNodeUI(node);
11564         }
11565         return node;
11566     },
11567
11568     /**
11569      * Returns the container element for this TreePanel
11570      */
11571     getEl : function(){
11572         return this.el;
11573     },
11574
11575     /**
11576      * Returns the default TreeLoader for this TreePanel
11577      */
11578     getLoader : function(){
11579         return this.loader;
11580     },
11581
11582     /**
11583      * Expand all nodes
11584      */
11585     expandAll : function(){
11586         this.root.expand(true);
11587     },
11588
11589     /**
11590      * Collapse all nodes
11591      */
11592     collapseAll : function(){
11593         this.root.collapse(true);
11594     },
11595
11596     /**
11597      * Returns the selection model used by this TreePanel
11598      */
11599     getSelectionModel : function(){
11600         if(!this.selModel){
11601             this.selModel = new Roo.tree.DefaultSelectionModel();
11602         }
11603         return this.selModel;
11604     },
11605
11606     /**
11607      * Retrieve an array of checked nodes, or an array of a specific attribute of checked nodes (e.g. "id")
11608      * @param {String} attribute (optional) Defaults to null (return the actual nodes)
11609      * @param {TreeNode} startNode (optional) The node to start from, defaults to the root
11610      * @return {Array}
11611      */
11612     getChecked : function(a, startNode){
11613         startNode = startNode || this.root;
11614         var r = [];
11615         var f = function(){
11616             if(this.attributes.checked){
11617                 r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
11618             }
11619         }
11620         startNode.cascade(f);
11621         return r;
11622     },
11623
11624     /**
11625      * Expands a specified path in this TreePanel. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
11626      * @param {String} path
11627      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
11628      * @param {Function} callback (optional) The callback to call when the expand is complete. The callback will be called with
11629      * (bSuccess, oLastNode) where bSuccess is if the expand was successful and oLastNode is the last node that was expanded.
11630      */
11631     expandPath : function(path, attr, callback){
11632         attr = attr || "id";
11633         var keys = path.split(this.pathSeparator);
11634         var curNode = this.root;
11635         if(curNode.attributes[attr] != keys[1]){ // invalid root
11636             if(callback){
11637                 callback(false, null);
11638             }
11639             return;
11640         }
11641         var index = 1;
11642         var f = function(){
11643             if(++index == keys.length){
11644                 if(callback){
11645                     callback(true, curNode);
11646                 }
11647                 return;
11648             }
11649             var c = curNode.findChild(attr, keys[index]);
11650             if(!c){
11651                 if(callback){
11652                     callback(false, curNode);
11653                 }
11654                 return;
11655             }
11656             curNode = c;
11657             c.expand(false, false, f);
11658         };
11659         curNode.expand(false, false, f);
11660     },
11661
11662     /**
11663      * Selects the node in this tree at the specified path. A path can be retrieved from a node with {@link Roo.data.Node#getPath}
11664      * @param {String} path
11665      * @param {String} attr (optional) The attribute used in the path (see {@link Roo.data.Node#getPath} for more info)
11666      * @param {Function} callback (optional) The callback to call when the selection is complete. The callback will be called with
11667      * (bSuccess, oSelNode) where bSuccess is if the selection was successful and oSelNode is the selected node.
11668      */
11669     selectPath : function(path, attr, callback){
11670         attr = attr || "id";
11671         var keys = path.split(this.pathSeparator);
11672         var v = keys.pop();
11673         if(keys.length > 0){
11674             var f = function(success, node){
11675                 if(success && node){
11676                     var n = node.findChild(attr, v);
11677                     if(n){
11678                         n.select();
11679                         if(callback){
11680                             callback(true, n);
11681                         }
11682                     }else if(callback){
11683                         callback(false, n);
11684                     }
11685                 }else{
11686                     if(callback){
11687                         callback(false, n);
11688                     }
11689                 }
11690             };
11691             this.expandPath(keys.join(this.pathSeparator), attr, f);
11692         }else{
11693             this.root.select();
11694             if(callback){
11695                 callback(true, this.root);
11696             }
11697         }
11698     },
11699
11700     getTreeEl : function(){
11701         return this.el;
11702     },
11703
11704     /**
11705      * Trigger rendering of this TreePanel
11706      */
11707     render : function(){
11708         if (this.innerCt) {
11709             return this; // stop it rendering more than once!!
11710         }
11711         
11712         this.innerCt = this.el.createChild({tag:"ul",
11713                cls:"x-tree-root-ct " +
11714                (this.lines ? "x-tree-lines" : "x-tree-no-lines")});
11715
11716         if(this.containerScroll){
11717             Roo.dd.ScrollManager.register(this.el);
11718         }
11719         if((this.enableDD || this.enableDrop) && !this.dropZone){
11720            /**
11721             * The dropZone used by this tree if drop is enabled
11722             * @type Roo.tree.TreeDropZone
11723             */
11724              this.dropZone = new Roo.tree.TreeDropZone(this, this.dropConfig || {
11725                ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
11726            });
11727         }
11728         if((this.enableDD || this.enableDrag) && !this.dragZone){
11729            /**
11730             * The dragZone used by this tree if drag is enabled
11731             * @type Roo.tree.TreeDragZone
11732             */
11733             this.dragZone = new Roo.tree.TreeDragZone(this, this.dragConfig || {
11734                ddGroup: this.ddGroup || "TreeDD",
11735                scroll: this.ddScroll
11736            });
11737         }
11738         this.getSelectionModel().init(this);
11739         if (!this.root) {
11740             Roo.log("ROOT not set in tree");
11741             return this;
11742         }
11743         this.root.render();
11744         if(!this.rootVisible){
11745             this.root.renderChildren();
11746         }
11747         return this;
11748     }
11749 });/*
11750  * Based on:
11751  * Ext JS Library 1.1.1
11752  * Copyright(c) 2006-2007, Ext JS, LLC.
11753  *
11754  * Originally Released Under LGPL - original licence link has changed is not relivant.
11755  *
11756  * Fork - LGPL
11757  * <script type="text/javascript">
11758  */
11759  
11760
11761 /**
11762  * @class Roo.tree.DefaultSelectionModel
11763  * @extends Roo.util.Observable
11764  * The default single selection for a TreePanel.
11765  * @param {Object} cfg Configuration
11766  */
11767 Roo.tree.DefaultSelectionModel = function(cfg){
11768    this.selNode = null;
11769    
11770    
11771    
11772    this.addEvents({
11773        /**
11774         * @event selectionchange
11775         * Fires when the selected node changes
11776         * @param {DefaultSelectionModel} this
11777         * @param {TreeNode} node the new selection
11778         */
11779        "selectionchange" : true,
11780
11781        /**
11782         * @event beforeselect
11783         * Fires before the selected node changes, return false to cancel the change
11784         * @param {DefaultSelectionModel} this
11785         * @param {TreeNode} node the new selection
11786         * @param {TreeNode} node the old selection
11787         */
11788        "beforeselect" : true
11789    });
11790    
11791     Roo.tree.DefaultSelectionModel.superclass.constructor.call(this,cfg);
11792 };
11793
11794 Roo.extend(Roo.tree.DefaultSelectionModel, Roo.util.Observable, {
11795     init : function(tree){
11796         this.tree = tree;
11797         tree.getTreeEl().on("keydown", this.onKeyDown, this);
11798         tree.on("click", this.onNodeClick, this);
11799     },
11800     
11801     onNodeClick : function(node, e){
11802         if (e.ctrlKey && this.selNode == node)  {
11803             this.unselect(node);
11804             return;
11805         }
11806         this.select(node);
11807     },
11808     
11809     /**
11810      * Select a node.
11811      * @param {TreeNode} node The node to select
11812      * @return {TreeNode} The selected node
11813      */
11814     select : function(node){
11815         var last = this.selNode;
11816         if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
11817             if(last){
11818                 last.ui.onSelectedChange(false);
11819             }
11820             this.selNode = node;
11821             node.ui.onSelectedChange(true);
11822             this.fireEvent("selectionchange", this, node, last);
11823         }
11824         return node;
11825     },
11826     
11827     /**
11828      * Deselect a node.
11829      * @param {TreeNode} node The node to unselect
11830      */
11831     unselect : function(node){
11832         if(this.selNode == node){
11833             this.clearSelections();
11834         }    
11835     },
11836     
11837     /**
11838      * Clear all selections
11839      */
11840     clearSelections : function(){
11841         var n = this.selNode;
11842         if(n){
11843             n.ui.onSelectedChange(false);
11844             this.selNode = null;
11845             this.fireEvent("selectionchange", this, null);
11846         }
11847         return n;
11848     },
11849     
11850     /**
11851      * Get the selected node
11852      * @return {TreeNode} The selected node
11853      */
11854     getSelectedNode : function(){
11855         return this.selNode;    
11856     },
11857     
11858     /**
11859      * Returns true if the node is selected
11860      * @param {TreeNode} node The node to check
11861      * @return {Boolean}
11862      */
11863     isSelected : function(node){
11864         return this.selNode == node;  
11865     },
11866
11867     /**
11868      * Selects the node above the selected node in the tree, intelligently walking the nodes
11869      * @return TreeNode The new selection
11870      */
11871     selectPrevious : function(){
11872         var s = this.selNode || this.lastSelNode;
11873         if(!s){
11874             return null;
11875         }
11876         var ps = s.previousSibling;
11877         if(ps){
11878             if(!ps.isExpanded() || ps.childNodes.length < 1){
11879                 return this.select(ps);
11880             } else{
11881                 var lc = ps.lastChild;
11882                 while(lc && lc.isExpanded() && lc.childNodes.length > 0){
11883                     lc = lc.lastChild;
11884                 }
11885                 return this.select(lc);
11886             }
11887         } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
11888             return this.select(s.parentNode);
11889         }
11890         return null;
11891     },
11892
11893     /**
11894      * Selects the node above the selected node in the tree, intelligently walking the nodes
11895      * @return TreeNode The new selection
11896      */
11897     selectNext : function(){
11898         var s = this.selNode || this.lastSelNode;
11899         if(!s){
11900             return null;
11901         }
11902         if(s.firstChild && s.isExpanded()){
11903              return this.select(s.firstChild);
11904          }else if(s.nextSibling){
11905              return this.select(s.nextSibling);
11906          }else if(s.parentNode){
11907             var newS = null;
11908             s.parentNode.bubble(function(){
11909                 if(this.nextSibling){
11910                     newS = this.getOwnerTree().selModel.select(this.nextSibling);
11911                     return false;
11912                 }
11913             });
11914             return newS;
11915          }
11916         return null;
11917     },
11918
11919     onKeyDown : function(e){
11920         var s = this.selNode || this.lastSelNode;
11921         // undesirable, but required
11922         var sm = this;
11923         if(!s){
11924             return;
11925         }
11926         var k = e.getKey();
11927         switch(k){
11928              case e.DOWN:
11929                  e.stopEvent();
11930                  this.selectNext();
11931              break;
11932              case e.UP:
11933                  e.stopEvent();
11934                  this.selectPrevious();
11935              break;
11936              case e.RIGHT:
11937                  e.preventDefault();
11938                  if(s.hasChildNodes()){
11939                      if(!s.isExpanded()){
11940                          s.expand();
11941                      }else if(s.firstChild){
11942                          this.select(s.firstChild, e);
11943                      }
11944                  }
11945              break;
11946              case e.LEFT:
11947                  e.preventDefault();
11948                  if(s.hasChildNodes() && s.isExpanded()){
11949                      s.collapse();
11950                  }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
11951                      this.select(s.parentNode, e);
11952                  }
11953              break;
11954         };
11955     }
11956 });
11957
11958 /**
11959  * @class Roo.tree.MultiSelectionModel
11960  * @extends Roo.util.Observable
11961  * Multi selection for a TreePanel.
11962  * @param {Object} cfg Configuration
11963  */
11964 Roo.tree.MultiSelectionModel = function(){
11965    this.selNodes = [];
11966    this.selMap = {};
11967    this.addEvents({
11968        /**
11969         * @event selectionchange
11970         * Fires when the selected nodes change
11971         * @param {MultiSelectionModel} this
11972         * @param {Array} nodes Array of the selected nodes
11973         */
11974        "selectionchange" : true
11975    });
11976    Roo.tree.MultiSelectionModel.superclass.constructor.call(this,cfg);
11977    
11978 };
11979
11980 Roo.extend(Roo.tree.MultiSelectionModel, Roo.util.Observable, {
11981     init : function(tree){
11982         this.tree = tree;
11983         tree.getTreeEl().on("keydown", this.onKeyDown, this);
11984         tree.on("click", this.onNodeClick, this);
11985     },
11986     
11987     onNodeClick : function(node, e){
11988         this.select(node, e, e.ctrlKey);
11989     },
11990     
11991     /**
11992      * Select a node.
11993      * @param {TreeNode} node The node to select
11994      * @param {EventObject} e (optional) An event associated with the selection
11995      * @param {Boolean} keepExisting True to retain existing selections
11996      * @return {TreeNode} The selected node
11997      */
11998     select : function(node, e, keepExisting){
11999         if(keepExisting !== true){
12000             this.clearSelections(true);
12001         }
12002         if(this.isSelected(node)){
12003             this.lastSelNode = node;
12004             return node;
12005         }
12006         this.selNodes.push(node);
12007         this.selMap[node.id] = node;
12008         this.lastSelNode = node;
12009         node.ui.onSelectedChange(true);
12010         this.fireEvent("selectionchange", this, this.selNodes);
12011         return node;
12012     },
12013     
12014     /**
12015      * Deselect a node.
12016      * @param {TreeNode} node The node to unselect
12017      */
12018     unselect : function(node){
12019         if(this.selMap[node.id]){
12020             node.ui.onSelectedChange(false);
12021             var sn = this.selNodes;
12022             var index = -1;
12023             if(sn.indexOf){
12024                 index = sn.indexOf(node);
12025             }else{
12026                 for(var i = 0, len = sn.length; i < len; i++){
12027                     if(sn[i] == node){
12028                         index = i;
12029                         break;
12030                     }
12031                 }
12032             }
12033             if(index != -1){
12034                 this.selNodes.splice(index, 1);
12035             }
12036             delete this.selMap[node.id];
12037             this.fireEvent("selectionchange", this, this.selNodes);
12038         }
12039     },
12040     
12041     /**
12042      * Clear all selections
12043      */
12044     clearSelections : function(suppressEvent){
12045         var sn = this.selNodes;
12046         if(sn.length > 0){
12047             for(var i = 0, len = sn.length; i < len; i++){
12048                 sn[i].ui.onSelectedChange(false);
12049             }
12050             this.selNodes = [];
12051             this.selMap = {};
12052             if(suppressEvent !== true){
12053                 this.fireEvent("selectionchange", this, this.selNodes);
12054             }
12055         }
12056     },
12057     
12058     /**
12059      * Returns true if the node is selected
12060      * @param {TreeNode} node The node to check
12061      * @return {Boolean}
12062      */
12063     isSelected : function(node){
12064         return this.selMap[node.id] ? true : false;  
12065     },
12066     
12067     /**
12068      * Returns an array of the selected nodes
12069      * @return {Array}
12070      */
12071     getSelectedNodes : function(){
12072         return this.selNodes;    
12073     },
12074
12075     onKeyDown : Roo.tree.DefaultSelectionModel.prototype.onKeyDown,
12076
12077     selectNext : Roo.tree.DefaultSelectionModel.prototype.selectNext,
12078
12079     selectPrevious : Roo.tree.DefaultSelectionModel.prototype.selectPrevious
12080 });/*
12081  * Based on:
12082  * Ext JS Library 1.1.1
12083  * Copyright(c) 2006-2007, Ext JS, LLC.
12084  *
12085  * Originally Released Under LGPL - original licence link has changed is not relivant.
12086  *
12087  * Fork - LGPL
12088  * <script type="text/javascript">
12089  */
12090  
12091 /**
12092  * @class Roo.tree.TreeNode
12093  * @extends Roo.data.Node
12094  * @cfg {String} text The text for this node
12095  * @cfg {Boolean} expanded true to start the node expanded
12096  * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)
12097  * @cfg {Boolean} allowDrop false if this node cannot be drop on
12098  * @cfg {Boolean} disabled true to start the node disabled
12099  * @cfg {String} icon The path to an icon for the node. The preferred way to do this
12100  *    is to use the cls or iconCls attributes and add the icon via a CSS background image.
12101  * @cfg {String} cls A css class to be added to the node
12102  * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images
12103  * @cfg {String} href URL of the link used for the node (defaults to #)
12104  * @cfg {String} hrefTarget target frame for the link
12105  * @cfg {String} qtip An Ext QuickTip for the node
12106  * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)
12107  * @cfg {Boolean} singleClickExpand True for single click expand on this node
12108  * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Roo.tree.TreeNodeUI)
12109  * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox
12110  * (defaults to undefined with no checkbox rendered)
12111  * @constructor
12112  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node
12113  */
12114 Roo.tree.TreeNode = function(attributes){
12115     attributes = attributes || {};
12116     if(typeof attributes == "string"){
12117         attributes = {text: attributes};
12118     }
12119     this.childrenRendered = false;
12120     this.rendered = false;
12121     Roo.tree.TreeNode.superclass.constructor.call(this, attributes);
12122     this.expanded = attributes.expanded === true;
12123     this.isTarget = attributes.isTarget !== false;
12124     this.draggable = attributes.draggable !== false && attributes.allowDrag !== false;
12125     this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false;
12126
12127     /**
12128      * Read-only. The text for this node. To change it use setText().
12129      * @type String
12130      */
12131     this.text = attributes.text;
12132     /**
12133      * True if this node is disabled.
12134      * @type Boolean
12135      */
12136     this.disabled = attributes.disabled === true;
12137
12138     this.addEvents({
12139         /**
12140         * @event textchange
12141         * Fires when the text for this node is changed
12142         * @param {Node} this This node
12143         * @param {String} text The new text
12144         * @param {String} oldText The old text
12145         */
12146         "textchange" : true,
12147         /**
12148         * @event beforeexpand
12149         * Fires before this node is expanded, return false to cancel.
12150         * @param {Node} this This node
12151         * @param {Boolean} deep
12152         * @param {Boolean} anim
12153         */
12154         "beforeexpand" : true,
12155         /**
12156         * @event beforecollapse
12157         * Fires before this node is collapsed, return false to cancel.
12158         * @param {Node} this This node
12159         * @param {Boolean} deep
12160         * @param {Boolean} anim
12161         */
12162         "beforecollapse" : true,
12163         /**
12164         * @event expand
12165         * Fires when this node is expanded
12166         * @param {Node} this This node
12167         */
12168         "expand" : true,
12169         /**
12170         * @event disabledchange
12171         * Fires when the disabled status of this node changes
12172         * @param {Node} this This node
12173         * @param {Boolean} disabled
12174         */
12175         "disabledchange" : true,
12176         /**
12177         * @event collapse
12178         * Fires when this node is collapsed
12179         * @param {Node} this This node
12180         */
12181         "collapse" : true,
12182         /**
12183         * @event beforeclick
12184         * Fires before click processing. Return false to cancel the default action.
12185         * @param {Node} this This node
12186         * @param {Roo.EventObject} e The event object
12187         */
12188         "beforeclick":true,
12189         /**
12190         * @event checkchange
12191         * Fires when a node with a checkbox's checked property changes
12192         * @param {Node} this This node
12193         * @param {Boolean} checked
12194         */
12195         "checkchange":true,
12196         /**
12197         * @event click
12198         * Fires when this node is clicked
12199         * @param {Node} this This node
12200         * @param {Roo.EventObject} e The event object
12201         */
12202         "click":true,
12203         /**
12204         * @event dblclick
12205         * Fires when this node is double clicked
12206         * @param {Node} this This node
12207         * @param {Roo.EventObject} e The event object
12208         */
12209         "dblclick":true,
12210         /**
12211         * @event contextmenu
12212         * Fires when this node is right clicked
12213         * @param {Node} this This node
12214         * @param {Roo.EventObject} e The event object
12215         */
12216         "contextmenu":true,
12217         /**
12218         * @event beforechildrenrendered
12219         * Fires right before the child nodes for this node are rendered
12220         * @param {Node} this This node
12221         */
12222         "beforechildrenrendered":true
12223     });
12224
12225     var uiClass = this.attributes.uiProvider || Roo.tree.TreeNodeUI;
12226
12227     /**
12228      * Read-only. The UI for this node
12229      * @type TreeNodeUI
12230      */
12231     this.ui = new uiClass(this);
12232     
12233     // finally support items[]
12234     if (typeof(this.attributes.items) == 'undefined' || !this.attributes.items) {
12235         return;
12236     }
12237     
12238     
12239     Roo.each(this.attributes.items, function(c) {
12240         this.appendChild(Roo.factory(c,Roo.Tree));
12241     }, this);
12242     delete this.attributes.items;
12243     
12244     
12245     
12246 };
12247 Roo.extend(Roo.tree.TreeNode, Roo.data.Node, {
12248     preventHScroll: true,
12249     /**
12250      * Returns true if this node is expanded
12251      * @return {Boolean}
12252      */
12253     isExpanded : function(){
12254         return this.expanded;
12255     },
12256
12257     /**
12258      * Returns the UI object for this node
12259      * @return {TreeNodeUI}
12260      */
12261     getUI : function(){
12262         return this.ui;
12263     },
12264
12265     // private override
12266     setFirstChild : function(node){
12267         var of = this.firstChild;
12268         Roo.tree.TreeNode.superclass.setFirstChild.call(this, node);
12269         if(this.childrenRendered && of && node != of){
12270             of.renderIndent(true, true);
12271         }
12272         if(this.rendered){
12273             this.renderIndent(true, true);
12274         }
12275     },
12276
12277     // private override
12278     setLastChild : function(node){
12279         var ol = this.lastChild;
12280         Roo.tree.TreeNode.superclass.setLastChild.call(this, node);
12281         if(this.childrenRendered && ol && node != ol){
12282             ol.renderIndent(true, true);
12283         }
12284         if(this.rendered){
12285             this.renderIndent(true, true);
12286         }
12287     },
12288
12289     // these methods are overridden to provide lazy rendering support
12290     // private override
12291     appendChild : function()
12292     {
12293         var node = Roo.tree.TreeNode.superclass.appendChild.apply(this, arguments);
12294         if(node && this.childrenRendered){
12295             node.render();
12296         }
12297         this.ui.updateExpandIcon();
12298         return node;
12299     },
12300
12301     // private override
12302     removeChild : function(node){
12303         this.ownerTree.getSelectionModel().unselect(node);
12304         Roo.tree.TreeNode.superclass.removeChild.apply(this, arguments);
12305         // if it's been rendered remove dom node
12306         if(this.childrenRendered){
12307             node.ui.remove();
12308         }
12309         if(this.childNodes.length < 1){
12310             this.collapse(false, false);
12311         }else{
12312             this.ui.updateExpandIcon();
12313         }
12314         if(!this.firstChild) {
12315             this.childrenRendered = false;
12316         }
12317         return node;
12318     },
12319
12320     // private override
12321     insertBefore : function(node, refNode){
12322         var newNode = Roo.tree.TreeNode.superclass.insertBefore.apply(this, arguments);
12323         if(newNode && refNode && this.childrenRendered){
12324             node.render();
12325         }
12326         this.ui.updateExpandIcon();
12327         return newNode;
12328     },
12329
12330     /**
12331      * Sets the text for this node
12332      * @param {String} text
12333      */
12334     setText : function(text){
12335         var oldText = this.text;
12336         this.text = text;
12337         this.attributes.text = text;
12338         if(this.rendered){ // event without subscribing
12339             this.ui.onTextChange(this, text, oldText);
12340         }
12341         this.fireEvent("textchange", this, text, oldText);
12342     },
12343
12344     /**
12345      * Triggers selection of this node
12346      */
12347     select : function(){
12348         this.getOwnerTree().getSelectionModel().select(this);
12349     },
12350
12351     /**
12352      * Triggers deselection of this node
12353      */
12354     unselect : function(){
12355         this.getOwnerTree().getSelectionModel().unselect(this);
12356     },
12357
12358     /**
12359      * Returns true if this node is selected
12360      * @return {Boolean}
12361      */
12362     isSelected : function(){
12363         return this.getOwnerTree().getSelectionModel().isSelected(this);
12364     },
12365
12366     /**
12367      * Expand this node.
12368      * @param {Boolean} deep (optional) True to expand all children as well
12369      * @param {Boolean} anim (optional) false to cancel the default animation
12370      * @param {Function} callback (optional) A callback to be called when
12371      * expanding this node completes (does not wait for deep expand to complete).
12372      * Called with 1 parameter, this node.
12373      */
12374     expand : function(deep, anim, callback){
12375         if(!this.expanded){
12376             if(this.fireEvent("beforeexpand", this, deep, anim) === false){
12377                 return;
12378             }
12379             if(!this.childrenRendered){
12380                 this.renderChildren();
12381             }
12382             this.expanded = true;
12383             
12384             if(!this.isHiddenRoot() && (this.getOwnerTree() && this.getOwnerTree().animate && anim !== false) || anim){
12385                 this.ui.animExpand(function(){
12386                     this.fireEvent("expand", this);
12387                     if(typeof callback == "function"){
12388                         callback(this);
12389                     }
12390                     if(deep === true){
12391                         this.expandChildNodes(true);
12392                     }
12393                 }.createDelegate(this));
12394                 return;
12395             }else{
12396                 this.ui.expand();
12397                 this.fireEvent("expand", this);
12398                 if(typeof callback == "function"){
12399                     callback(this);
12400                 }
12401             }
12402         }else{
12403            if(typeof callback == "function"){
12404                callback(this);
12405            }
12406         }
12407         if(deep === true){
12408             this.expandChildNodes(true);
12409         }
12410     },
12411
12412     isHiddenRoot : function(){
12413         return this.isRoot && !this.getOwnerTree().rootVisible;
12414     },
12415
12416     /**
12417      * Collapse this node.
12418      * @param {Boolean} deep (optional) True to collapse all children as well
12419      * @param {Boolean} anim (optional) false to cancel the default animation
12420      */
12421     collapse : function(deep, anim){
12422         if(this.expanded && !this.isHiddenRoot()){
12423             if(this.fireEvent("beforecollapse", this, deep, anim) === false){
12424                 return;
12425             }
12426             this.expanded = false;
12427             if((this.getOwnerTree().animate && anim !== false) || anim){
12428                 this.ui.animCollapse(function(){
12429                     this.fireEvent("collapse", this);
12430                     if(deep === true){
12431                         this.collapseChildNodes(true);
12432                     }
12433                 }.createDelegate(this));
12434                 return;
12435             }else{
12436                 this.ui.collapse();
12437                 this.fireEvent("collapse", this);
12438             }
12439         }
12440         if(deep === true){
12441             var cs = this.childNodes;
12442             for(var i = 0, len = cs.length; i < len; i++) {
12443                 cs[i].collapse(true, false);
12444             }
12445         }
12446     },
12447
12448     // private
12449     delayedExpand : function(delay){
12450         if(!this.expandProcId){
12451             this.expandProcId = this.expand.defer(delay, this);
12452         }
12453     },
12454
12455     // private
12456     cancelExpand : function(){
12457         if(this.expandProcId){
12458             clearTimeout(this.expandProcId);
12459         }
12460         this.expandProcId = false;
12461     },
12462
12463     /**
12464      * Toggles expanded/collapsed state of the node
12465      */
12466     toggle : function(){
12467         if(this.expanded){
12468             this.collapse();
12469         }else{
12470             this.expand();
12471         }
12472     },
12473
12474     /**
12475      * Ensures all parent nodes are expanded
12476      */
12477     ensureVisible : function(callback){
12478         var tree = this.getOwnerTree();
12479         tree.expandPath(this.parentNode.getPath(), false, function(){
12480             tree.getTreeEl().scrollChildIntoView(this.ui.anchor);
12481             Roo.callback(callback);
12482         }.createDelegate(this));
12483     },
12484
12485     /**
12486      * Expand all child nodes
12487      * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes
12488      */
12489     expandChildNodes : function(deep){
12490         var cs = this.childNodes;
12491         for(var i = 0, len = cs.length; i < len; i++) {
12492                 cs[i].expand(deep);
12493         }
12494     },
12495
12496     /**
12497      * Collapse all child nodes
12498      * @param {Boolean} deep (optional) true if the child nodes should also collapse their child nodes
12499      */
12500     collapseChildNodes : function(deep){
12501         var cs = this.childNodes;
12502         for(var i = 0, len = cs.length; i < len; i++) {
12503                 cs[i].collapse(deep);
12504         }
12505     },
12506
12507     /**
12508      * Disables this node
12509      */
12510     disable : function(){
12511         this.disabled = true;
12512         this.unselect();
12513         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12514             this.ui.onDisableChange(this, true);
12515         }
12516         this.fireEvent("disabledchange", this, true);
12517     },
12518
12519     /**
12520      * Enables this node
12521      */
12522     enable : function(){
12523         this.disabled = false;
12524         if(this.rendered && this.ui.onDisableChange){ // event without subscribing
12525             this.ui.onDisableChange(this, false);
12526         }
12527         this.fireEvent("disabledchange", this, false);
12528     },
12529
12530     // private
12531     renderChildren : function(suppressEvent){
12532         if(suppressEvent !== false){
12533             this.fireEvent("beforechildrenrendered", this);
12534         }
12535         var cs = this.childNodes;
12536         for(var i = 0, len = cs.length; i < len; i++){
12537             cs[i].render(true);
12538         }
12539         this.childrenRendered = true;
12540     },
12541
12542     // private
12543     sort : function(fn, scope){
12544         Roo.tree.TreeNode.superclass.sort.apply(this, arguments);
12545         if(this.childrenRendered){
12546             var cs = this.childNodes;
12547             for(var i = 0, len = cs.length; i < len; i++){
12548                 cs[i].render(true);
12549             }
12550         }
12551     },
12552
12553     // private
12554     render : function(bulkRender){
12555         this.ui.render(bulkRender);
12556         if(!this.rendered){
12557             this.rendered = true;
12558             if(this.expanded){
12559                 this.expanded = false;
12560                 this.expand(false, false);
12561             }
12562         }
12563     },
12564
12565     // private
12566     renderIndent : function(deep, refresh){
12567         if(refresh){
12568             this.ui.childIndent = null;
12569         }
12570         this.ui.renderIndent();
12571         if(deep === true && this.childrenRendered){
12572             var cs = this.childNodes;
12573             for(var i = 0, len = cs.length; i < len; i++){
12574                 cs[i].renderIndent(true, refresh);
12575             }
12576         }
12577     }
12578 });/*
12579  * Based on:
12580  * Ext JS Library 1.1.1
12581  * Copyright(c) 2006-2007, Ext JS, LLC.
12582  *
12583  * Originally Released Under LGPL - original licence link has changed is not relivant.
12584  *
12585  * Fork - LGPL
12586  * <script type="text/javascript">
12587  */
12588  
12589 /**
12590  * @class Roo.tree.AsyncTreeNode
12591  * @extends Roo.tree.TreeNode
12592  * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree)
12593  * @constructor
12594  * @param {Object/String} attributes The attributes/config for the node or just a string with the text for the node 
12595  */
12596  Roo.tree.AsyncTreeNode = function(config){
12597     this.loaded = false;
12598     this.loading = false;
12599     Roo.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
12600     /**
12601     * @event beforeload
12602     * Fires before this node is loaded, return false to cancel
12603     * @param {Node} this This node
12604     */
12605     this.addEvents({'beforeload':true, 'load': true});
12606     /**
12607     * @event load
12608     * Fires when this node is loaded
12609     * @param {Node} this This node
12610     */
12611     /**
12612      * The loader used by this node (defaults to using the tree's defined loader)
12613      * @type TreeLoader
12614      * @property loader
12615      */
12616 };
12617 Roo.extend(Roo.tree.AsyncTreeNode, Roo.tree.TreeNode, {
12618     expand : function(deep, anim, callback){
12619         if(this.loading){ // if an async load is already running, waiting til it's done
12620             var timer;
12621             var f = function(){
12622                 if(!this.loading){ // done loading
12623                     clearInterval(timer);
12624                     this.expand(deep, anim, callback);
12625                 }
12626             }.createDelegate(this);
12627             timer = setInterval(f, 200);
12628             return;
12629         }
12630         if(!this.loaded){
12631             if(this.fireEvent("beforeload", this) === false){
12632                 return;
12633             }
12634             this.loading = true;
12635             this.ui.beforeLoad(this);
12636             var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader();
12637             if(loader){
12638                 loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback]));
12639                 return;
12640             }
12641         }
12642         Roo.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback);
12643     },
12644     
12645     /**
12646      * Returns true if this node is currently loading
12647      * @return {Boolean}
12648      */
12649     isLoading : function(){
12650         return this.loading;  
12651     },
12652     
12653     loadComplete : function(deep, anim, callback){
12654         this.loading = false;
12655         this.loaded = true;
12656         this.ui.afterLoad(this);
12657         this.fireEvent("load", this);
12658         this.expand(deep, anim, callback);
12659     },
12660     
12661     /**
12662      * Returns true if this node has been loaded
12663      * @return {Boolean}
12664      */
12665     isLoaded : function(){
12666         return this.loaded;
12667     },
12668     
12669     hasChildNodes : function(){
12670         if(!this.isLeaf() && !this.loaded){
12671             return true;
12672         }else{
12673             return Roo.tree.AsyncTreeNode.superclass.hasChildNodes.call(this);
12674         }
12675     },
12676
12677     /**
12678      * Trigger a reload for this node
12679      * @param {Function} callback
12680      */
12681     reload : function(callback){
12682         this.collapse(false, false);
12683         while(this.firstChild){
12684             this.removeChild(this.firstChild);
12685         }
12686         this.childrenRendered = false;
12687         this.loaded = false;
12688         if(this.isHiddenRoot()){
12689             this.expanded = false;
12690         }
12691         this.expand(false, false, callback);
12692     }
12693 });/*
12694  * Based on:
12695  * Ext JS Library 1.1.1
12696  * Copyright(c) 2006-2007, Ext JS, LLC.
12697  *
12698  * Originally Released Under LGPL - original licence link has changed is not relivant.
12699  *
12700  * Fork - LGPL
12701  * <script type="text/javascript">
12702  */
12703  
12704 /**
12705  * @class Roo.tree.TreeNodeUI
12706  * @constructor
12707  * @param {Object} node The node to render
12708  * The TreeNode UI implementation is separate from the
12709  * tree implementation. Unless you are customizing the tree UI,
12710  * you should never have to use this directly.
12711  */
12712 Roo.tree.TreeNodeUI = function(node){
12713     this.node = node;
12714     this.rendered = false;
12715     this.animating = false;
12716     this.emptyIcon = Roo.BLANK_IMAGE_URL;
12717 };
12718
12719 Roo.tree.TreeNodeUI.prototype = {
12720     removeChild : function(node){
12721         if(this.rendered){
12722             this.ctNode.removeChild(node.ui.getEl());
12723         }
12724     },
12725
12726     beforeLoad : function(){
12727          this.addClass("x-tree-node-loading");
12728     },
12729
12730     afterLoad : function(){
12731          this.removeClass("x-tree-node-loading");
12732     },
12733
12734     onTextChange : function(node, text, oldText){
12735         if(this.rendered){
12736             this.textNode.innerHTML = text;
12737         }
12738     },
12739
12740     onDisableChange : function(node, state){
12741         this.disabled = state;
12742         if(state){
12743             this.addClass("x-tree-node-disabled");
12744         }else{
12745             this.removeClass("x-tree-node-disabled");
12746         }
12747     },
12748
12749     onSelectedChange : function(state){
12750         if(state){
12751             this.focus();
12752             this.addClass("x-tree-selected");
12753         }else{
12754             //this.blur();
12755             this.removeClass("x-tree-selected");
12756         }
12757     },
12758
12759     onMove : function(tree, node, oldParent, newParent, index, refNode){
12760         this.childIndent = null;
12761         if(this.rendered){
12762             var targetNode = newParent.ui.getContainer();
12763             if(!targetNode){//target not rendered
12764                 this.holder = document.createElement("div");
12765                 this.holder.appendChild(this.wrap);
12766                 return;
12767             }
12768             var insertBefore = refNode ? refNode.ui.getEl() : null;
12769             if(insertBefore){
12770                 targetNode.insertBefore(this.wrap, insertBefore);
12771             }else{
12772                 targetNode.appendChild(this.wrap);
12773             }
12774             this.node.renderIndent(true);
12775         }
12776     },
12777
12778     addClass : function(cls){
12779         if(this.elNode){
12780             Roo.fly(this.elNode).addClass(cls);
12781         }
12782     },
12783
12784     removeClass : function(cls){
12785         if(this.elNode){
12786             Roo.fly(this.elNode).removeClass(cls);
12787         }
12788     },
12789
12790     remove : function(){
12791         if(this.rendered){
12792             this.holder = document.createElement("div");
12793             this.holder.appendChild(this.wrap);
12794         }
12795     },
12796
12797     fireEvent : function(){
12798         return this.node.fireEvent.apply(this.node, arguments);
12799     },
12800
12801     initEvents : function(){
12802         this.node.on("move", this.onMove, this);
12803         var E = Roo.EventManager;
12804         var a = this.anchor;
12805
12806         var el = Roo.fly(a, '_treeui');
12807
12808         if(Roo.isOpera){ // opera render bug ignores the CSS
12809             el.setStyle("text-decoration", "none");
12810         }
12811
12812         el.on("click", this.onClick, this);
12813         el.on("dblclick", this.onDblClick, this);
12814
12815         if(this.checkbox){
12816             Roo.EventManager.on(this.checkbox,
12817                     Roo.isIE ? 'click' : 'change', this.onCheckChange, this);
12818         }
12819
12820         el.on("contextmenu", this.onContextMenu, this);
12821
12822         var icon = Roo.fly(this.iconNode);
12823         icon.on("click", this.onClick, this);
12824         icon.on("dblclick", this.onDblClick, this);
12825         icon.on("contextmenu", this.onContextMenu, this);
12826         E.on(this.ecNode, "click", this.ecClick, this, true);
12827
12828         if(this.node.disabled){
12829             this.addClass("x-tree-node-disabled");
12830         }
12831         if(this.node.hidden){
12832             this.addClass("x-tree-node-disabled");
12833         }
12834         var ot = this.node.getOwnerTree();
12835         var dd = ot ? (ot.enableDD || ot.enableDrag || ot.enableDrop) : false;
12836         if(dd && (!this.node.isRoot || ot.rootVisible)){
12837             Roo.dd.Registry.register(this.elNode, {
12838                 node: this.node,
12839                 handles: this.getDDHandles(),
12840                 isHandle: false
12841             });
12842         }
12843     },
12844
12845     getDDHandles : function(){
12846         return [this.iconNode, this.textNode];
12847     },
12848
12849     hide : function(){
12850         if(this.rendered){
12851             this.wrap.style.display = "none";
12852         }
12853     },
12854
12855     show : function(){
12856         if(this.rendered){
12857             this.wrap.style.display = "";
12858         }
12859     },
12860
12861     onContextMenu : function(e){
12862         if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
12863             e.preventDefault();
12864             this.focus();
12865             this.fireEvent("contextmenu", this.node, e);
12866         }
12867     },
12868
12869     onClick : function(e){
12870         if(this.dropping){
12871             e.stopEvent();
12872             return;
12873         }
12874         if(this.fireEvent("beforeclick", this.node, e) !== false){
12875             if(!this.disabled && this.node.attributes.href){
12876                 this.fireEvent("click", this.node, e);
12877                 return;
12878             }
12879             e.preventDefault();
12880             if(this.disabled){
12881                 return;
12882             }
12883
12884             if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
12885                 this.node.toggle();
12886             }
12887
12888             this.fireEvent("click", this.node, e);
12889         }else{
12890             e.stopEvent();
12891         }
12892     },
12893
12894     onDblClick : function(e){
12895         e.preventDefault();
12896         if(this.disabled){
12897             return;
12898         }
12899         if(this.checkbox){
12900             this.toggleCheck();
12901         }
12902         if(!this.animating && this.node.hasChildNodes()){
12903             this.node.toggle();
12904         }
12905         this.fireEvent("dblclick", this.node, e);
12906     },
12907
12908     onCheckChange : function(){
12909         var checked = this.checkbox.checked;
12910         this.node.attributes.checked = checked;
12911         this.fireEvent('checkchange', this.node, checked);
12912     },
12913
12914     ecClick : function(e){
12915         if(!this.animating && this.node.hasChildNodes()){
12916             this.node.toggle();
12917         }
12918     },
12919
12920     startDrop : function(){
12921         this.dropping = true;
12922     },
12923
12924     // delayed drop so the click event doesn't get fired on a drop
12925     endDrop : function(){
12926        setTimeout(function(){
12927            this.dropping = false;
12928        }.createDelegate(this), 50);
12929     },
12930
12931     expand : function(){
12932         this.updateExpandIcon();
12933         this.ctNode.style.display = "";
12934     },
12935
12936     focus : function(){
12937         if(!this.node.preventHScroll){
12938             try{this.anchor.focus();
12939             }catch(e){}
12940         }else if(!Roo.isIE){
12941             try{
12942                 var noscroll = this.node.getOwnerTree().getTreeEl().dom;
12943                 var l = noscroll.scrollLeft;
12944                 this.anchor.focus();
12945                 noscroll.scrollLeft = l;
12946             }catch(e){}
12947         }
12948     },
12949
12950     toggleCheck : function(value){
12951         var cb = this.checkbox;
12952         if(cb){
12953             cb.checked = (value === undefined ? !cb.checked : value);
12954         }
12955     },
12956
12957     blur : function(){
12958         try{
12959             this.anchor.blur();
12960         }catch(e){}
12961     },
12962
12963     animExpand : function(callback){
12964         var ct = Roo.get(this.ctNode);
12965         ct.stopFx();
12966         if(!this.node.hasChildNodes()){
12967             this.updateExpandIcon();
12968             this.ctNode.style.display = "";
12969             Roo.callback(callback);
12970             return;
12971         }
12972         this.animating = true;
12973         this.updateExpandIcon();
12974
12975         ct.slideIn('t', {
12976            callback : function(){
12977                this.animating = false;
12978                Roo.callback(callback);
12979             },
12980             scope: this,
12981             duration: this.node.ownerTree.duration || .25
12982         });
12983     },
12984
12985     highlight : function(){
12986         var tree = this.node.getOwnerTree();
12987         Roo.fly(this.wrap).highlight(
12988             tree.hlColor || "C3DAF9",
12989             {endColor: tree.hlBaseColor}
12990         );
12991     },
12992
12993     collapse : function(){
12994         this.updateExpandIcon();
12995         this.ctNode.style.display = "none";
12996     },
12997
12998     animCollapse : function(callback){
12999         var ct = Roo.get(this.ctNode);
13000         ct.enableDisplayMode('block');
13001         ct.stopFx();
13002
13003         this.animating = true;
13004         this.updateExpandIcon();
13005
13006         ct.slideOut('t', {
13007             callback : function(){
13008                this.animating = false;
13009                Roo.callback(callback);
13010             },
13011             scope: this,
13012             duration: this.node.ownerTree.duration || .25
13013         });
13014     },
13015
13016     getContainer : function(){
13017         return this.ctNode;
13018     },
13019
13020     getEl : function(){
13021         return this.wrap;
13022     },
13023
13024     appendDDGhost : function(ghostNode){
13025         ghostNode.appendChild(this.elNode.cloneNode(true));
13026     },
13027
13028     getDDRepairXY : function(){
13029         return Roo.lib.Dom.getXY(this.iconNode);
13030     },
13031
13032     onRender : function(){
13033         this.render();
13034     },
13035
13036     render : function(bulkRender){
13037         var n = this.node, a = n.attributes;
13038         var targetNode = n.parentNode ?
13039               n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
13040
13041         if(!this.rendered){
13042             this.rendered = true;
13043
13044             this.renderElements(n, a, targetNode, bulkRender);
13045
13046             if(a.qtip){
13047                if(this.textNode.setAttributeNS){
13048                    this.textNode.setAttributeNS("ext", "qtip", a.qtip);
13049                    if(a.qtipTitle){
13050                        this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
13051                    }
13052                }else{
13053                    this.textNode.setAttribute("ext:qtip", a.qtip);
13054                    if(a.qtipTitle){
13055                        this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
13056                    }
13057                }
13058             }else if(a.qtipCfg){
13059                 a.qtipCfg.target = Roo.id(this.textNode);
13060                 Roo.QuickTips.register(a.qtipCfg);
13061             }
13062             this.initEvents();
13063             if(!this.node.expanded){
13064                 this.updateExpandIcon();
13065             }
13066         }else{
13067             if(bulkRender === true) {
13068                 targetNode.appendChild(this.wrap);
13069             }
13070         }
13071     },
13072
13073     renderElements : function(n, a, targetNode, bulkRender)
13074     {
13075         // add some indent caching, this helps performance when rendering a large tree
13076         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
13077         var t = n.getOwnerTree();
13078         var txt = t && t.renderer ? t.renderer(n.attributes) : Roo.util.Format.htmlEncode(n.text);
13079         if (typeof(n.attributes.html) != 'undefined') {
13080             txt = n.attributes.html;
13081         }
13082         var tip = t && t.rendererTip ? t.rendererTip(n.attributes) : txt;
13083         var cb = typeof a.checked == 'boolean';
13084         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
13085         var buf = ['<li class="x-tree-node"><div class="x-tree-node-el ', a.cls,'">',
13086             '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
13087             '<img src="', this.emptyIcon, '" class="x-tree-ec-icon" />',
13088             '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
13089             cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : ' />')) : '',
13090             '<a hidefocus="on" href="',href,'" tabIndex="1" ',
13091              a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", 
13092                 '><span unselectable="on" qtip="' , tip ,'">',txt,"</span></a></div>",
13093             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
13094             "</li>"];
13095
13096         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
13097             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
13098                                 n.nextSibling.ui.getEl(), buf.join(""));
13099         }else{
13100             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
13101         }
13102
13103         this.elNode = this.wrap.childNodes[0];
13104         this.ctNode = this.wrap.childNodes[1];
13105         var cs = this.elNode.childNodes;
13106         this.indentNode = cs[0];
13107         this.ecNode = cs[1];
13108         this.iconNode = cs[2];
13109         var index = 3;
13110         if(cb){
13111             this.checkbox = cs[3];
13112             index++;
13113         }
13114         this.anchor = cs[index];
13115         this.textNode = cs[index].firstChild;
13116     },
13117
13118     getAnchor : function(){
13119         return this.anchor;
13120     },
13121
13122     getTextEl : function(){
13123         return this.textNode;
13124     },
13125
13126     getIconEl : function(){
13127         return this.iconNode;
13128     },
13129
13130     isChecked : function(){
13131         return this.checkbox ? this.checkbox.checked : false;
13132     },
13133
13134     updateExpandIcon : function(){
13135         if(this.rendered){
13136             var n = this.node, c1, c2;
13137             var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
13138             var hasChild = n.hasChildNodes();
13139             if(hasChild){
13140                 if(n.expanded){
13141                     cls += "-minus";
13142                     c1 = "x-tree-node-collapsed";
13143                     c2 = "x-tree-node-expanded";
13144                 }else{
13145                     cls += "-plus";
13146                     c1 = "x-tree-node-expanded";
13147                     c2 = "x-tree-node-collapsed";
13148                 }
13149                 if(this.wasLeaf){
13150                     this.removeClass("x-tree-node-leaf");
13151                     this.wasLeaf = false;
13152                 }
13153                 if(this.c1 != c1 || this.c2 != c2){
13154                     Roo.fly(this.elNode).replaceClass(c1, c2);
13155                     this.c1 = c1; this.c2 = c2;
13156                 }
13157             }else{
13158                 // this changes non-leafs into leafs if they have no children.
13159                 // it's not very rational behaviour..
13160                 
13161                 if(!this.wasLeaf && this.node.leaf){
13162                     Roo.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
13163                     delete this.c1;
13164                     delete this.c2;
13165                     this.wasLeaf = true;
13166                 }
13167             }
13168             var ecc = "x-tree-ec-icon "+cls;
13169             if(this.ecc != ecc){
13170                 this.ecNode.className = ecc;
13171                 this.ecc = ecc;
13172             }
13173         }
13174     },
13175
13176     getChildIndent : function(){
13177         if(!this.childIndent){
13178             var buf = [];
13179             var p = this.node;
13180             while(p){
13181                 if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
13182                     if(!p.isLast()) {
13183                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
13184                     } else {
13185                         buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
13186                     }
13187                 }
13188                 p = p.parentNode;
13189             }
13190             this.childIndent = buf.join("");
13191         }
13192         return this.childIndent;
13193     },
13194
13195     renderIndent : function(){
13196         if(this.rendered){
13197             var indent = "";
13198             var p = this.node.parentNode;
13199             if(p){
13200                 indent = p.ui.getChildIndent();
13201             }
13202             if(this.indentMarkup != indent){ // don't rerender if not required
13203                 this.indentNode.innerHTML = indent;
13204                 this.indentMarkup = indent;
13205             }
13206             this.updateExpandIcon();
13207         }
13208     }
13209 };
13210
13211 Roo.tree.RootTreeNodeUI = function(){
13212     Roo.tree.RootTreeNodeUI.superclass.constructor.apply(this, arguments);
13213 };
13214 Roo.extend(Roo.tree.RootTreeNodeUI, Roo.tree.TreeNodeUI, {
13215     render : function(){
13216         if(!this.rendered){
13217             var targetNode = this.node.ownerTree.innerCt.dom;
13218             this.node.expanded = true;
13219             targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
13220             this.wrap = this.ctNode = targetNode.firstChild;
13221         }
13222     },
13223     collapse : function(){
13224     },
13225     expand : function(){
13226     }
13227 });/*
13228  * Based on:
13229  * Ext JS Library 1.1.1
13230  * Copyright(c) 2006-2007, Ext JS, LLC.
13231  *
13232  * Originally Released Under LGPL - original licence link has changed is not relivant.
13233  *
13234  * Fork - LGPL
13235  * <script type="text/javascript">
13236  */
13237 /**
13238  * @class Roo.tree.TreeLoader
13239  * @extends Roo.util.Observable
13240  * A TreeLoader provides for lazy loading of an {@link Roo.tree.TreeNode}'s child
13241  * nodes from a specified URL. The response must be a javascript Array definition
13242  * who's elements are node definition objects. eg:
13243  * <pre><code>
13244 {  success : true,
13245    data :      [
13246    
13247     { 'id': 1, 'text': 'A folder Node', 'leaf': false },
13248     { 'id': 2, 'text': 'A leaf Node', 'leaf': true }
13249     ]
13250 }
13251
13252
13253 </code></pre>
13254  * <br><br>
13255  * The old style respose with just an array is still supported, but not recommended.
13256  * <br><br>
13257  *
13258  * A server request is sent, and child nodes are loaded only when a node is expanded.
13259  * The loading node's id is passed to the server under the parameter name "node" to
13260  * enable the server to produce the correct child nodes.
13261  * <br><br>
13262  * To pass extra parameters, an event handler may be attached to the "beforeload"
13263  * event, and the parameters specified in the TreeLoader's baseParams property:
13264  * <pre><code>
13265     myTreeLoader.on("beforeload", function(treeLoader, node) {
13266         this.baseParams.category = node.attributes.category;
13267     }, this);
13268     
13269 </code></pre>
13270  *
13271  * This would pass an HTTP parameter called "category" to the server containing
13272  * the value of the Node's "category" attribute.
13273  * @constructor
13274  * Creates a new Treeloader.
13275  * @param {Object} config A config object containing config properties.
13276  */
13277 Roo.tree.TreeLoader = function(config){
13278     this.baseParams = {};
13279     this.requestMethod = "POST";
13280     Roo.apply(this, config);
13281
13282     this.addEvents({
13283     
13284         /**
13285          * @event beforeload
13286          * Fires before a network request is made to retrieve the Json text which specifies a node's children.
13287          * @param {Object} This TreeLoader object.
13288          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13289          * @param {Object} callback The callback function specified in the {@link #load} call.
13290          */
13291         beforeload : true,
13292         /**
13293          * @event load
13294          * Fires when the node has been successfuly loaded.
13295          * @param {Object} This TreeLoader object.
13296          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13297          * @param {Object} response The response object containing the data from the server.
13298          */
13299         load : true,
13300         /**
13301          * @event loadexception
13302          * Fires if the network request failed.
13303          * @param {Object} This TreeLoader object.
13304          * @param {Object} node The {@link Roo.tree.TreeNode} object being loaded.
13305          * @param {Object} response The response object containing the data from the server.
13306          */
13307         loadexception : true,
13308         /**
13309          * @event create
13310          * Fires before a node is created, enabling you to return custom Node types 
13311          * @param {Object} This TreeLoader object.
13312          * @param {Object} attr - the data returned from the AJAX call (modify it to suit)
13313          */
13314         create : true
13315     });
13316
13317     Roo.tree.TreeLoader.superclass.constructor.call(this);
13318 };
13319
13320 Roo.extend(Roo.tree.TreeLoader, Roo.util.Observable, {
13321     /**
13322     * @cfg {String} dataUrl The URL from which to request a Json string which
13323     * specifies an array of node definition object representing the child nodes
13324     * to be loaded.
13325     */
13326     /**
13327     * @cfg {String} requestMethod either GET or POST
13328     * defaults to POST (due to BC)
13329     * to be loaded.
13330     */
13331     /**
13332     * @cfg {Object} baseParams (optional) An object containing properties which
13333     * specify HTTP parameters to be passed to each request for child nodes.
13334     */
13335     /**
13336     * @cfg {Object} baseAttrs (optional) An object containing attributes to be added to all nodes
13337     * created by this loader. If the attributes sent by the server have an attribute in this object,
13338     * they take priority.
13339     */
13340     /**
13341     * @cfg {Object} uiProviders (optional) An object containing properties which
13342     * 
13343     * DEPRECATED - use 'create' event handler to modify attributes - which affect creation.
13344     * specify custom {@link Roo.tree.TreeNodeUI} implementations. If the optional
13345     * <i>uiProvider</i> attribute of a returned child node is a string rather
13346     * than a reference to a TreeNodeUI implementation, this that string value
13347     * is used as a property name in the uiProviders object. You can define the provider named
13348     * 'default' , and this will be used for all nodes (if no uiProvider is delivered by the node data)
13349     */
13350     uiProviders : {},
13351
13352     /**
13353     * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
13354     * child nodes before loading.
13355     */
13356     clearOnLoad : true,
13357
13358     /**
13359     * @cfg {String} root (optional) Default to false. Use this to read data from an object 
13360     * property on loading, rather than expecting an array. (eg. more compatible to a standard
13361     * Grid query { data : [ .....] }
13362     */
13363     
13364     root : false,
13365      /**
13366     * @cfg {String} queryParam (optional) 
13367     * Name of the query as it will be passed on the querystring (defaults to 'node')
13368     * eg. the request will be ?node=[id]
13369     */
13370     
13371     
13372     queryParam: false,
13373     
13374     /**
13375      * Load an {@link Roo.tree.TreeNode} from the URL specified in the constructor.
13376      * This is called automatically when a node is expanded, but may be used to reload
13377      * a node (or append new children if the {@link #clearOnLoad} option is false.)
13378      * @param {Roo.tree.TreeNode} node
13379      * @param {Function} callback
13380      */
13381     load : function(node, callback){
13382         if(this.clearOnLoad){
13383             while(node.firstChild){
13384                 node.removeChild(node.firstChild);
13385             }
13386         }
13387         if(node.attributes.children){ // preloaded json children
13388             var cs = node.attributes.children;
13389             for(var i = 0, len = cs.length; i < len; i++){
13390                 node.appendChild(this.createNode(cs[i]));
13391             }
13392             if(typeof callback == "function"){
13393                 callback();
13394             }
13395         }else if(this.dataUrl){
13396             this.requestData(node, callback);
13397         }
13398     },
13399
13400     getParams: function(node){
13401         var buf = [], bp = this.baseParams;
13402         for(var key in bp){
13403             if(typeof bp[key] != "function"){
13404                 buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
13405             }
13406         }
13407         var n = this.queryParam === false ? 'node' : this.queryParam;
13408         buf.push(n + "=", encodeURIComponent(node.id));
13409         return buf.join("");
13410     },
13411
13412     requestData : function(node, callback){
13413         if(this.fireEvent("beforeload", this, node, callback) !== false){
13414             this.transId = Roo.Ajax.request({
13415                 method:this.requestMethod,
13416                 url: this.dataUrl||this.url,
13417                 success: this.handleResponse,
13418                 failure: this.handleFailure,
13419                 scope: this,
13420                 argument: {callback: callback, node: node},
13421                 params: this.getParams(node)
13422             });
13423         }else{
13424             // if the load is cancelled, make sure we notify
13425             // the node that we are done
13426             if(typeof callback == "function"){
13427                 callback();
13428             }
13429         }
13430     },
13431
13432     isLoading : function(){
13433         return this.transId ? true : false;
13434     },
13435
13436     abort : function(){
13437         if(this.isLoading()){
13438             Roo.Ajax.abort(this.transId);
13439         }
13440     },
13441
13442     // private
13443     createNode : function(attr)
13444     {
13445         // apply baseAttrs, nice idea Corey!
13446         if(this.baseAttrs){
13447             Roo.applyIf(attr, this.baseAttrs);
13448         }
13449         if(this.applyLoader !== false){
13450             attr.loader = this;
13451         }
13452         // uiProvider = depreciated..
13453         
13454         if(typeof(attr.uiProvider) == 'string'){
13455            attr.uiProvider = this.uiProviders[attr.uiProvider] || 
13456                 /**  eval:var:attr */ eval(attr.uiProvider);
13457         }
13458         if(typeof(this.uiProviders['default']) != 'undefined') {
13459             attr.uiProvider = this.uiProviders['default'];
13460         }
13461         
13462         this.fireEvent('create', this, attr);
13463         
13464         attr.leaf  = typeof(attr.leaf) == 'string' ? attr.leaf * 1 : attr.leaf;
13465         return(attr.leaf ?
13466                         new Roo.tree.TreeNode(attr) :
13467                         new Roo.tree.AsyncTreeNode(attr));
13468     },
13469
13470     processResponse : function(response, node, callback)
13471     {
13472         var json = response.responseText;
13473         try {
13474             
13475             var o = Roo.decode(json);
13476             
13477             if (this.root === false && typeof(o.success) != undefined) {
13478                 this.root = 'data'; // the default behaviour for list like data..
13479                 }
13480                 
13481             if (this.root !== false &&  !o.success) {
13482                 // it's a failure condition.
13483                 var a = response.argument;
13484                 this.fireEvent("loadexception", this, a.node, response);
13485                 Roo.log("Load failed - should have a handler really");
13486                 return;
13487             }
13488             
13489             
13490             
13491             if (this.root !== false) {
13492                  o = o[this.root];
13493             }
13494             
13495             for(var i = 0, len = o.length; i < len; i++){
13496                 var n = this.createNode(o[i]);
13497                 if(n){
13498                     node.appendChild(n);
13499                 }
13500             }
13501             if(typeof callback == "function"){
13502                 callback(this, node);
13503             }
13504         }catch(e){
13505             this.handleFailure(response);
13506         }
13507     },
13508
13509     handleResponse : function(response){
13510         this.transId = false;
13511         var a = response.argument;
13512         this.processResponse(response, a.node, a.callback);
13513         this.fireEvent("load", this, a.node, response);
13514     },
13515
13516     handleFailure : function(response)
13517     {
13518         // should handle failure better..
13519         this.transId = false;
13520         var a = response.argument;
13521         this.fireEvent("loadexception", this, a.node, response);
13522         if(typeof a.callback == "function"){
13523             a.callback(this, a.node);
13524         }
13525     }
13526 });/*
13527  * Based on:
13528  * Ext JS Library 1.1.1
13529  * Copyright(c) 2006-2007, Ext JS, LLC.
13530  *
13531  * Originally Released Under LGPL - original licence link has changed is not relivant.
13532  *
13533  * Fork - LGPL
13534  * <script type="text/javascript">
13535  */
13536
13537 /**
13538 * @class Roo.tree.TreeFilter
13539 * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes
13540 * @param {TreePanel} tree
13541 * @param {Object} config (optional)
13542  */
13543 Roo.tree.TreeFilter = function(tree, config){
13544     this.tree = tree;
13545     this.filtered = {};
13546     Roo.apply(this, config);
13547 };
13548
13549 Roo.tree.TreeFilter.prototype = {
13550     clearBlank:false,
13551     reverse:false,
13552     autoClear:false,
13553     remove:false,
13554
13555      /**
13556      * Filter the data by a specific attribute.
13557      * @param {String/RegExp} value Either string that the attribute value
13558      * should start with or a RegExp to test against the attribute
13559      * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text".
13560      * @param {TreeNode} startNode (optional) The node to start the filter at.
13561      */
13562     filter : function(value, attr, startNode){
13563         attr = attr || "text";
13564         var f;
13565         if(typeof value == "string"){
13566             var vlen = value.length;
13567             // auto clear empty filter
13568             if(vlen == 0 && this.clearBlank){
13569                 this.clear();
13570                 return;
13571             }
13572             value = value.toLowerCase();
13573             f = function(n){
13574                 return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
13575             };
13576         }else if(value.exec){ // regex?
13577             f = function(n){
13578                 return value.test(n.attributes[attr]);
13579             };
13580         }else{
13581             throw 'Illegal filter type, must be string or regex';
13582         }
13583         this.filterBy(f, null, startNode);
13584         },
13585
13586     /**
13587      * Filter by a function. The passed function will be called with each
13588      * node in the tree (or from the startNode). If the function returns true, the node is kept
13589      * otherwise it is filtered. If a node is filtered, its children are also filtered.
13590      * @param {Function} fn The filter function
13591      * @param {Object} scope (optional) The scope of the function (defaults to the current node)
13592      */
13593     filterBy : function(fn, scope, startNode){
13594         startNode = startNode || this.tree.root;
13595         if(this.autoClear){
13596             this.clear();
13597         }
13598         var af = this.filtered, rv = this.reverse;
13599         var f = function(n){
13600             if(n == startNode){
13601                 return true;
13602             }
13603             if(af[n.id]){
13604                 return false;
13605             }
13606             var m = fn.call(scope || n, n);
13607             if(!m || rv){
13608                 af[n.id] = n;
13609                 n.ui.hide();
13610                 return false;
13611             }
13612             return true;
13613         };
13614         startNode.cascade(f);
13615         if(this.remove){
13616            for(var id in af){
13617                if(typeof id != "function"){
13618                    var n = af[id];
13619                    if(n && n.parentNode){
13620                        n.parentNode.removeChild(n);
13621                    }
13622                }
13623            }
13624         }
13625     },
13626
13627     /**
13628      * Clears the current filter. Note: with the "remove" option
13629      * set a filter cannot be cleared.
13630      */
13631     clear : function(){
13632         var t = this.tree;
13633         var af = this.filtered;
13634         for(var id in af){
13635             if(typeof id != "function"){
13636                 var n = af[id];
13637                 if(n){
13638                     n.ui.show();
13639                 }
13640             }
13641         }
13642         this.filtered = {};
13643     }
13644 };
13645 /*
13646  * Based on:
13647  * Ext JS Library 1.1.1
13648  * Copyright(c) 2006-2007, Ext JS, LLC.
13649  *
13650  * Originally Released Under LGPL - original licence link has changed is not relivant.
13651  *
13652  * Fork - LGPL
13653  * <script type="text/javascript">
13654  */
13655  
13656
13657 /**
13658  * @class Roo.tree.TreeSorter
13659  * Provides sorting of nodes in a TreePanel
13660  * 
13661  * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes
13662  * @cfg {String} property The named attribute on the node to sort by (defaults to text)
13663  * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)
13664  * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf")
13665  * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)
13666  * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting
13667  * @constructor
13668  * @param {TreePanel} tree
13669  * @param {Object} config
13670  */
13671 Roo.tree.TreeSorter = function(tree, config){
13672     Roo.apply(this, config);
13673     tree.on("beforechildrenrendered", this.doSort, this);
13674     tree.on("append", this.updateSort, this);
13675     tree.on("insert", this.updateSort, this);
13676     
13677     var dsc = this.dir && this.dir.toLowerCase() == "desc";
13678     var p = this.property || "text";
13679     var sortType = this.sortType;
13680     var fs = this.folderSort;
13681     var cs = this.caseSensitive === true;
13682     var leafAttr = this.leafAttr || 'leaf';
13683
13684     this.sortFn = function(n1, n2){
13685         if(fs){
13686             if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
13687                 return 1;
13688             }
13689             if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
13690                 return -1;
13691             }
13692         }
13693         var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
13694         var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
13695         if(v1 < v2){
13696                         return dsc ? +1 : -1;
13697                 }else if(v1 > v2){
13698                         return dsc ? -1 : +1;
13699         }else{
13700                 return 0;
13701         }
13702     };
13703 };
13704
13705 Roo.tree.TreeSorter.prototype = {
13706     doSort : function(node){
13707         node.sort(this.sortFn);
13708     },
13709     
13710     compareNodes : function(n1, n2){
13711         return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
13712     },
13713     
13714     updateSort : function(tree, node){
13715         if(node.childrenRendered){
13716             this.doSort.defer(1, this, [node]);
13717         }
13718     }
13719 };/*
13720  * Based on:
13721  * Ext JS Library 1.1.1
13722  * Copyright(c) 2006-2007, Ext JS, LLC.
13723  *
13724  * Originally Released Under LGPL - original licence link has changed is not relivant.
13725  *
13726  * Fork - LGPL
13727  * <script type="text/javascript">
13728  */
13729
13730 if(Roo.dd.DropZone){
13731     
13732 Roo.tree.TreeDropZone = function(tree, config){
13733     this.allowParentInsert = false;
13734     this.allowContainerDrop = false;
13735     this.appendOnly = false;
13736     Roo.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
13737     this.tree = tree;
13738     this.lastInsertClass = "x-tree-no-status";
13739     this.dragOverData = {};
13740 };
13741
13742 Roo.extend(Roo.tree.TreeDropZone, Roo.dd.DropZone, {
13743     ddGroup : "TreeDD",
13744     scroll:  true,
13745     
13746     expandDelay : 1000,
13747     
13748     expandNode : function(node){
13749         if(node.hasChildNodes() && !node.isExpanded()){
13750             node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
13751         }
13752     },
13753     
13754     queueExpand : function(node){
13755         this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
13756     },
13757     
13758     cancelExpand : function(){
13759         if(this.expandProcId){
13760             clearTimeout(this.expandProcId);
13761             this.expandProcId = false;
13762         }
13763     },
13764     
13765     isValidDropPoint : function(n, pt, dd, e, data){
13766         if(!n || !data){ return false; }
13767         var targetNode = n.node;
13768         var dropNode = data.node;
13769         // default drop rules
13770         if(!(targetNode && targetNode.isTarget && pt)){
13771             return false;
13772         }
13773         if(pt == "append" && targetNode.allowChildren === false){
13774             return false;
13775         }
13776         if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
13777             return false;
13778         }
13779         if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
13780             return false;
13781         }
13782         // reuse the object
13783         var overEvent = this.dragOverData;
13784         overEvent.tree = this.tree;
13785         overEvent.target = targetNode;
13786         overEvent.data = data;
13787         overEvent.point = pt;
13788         overEvent.source = dd;
13789         overEvent.rawEvent = e;
13790         overEvent.dropNode = dropNode;
13791         overEvent.cancel = false;  
13792         var result = this.tree.fireEvent("nodedragover", overEvent);
13793         return overEvent.cancel === false && result !== false;
13794     },
13795     
13796     getDropPoint : function(e, n, dd)
13797     {
13798         var tn = n.node;
13799         if(tn.isRoot){
13800             return tn.allowChildren !== false ? "append" : false; // always append for root
13801         }
13802         var dragEl = n.ddel;
13803         var t = Roo.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
13804         var y = Roo.lib.Event.getPageY(e);
13805         //var noAppend = tn.allowChildren === false || tn.isLeaf();
13806         
13807         // we may drop nodes anywhere, as long as allowChildren has not been set to false..
13808         var noAppend = tn.allowChildren === false;
13809         if(this.appendOnly || tn.parentNode.allowChildren === false){
13810             return noAppend ? false : "append";
13811         }
13812         var noBelow = false;
13813         if(!this.allowParentInsert){
13814             noBelow = tn.hasChildNodes() && tn.isExpanded();
13815         }
13816         var q = (b - t) / (noAppend ? 2 : 3);
13817         if(y >= t && y < (t + q)){
13818             return "above";
13819         }else if(!noBelow && (noAppend || y >= b-q && y <= b)){
13820             return "below";
13821         }else{
13822             return "append";
13823         }
13824     },
13825     
13826     onNodeEnter : function(n, dd, e, data)
13827     {
13828         this.cancelExpand();
13829     },
13830     
13831     onNodeOver : function(n, dd, e, data)
13832     {
13833        
13834         var pt = this.getDropPoint(e, n, dd);
13835         var node = n.node;
13836         
13837         // auto node expand check
13838         if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
13839             this.queueExpand(node);
13840         }else if(pt != "append"){
13841             this.cancelExpand();
13842         }
13843         
13844         // set the insert point style on the target node
13845         var returnCls = this.dropNotAllowed;
13846         if(this.isValidDropPoint(n, pt, dd, e, data)){
13847            if(pt){
13848                var el = n.ddel;
13849                var cls;
13850                if(pt == "above"){
13851                    returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
13852                    cls = "x-tree-drag-insert-above";
13853                }else if(pt == "below"){
13854                    returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
13855                    cls = "x-tree-drag-insert-below";
13856                }else{
13857                    returnCls = "x-tree-drop-ok-append";
13858                    cls = "x-tree-drag-append";
13859                }
13860                if(this.lastInsertClass != cls){
13861                    Roo.fly(el).replaceClass(this.lastInsertClass, cls);
13862                    this.lastInsertClass = cls;
13863                }
13864            }
13865        }
13866        return returnCls;
13867     },
13868     
13869     onNodeOut : function(n, dd, e, data){
13870         
13871         this.cancelExpand();
13872         this.removeDropIndicators(n);
13873     },
13874     
13875     onNodeDrop : function(n, dd, e, data){
13876         var point = this.getDropPoint(e, n, dd);
13877         var targetNode = n.node;
13878         targetNode.ui.startDrop();
13879         if(!this.isValidDropPoint(n, point, dd, e, data)){
13880             targetNode.ui.endDrop();
13881             return false;
13882         }
13883         // first try to find the drop node
13884         var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
13885         var dropEvent = {
13886             tree : this.tree,
13887             target: targetNode,
13888             data: data,
13889             point: point,
13890             source: dd,
13891             rawEvent: e,
13892             dropNode: dropNode,
13893             cancel: !dropNode   
13894         };
13895         var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
13896         if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
13897             targetNode.ui.endDrop();
13898             return false;
13899         }
13900         // allow target changing
13901         targetNode = dropEvent.target;
13902         if(point == "append" && !targetNode.isExpanded()){
13903             targetNode.expand(false, null, function(){
13904                 this.completeDrop(dropEvent);
13905             }.createDelegate(this));
13906         }else{
13907             this.completeDrop(dropEvent);
13908         }
13909         return true;
13910     },
13911     
13912     completeDrop : function(de){
13913         var ns = de.dropNode, p = de.point, t = de.target;
13914         if(!(ns instanceof Array)){
13915             ns = [ns];
13916         }
13917         var n;
13918         for(var i = 0, len = ns.length; i < len; i++){
13919             n = ns[i];
13920             if(p == "above"){
13921                 t.parentNode.insertBefore(n, t);
13922             }else if(p == "below"){
13923                 t.parentNode.insertBefore(n, t.nextSibling);
13924             }else{
13925                 t.appendChild(n);
13926             }
13927         }
13928         n.ui.focus();
13929         if(this.tree.hlDrop){
13930             n.ui.highlight();
13931         }
13932         t.ui.endDrop();
13933         this.tree.fireEvent("nodedrop", de);
13934     },
13935     
13936     afterNodeMoved : function(dd, data, e, targetNode, dropNode){
13937         if(this.tree.hlDrop){
13938             dropNode.ui.focus();
13939             dropNode.ui.highlight();
13940         }
13941         this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
13942     },
13943     
13944     getTree : function(){
13945         return this.tree;
13946     },
13947     
13948     removeDropIndicators : function(n){
13949         if(n && n.ddel){
13950             var el = n.ddel;
13951             Roo.fly(el).removeClass([
13952                     "x-tree-drag-insert-above",
13953                     "x-tree-drag-insert-below",
13954                     "x-tree-drag-append"]);
13955             this.lastInsertClass = "_noclass";
13956         }
13957     },
13958     
13959     beforeDragDrop : function(target, e, id){
13960         this.cancelExpand();
13961         return true;
13962     },
13963     
13964     afterRepair : function(data){
13965         if(data && Roo.enableFx){
13966             data.node.ui.highlight();
13967         }
13968         this.hideProxy();
13969     } 
13970     
13971 });
13972
13973 }
13974 /*
13975  * Based on:
13976  * Ext JS Library 1.1.1
13977  * Copyright(c) 2006-2007, Ext JS, LLC.
13978  *
13979  * Originally Released Under LGPL - original licence link has changed is not relivant.
13980  *
13981  * Fork - LGPL
13982  * <script type="text/javascript">
13983  */
13984  
13985
13986 if(Roo.dd.DragZone){
13987 Roo.tree.TreeDragZone = function(tree, config){
13988     Roo.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
13989     this.tree = tree;
13990 };
13991
13992 Roo.extend(Roo.tree.TreeDragZone, Roo.dd.DragZone, {
13993     ddGroup : "TreeDD",
13994    
13995     onBeforeDrag : function(data, e){
13996         var n = data.node;
13997         return n && n.draggable && !n.disabled;
13998     },
13999      
14000     
14001     onInitDrag : function(e){
14002         var data = this.dragData;
14003         this.tree.getSelectionModel().select(data.node);
14004         this.proxy.update("");
14005         data.node.ui.appendDDGhost(this.proxy.ghost.dom);
14006         this.tree.fireEvent("startdrag", this.tree, data.node, e);
14007     },
14008     
14009     getRepairXY : function(e, data){
14010         return data.node.ui.getDDRepairXY();
14011     },
14012     
14013     onEndDrag : function(data, e){
14014         this.tree.fireEvent("enddrag", this.tree, data.node, e);
14015         
14016         
14017     },
14018     
14019     onValidDrop : function(dd, e, id){
14020         this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
14021         this.hideProxy();
14022     },
14023     
14024     beforeInvalidDrop : function(e, id){
14025         // this scrolls the original position back into view
14026         var sm = this.tree.getSelectionModel();
14027         sm.clearSelections();
14028         sm.select(this.dragData.node);
14029     }
14030 });
14031 }/*
14032  * Based on:
14033  * Ext JS Library 1.1.1
14034  * Copyright(c) 2006-2007, Ext JS, LLC.
14035  *
14036  * Originally Released Under LGPL - original licence link has changed is not relivant.
14037  *
14038  * Fork - LGPL
14039  * <script type="text/javascript">
14040  */
14041 /**
14042  * @class Roo.tree.TreeEditor
14043  * @extends Roo.Editor
14044  * Provides editor functionality for inline tree node editing.  Any valid {@link Roo.form.Field} can be used
14045  * as the editor field.
14046  * @constructor
14047  * @param {Object} config (used to be the tree panel.)
14048  * @param {Object} oldconfig DEPRECIATED Either a prebuilt {@link Roo.form.Field} instance or a Field config object
14049  * 
14050  * @cfg {Roo.tree.TreePanel} tree The tree to bind to.
14051  * @cfg {Roo.form.TextField} field [required] The field configuration
14052  *
14053  * 
14054  */
14055 Roo.tree.TreeEditor = function(config, oldconfig) { // was -- (tree, config){
14056     var tree = config;
14057     var field;
14058     if (oldconfig) { // old style..
14059         field = oldconfig.events ? oldconfig : new Roo.form.TextField(oldconfig);
14060     } else {
14061         // new style..
14062         tree = config.tree;
14063         config.field = config.field  || {};
14064         config.field.xtype = 'TextField';
14065         field = Roo.factory(config.field, Roo.form);
14066     }
14067     config = config || {};
14068     
14069     
14070     this.addEvents({
14071         /**
14072          * @event beforenodeedit
14073          * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
14074          * false from the handler of this event.
14075          * @param {Editor} this
14076          * @param {Roo.tree.Node} node 
14077          */
14078         "beforenodeedit" : true
14079     });
14080     
14081     //Roo.log(config);
14082     Roo.tree.TreeEditor.superclass.constructor.call(this, field, config);
14083
14084     this.tree = tree;
14085
14086     tree.on('beforeclick', this.beforeNodeClick, this);
14087     tree.getTreeEl().on('mousedown', this.hide, this);
14088     this.on('complete', this.updateNode, this);
14089     this.on('beforestartedit', this.fitToTree, this);
14090     this.on('startedit', this.bindScroll, this, {delay:10});
14091     this.on('specialkey', this.onSpecialKey, this);
14092 };
14093
14094 Roo.extend(Roo.tree.TreeEditor, Roo.Editor, {
14095     /**
14096      * @cfg {String} alignment
14097      * The position to align to (see {@link Roo.Element#alignTo} for more details, defaults to "l-l").
14098      */
14099     alignment: "l-l",
14100     // inherit
14101     autoSize: false,
14102     /**
14103      * @cfg {Boolean} hideEl
14104      * True to hide the bound element while the editor is displayed (defaults to false)
14105      */
14106     hideEl : false,
14107     /**
14108      * @cfg {String} cls
14109      * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
14110      */
14111     cls: "x-small-editor x-tree-editor",
14112     /**
14113      * @cfg {Boolean} shim
14114      * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
14115      */
14116     shim:false,
14117     // inherit
14118     shadow:"frame",
14119     /**
14120      * @cfg {Number} maxWidth
14121      * The maximum width in pixels of the editor field (defaults to 250).  Note that if the maxWidth would exceed
14122      * the containing tree element's size, it will be automatically limited for you to the container width, taking
14123      * scroll and client offsets into account prior to each edit.
14124      */
14125     maxWidth: 250,
14126
14127     editDelay : 350,
14128
14129     // private
14130     fitToTree : function(ed, el){
14131         var td = this.tree.getTreeEl().dom, nd = el.dom;
14132         if(td.scrollLeft >  nd.offsetLeft){ // ensure the node left point is visible
14133             td.scrollLeft = nd.offsetLeft;
14134         }
14135         var w = Math.min(
14136                 this.maxWidth,
14137                 (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
14138         this.setSize(w, '');
14139         
14140         return this.fireEvent('beforenodeedit', this, this.editNode);
14141         
14142     },
14143
14144     // private
14145     triggerEdit : function(node){
14146         this.completeEdit();
14147         this.editNode = node;
14148         this.startEdit(node.ui.textNode, node.text);
14149     },
14150
14151     // private
14152     bindScroll : function(){
14153         this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
14154     },
14155
14156     // private
14157     beforeNodeClick : function(node, e){
14158         var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
14159         this.lastClick = new Date();
14160         if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
14161             e.stopEvent();
14162             this.triggerEdit(node);
14163             return false;
14164         }
14165         return true;
14166     },
14167
14168     // private
14169     updateNode : function(ed, value){
14170         this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
14171         this.editNode.setText(value);
14172     },
14173
14174     // private
14175     onHide : function(){
14176         Roo.tree.TreeEditor.superclass.onHide.call(this);
14177         if(this.editNode){
14178             this.editNode.ui.focus();
14179         }
14180     },
14181
14182     // private
14183     onSpecialKey : function(field, e){
14184         var k = e.getKey();
14185         if(k == e.ESC){
14186             e.stopEvent();
14187             this.cancelEdit();
14188         }else if(k == e.ENTER && !e.hasModifier()){
14189             e.stopEvent();
14190             this.completeEdit();
14191         }
14192     }
14193 });//<Script type="text/javascript">
14194 /*
14195  * Based on:
14196  * Ext JS Library 1.1.1
14197  * Copyright(c) 2006-2007, Ext JS, LLC.
14198  *
14199  * Originally Released Under LGPL - original licence link has changed is not relivant.
14200  *
14201  * Fork - LGPL
14202  * <script type="text/javascript">
14203  */
14204  
14205 /**
14206  * Not documented??? - probably should be...
14207  */
14208
14209 Roo.tree.ColumnNodeUI = Roo.extend(Roo.tree.TreeNodeUI, {
14210     //focus: Roo.emptyFn, // prevent odd scrolling behavior
14211     
14212     renderElements : function(n, a, targetNode, bulkRender){
14213         //consel.log("renderElements?");
14214         this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
14215
14216         var t = n.getOwnerTree();
14217         var tid = Pman.Tab.Document_TypesTree.tree.el.id;
14218         
14219         var cols = t.columns;
14220         var bw = t.borderWidth;
14221         var c = cols[0];
14222         var href = a.href ? a.href : Roo.isGecko ? "" : "#";
14223          var cb = typeof a.checked == "boolean";
14224         var tx = String.format('{0}',n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14225         var colcls = 'x-t-' + tid + '-c0';
14226         var buf = [
14227             '<li class="x-tree-node">',
14228             
14229                 
14230                 '<div class="x-tree-node-el ', a.cls,'">',
14231                     // extran...
14232                     '<div class="x-tree-col ', colcls, '" style="width:', c.width-bw, 'px;">',
14233                 
14234                 
14235                         '<span class="x-tree-node-indent">',this.indentMarkup,'</span>',
14236                         '<img src="', this.emptyIcon, '" class="x-tree-ec-icon  " />',
14237                         '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',
14238                            (a.icon ? ' x-tree-node-inline-icon' : ''),
14239                            (a.iconCls ? ' '+a.iconCls : ''),
14240                            '" unselectable="on" />',
14241                         (cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + 
14242                              (a.checked ? 'checked="checked" />' : ' />')) : ''),
14243                              
14244                         '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14245                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>',
14246                             '<span unselectable="on" qtip="' + tx + '">',
14247                              tx,
14248                              '</span></a>' ,
14249                     '</div>',
14250                      '<a class="x-tree-node-anchor" hidefocus="on" href="',href,'" tabIndex="1" ',
14251                             (a.hrefTarget ? ' target="' +a.hrefTarget + '"' : ''), '>'
14252                  ];
14253         for(var i = 1, len = cols.length; i < len; i++){
14254             c = cols[i];
14255             colcls = 'x-t-' + tid + '-c' +i;
14256             tx = String.format('{0}', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]));
14257             buf.push('<div class="x-tree-col ', colcls, ' ' ,(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
14258                         '<div class="x-tree-col-text" qtip="' + tx +'">',tx,"</div>",
14259                       "</div>");
14260          }
14261          
14262          buf.push(
14263             '</a>',
14264             '<div class="x-clear"></div></div>',
14265             '<ul class="x-tree-node-ct" style="display:none;"></ul>',
14266             "</li>");
14267         
14268         if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
14269             this.wrap = Roo.DomHelper.insertHtml("beforeBegin",
14270                                 n.nextSibling.ui.getEl(), buf.join(""));
14271         }else{
14272             this.wrap = Roo.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
14273         }
14274         var el = this.wrap.firstChild;
14275         this.elRow = el;
14276         this.elNode = el.firstChild;
14277         this.ranchor = el.childNodes[1];
14278         this.ctNode = this.wrap.childNodes[1];
14279         var cs = el.firstChild.childNodes;
14280         this.indentNode = cs[0];
14281         this.ecNode = cs[1];
14282         this.iconNode = cs[2];
14283         var index = 3;
14284         if(cb){
14285             this.checkbox = cs[3];
14286             index++;
14287         }
14288         this.anchor = cs[index];
14289         
14290         this.textNode = cs[index].firstChild;
14291         
14292         //el.on("click", this.onClick, this);
14293         //el.on("dblclick", this.onDblClick, this);
14294         
14295         
14296        // console.log(this);
14297     },
14298     initEvents : function(){
14299         Roo.tree.ColumnNodeUI.superclass.initEvents.call(this);
14300         
14301             
14302         var a = this.ranchor;
14303
14304         var el = Roo.get(a);
14305
14306         if(Roo.isOpera){ // opera render bug ignores the CSS
14307             el.setStyle("text-decoration", "none");
14308         }
14309
14310         el.on("click", this.onClick, this);
14311         el.on("dblclick", this.onDblClick, this);
14312         el.on("contextmenu", this.onContextMenu, this);
14313         
14314     },
14315     
14316     /*onSelectedChange : function(state){
14317         if(state){
14318             this.focus();
14319             this.addClass("x-tree-selected");
14320         }else{
14321             //this.blur();
14322             this.removeClass("x-tree-selected");
14323         }
14324     },*/
14325     addClass : function(cls){
14326         if(this.elRow){
14327             Roo.fly(this.elRow).addClass(cls);
14328         }
14329         
14330     },
14331     
14332     
14333     removeClass : function(cls){
14334         if(this.elRow){
14335             Roo.fly(this.elRow).removeClass(cls);
14336         }
14337     }
14338
14339     
14340     
14341 });//<Script type="text/javascript">
14342
14343 /*
14344  * Based on:
14345  * Ext JS Library 1.1.1
14346  * Copyright(c) 2006-2007, Ext JS, LLC.
14347  *
14348  * Originally Released Under LGPL - original licence link has changed is not relivant.
14349  *
14350  * Fork - LGPL
14351  * <script type="text/javascript">
14352  */
14353  
14354
14355 /**
14356  * @class Roo.tree.ColumnTree
14357  * @extends Roo.tree.TreePanel
14358  * @cfg {Object} columns  Including width, header, renderer, cls, dataIndex 
14359  * @cfg {int} borderWidth  compined right/left border allowance
14360  * @constructor
14361  * @param {String/HTMLElement/Element} el The container element
14362  * @param {Object} config
14363  */
14364 Roo.tree.ColumnTree =  function(el, config)
14365 {
14366    Roo.tree.ColumnTree.superclass.constructor.call(this, el , config);
14367    this.addEvents({
14368         /**
14369         * @event resize
14370         * Fire this event on a container when it resizes
14371         * @param {int} w Width
14372         * @param {int} h Height
14373         */
14374        "resize" : true
14375     });
14376     this.on('resize', this.onResize, this);
14377 };
14378
14379 Roo.extend(Roo.tree.ColumnTree, Roo.tree.TreePanel, {
14380     //lines:false,
14381     
14382     
14383     borderWidth: Roo.isBorderBox ? 0 : 2, 
14384     headEls : false,
14385     
14386     render : function(){
14387         // add the header.....
14388        
14389         Roo.tree.ColumnTree.superclass.render.apply(this);
14390         
14391         this.el.addClass('x-column-tree');
14392         
14393         this.headers = this.el.createChild(
14394             {cls:'x-tree-headers'},this.innerCt.dom);
14395    
14396         var cols = this.columns, c;
14397         var totalWidth = 0;
14398         this.headEls = [];
14399         var  len = cols.length;
14400         for(var i = 0; i < len; i++){
14401              c = cols[i];
14402              totalWidth += c.width;
14403             this.headEls.push(this.headers.createChild({
14404                  cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
14405                  cn: {
14406                      cls:'x-tree-hd-text',
14407                      html: c.header
14408                  },
14409                  style:'width:'+(c.width-this.borderWidth)+'px;'
14410              }));
14411         }
14412         this.headers.createChild({cls:'x-clear'});
14413         // prevent floats from wrapping when clipped
14414         this.headers.setWidth(totalWidth);
14415         //this.innerCt.setWidth(totalWidth);
14416         this.innerCt.setStyle({ overflow: 'auto' });
14417         this.onResize(this.width, this.height);
14418              
14419         
14420     },
14421     onResize : function(w,h)
14422     {
14423         this.height = h;
14424         this.width = w;
14425         // resize cols..
14426         this.innerCt.setWidth(this.width);
14427         this.innerCt.setHeight(this.height-20);
14428         
14429         // headers...
14430         var cols = this.columns, c;
14431         var totalWidth = 0;
14432         var expEl = false;
14433         var len = cols.length;
14434         for(var i = 0; i < len; i++){
14435             c = cols[i];
14436             if (this.autoExpandColumn !== false && c.dataIndex == this.autoExpandColumn) {
14437                 // it's the expander..
14438                 expEl  = this.headEls[i];
14439                 continue;
14440             }
14441             totalWidth += c.width;
14442             
14443         }
14444         if (expEl) {
14445             expEl.setWidth(  ((w - totalWidth)-this.borderWidth - 20));
14446         }
14447         this.headers.setWidth(w-20);
14448
14449         
14450         
14451         
14452     }
14453 });
14454 /*
14455  * Based on:
14456  * Ext JS Library 1.1.1
14457  * Copyright(c) 2006-2007, Ext JS, LLC.
14458  *
14459  * Originally Released Under LGPL - original licence link has changed is not relivant.
14460  *
14461  * Fork - LGPL
14462  * <script type="text/javascript">
14463  */
14464  
14465 /**
14466  * @class Roo.menu.Menu
14467  * @extends Roo.util.Observable
14468  * @children Roo.menu.Item Roo.menu.Separator Roo.menu.TextItem
14469  * A menu object.  This is the container to which you add all other menu items.  Menu can also serve a as a base class
14470  * when you want a specialzed menu based off of another component (like {@link Roo.menu.DateMenu} for example).
14471  * @constructor
14472  * Creates a new Menu
14473  * @param {Object} config Configuration options
14474  */
14475 Roo.menu.Menu = function(config){
14476     
14477     Roo.menu.Menu.superclass.constructor.call(this, config);
14478     
14479     this.id = this.id || Roo.id();
14480     this.addEvents({
14481         /**
14482          * @event beforeshow
14483          * Fires before this menu is displayed
14484          * @param {Roo.menu.Menu} this
14485          */
14486         beforeshow : true,
14487         /**
14488          * @event beforehide
14489          * Fires before this menu is hidden
14490          * @param {Roo.menu.Menu} this
14491          */
14492         beforehide : true,
14493         /**
14494          * @event show
14495          * Fires after this menu is displayed
14496          * @param {Roo.menu.Menu} this
14497          */
14498         show : true,
14499         /**
14500          * @event hide
14501          * Fires after this menu is hidden
14502          * @param {Roo.menu.Menu} this
14503          */
14504         hide : true,
14505         /**
14506          * @event click
14507          * Fires when this menu is clicked (or when the enter key is pressed while it is active)
14508          * @param {Roo.menu.Menu} this
14509          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14510          * @param {Roo.EventObject} e
14511          */
14512         click : true,
14513         /**
14514          * @event mouseover
14515          * Fires when the mouse is hovering over this menu
14516          * @param {Roo.menu.Menu} this
14517          * @param {Roo.EventObject} e
14518          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14519          */
14520         mouseover : true,
14521         /**
14522          * @event mouseout
14523          * Fires when the mouse exits this menu
14524          * @param {Roo.menu.Menu} this
14525          * @param {Roo.EventObject} e
14526          * @param {Roo.menu.Item} menuItem The menu item that was clicked
14527          */
14528         mouseout : true,
14529         /**
14530          * @event itemclick
14531          * Fires when a menu item contained in this menu is clicked
14532          * @param {Roo.menu.BaseItem} baseItem The BaseItem that was clicked
14533          * @param {Roo.EventObject} e
14534          */
14535         itemclick: true
14536     });
14537     if (this.registerMenu) {
14538         Roo.menu.MenuMgr.register(this);
14539     }
14540     
14541     var mis = this.items;
14542     this.items = new Roo.util.MixedCollection();
14543     if(mis){
14544         this.add.apply(this, mis);
14545     }
14546 };
14547
14548 Roo.extend(Roo.menu.Menu, Roo.util.Observable, {
14549     /**
14550      * @cfg {Number} minWidth The minimum width of the menu in pixels (defaults to 120)
14551      */
14552     minWidth : 120,
14553     /**
14554      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
14555      * for bottom-right shadow (defaults to "sides")
14556      */
14557     shadow : "sides",
14558     /**
14559      * @cfg {String} subMenuAlign The {@link Roo.Element#alignTo} anchor position value to use for submenus of
14560      * this menu (defaults to "tl-tr?")
14561      */
14562     subMenuAlign : "tl-tr?",
14563     /**
14564      * @cfg {String} defaultAlign The default {@link Roo.Element#alignTo) anchor position value for this menu
14565      * relative to its element of origin (defaults to "tl-bl?")
14566      */
14567     defaultAlign : "tl-bl?",
14568     /**
14569      * @cfg {Boolean} allowOtherMenus True to allow multiple menus to be displayed at the same time (defaults to false)
14570      */
14571     allowOtherMenus : false,
14572     /**
14573      * @cfg {Boolean} registerMenu True (default) - means that clicking on screen etc. hides it.
14574      */
14575     registerMenu : true,
14576
14577     hidden:true,
14578
14579     // private
14580     render : function(){
14581         if(this.el){
14582             return;
14583         }
14584         var el = this.el = new Roo.Layer({
14585             cls: "x-menu",
14586             shadow:this.shadow,
14587             constrain: false,
14588             parentEl: this.parentEl || document.body,
14589             zindex:15000
14590         });
14591
14592         this.keyNav = new Roo.menu.MenuNav(this);
14593
14594         if(this.plain){
14595             el.addClass("x-menu-plain");
14596         }
14597         if(this.cls){
14598             el.addClass(this.cls);
14599         }
14600         // generic focus element
14601         this.focusEl = el.createChild({
14602             tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
14603         });
14604         var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
14605         //disabling touch- as it's causing issues ..
14606         //ul.on(Roo.isTouch ? 'touchstart' : 'click'   , this.onClick, this);
14607         ul.on('click'   , this.onClick, this);
14608         
14609         
14610         ul.on("mouseover", this.onMouseOver, this);
14611         ul.on("mouseout", this.onMouseOut, this);
14612         this.items.each(function(item){
14613             if (item.hidden) {
14614                 return;
14615             }
14616             
14617             var li = document.createElement("li");
14618             li.className = "x-menu-list-item";
14619             ul.dom.appendChild(li);
14620             item.render(li, this);
14621         }, this);
14622         this.ul = ul;
14623         this.autoWidth();
14624     },
14625
14626     // private
14627     autoWidth : function(){
14628         var el = this.el, ul = this.ul;
14629         if(!el){
14630             return;
14631         }
14632         var w = this.width;
14633         if(w){
14634             el.setWidth(w);
14635         }else if(Roo.isIE){
14636             el.setWidth(this.minWidth);
14637             var t = el.dom.offsetWidth; // force recalc
14638             el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
14639         }
14640     },
14641
14642     // private
14643     delayAutoWidth : function(){
14644         if(this.rendered){
14645             if(!this.awTask){
14646                 this.awTask = new Roo.util.DelayedTask(this.autoWidth, this);
14647             }
14648             this.awTask.delay(20);
14649         }
14650     },
14651
14652     // private
14653     findTargetItem : function(e){
14654         var t = e.getTarget(".x-menu-list-item", this.ul,  true);
14655         if(t && t.menuItemId){
14656             return this.items.get(t.menuItemId);
14657         }
14658     },
14659
14660     // private
14661     onClick : function(e){
14662         Roo.log("menu.onClick");
14663         var t = this.findTargetItem(e);
14664         if(!t){
14665             return;
14666         }
14667         Roo.log(e);
14668         if (Roo.isTouch && e.type == 'touchstart' && t.menu  && !t.disabled) {
14669             if(t == this.activeItem && t.shouldDeactivate(e)){
14670                 this.activeItem.deactivate();
14671                 delete this.activeItem;
14672                 return;
14673             }
14674             if(t.canActivate){
14675                 this.setActiveItem(t, true);
14676             }
14677             return;
14678             
14679             
14680         }
14681         
14682         t.onClick(e);
14683         this.fireEvent("click", this, t, e);
14684     },
14685
14686     // private
14687     setActiveItem : function(item, autoExpand){
14688         if(item != this.activeItem){
14689             if(this.activeItem){
14690                 this.activeItem.deactivate();
14691             }
14692             this.activeItem = item;
14693             item.activate(autoExpand);
14694         }else if(autoExpand){
14695             item.expandMenu();
14696         }
14697     },
14698
14699     // private
14700     tryActivate : function(start, step){
14701         var items = this.items;
14702         for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
14703             var item = items.get(i);
14704             if(!item.disabled && item.canActivate){
14705                 this.setActiveItem(item, false);
14706                 return item;
14707             }
14708         }
14709         return false;
14710     },
14711
14712     // private
14713     onMouseOver : function(e){
14714         var t;
14715         if(t = this.findTargetItem(e)){
14716             if(t.canActivate && !t.disabled){
14717                 this.setActiveItem(t, true);
14718             }
14719         }
14720         this.fireEvent("mouseover", this, e, t);
14721     },
14722
14723     // private
14724     onMouseOut : function(e){
14725         var t;
14726         if(t = this.findTargetItem(e)){
14727             if(t == this.activeItem && t.shouldDeactivate(e)){
14728                 this.activeItem.deactivate();
14729                 delete this.activeItem;
14730             }
14731         }
14732         this.fireEvent("mouseout", this, e, t);
14733     },
14734
14735     /**
14736      * Read-only.  Returns true if the menu is currently displayed, else false.
14737      * @type Boolean
14738      */
14739     isVisible : function(){
14740         return this.el && !this.hidden;
14741     },
14742
14743     /**
14744      * Displays this menu relative to another element
14745      * @param {String/HTMLElement/Roo.Element} element The element to align to
14746      * @param {String} position (optional) The {@link Roo.Element#alignTo} anchor position to use in aligning to
14747      * the element (defaults to this.defaultAlign)
14748      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
14749      */
14750     show : function(el, pos, parentMenu){
14751         this.parentMenu = parentMenu;
14752         if(!this.el){
14753             this.render();
14754         }
14755         this.fireEvent("beforeshow", this);
14756         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
14757     },
14758
14759     /**
14760      * Displays this menu at a specific xy position
14761      * @param {Array} xyPosition Contains X & Y [x, y] values for the position at which to show the menu (coordinates are page-based)
14762      * @param {Roo.menu.Menu} parentMenu (optional) This menu's parent menu, if applicable (defaults to undefined)
14763      */
14764     showAt : function(xy, parentMenu, /* private: */_e){
14765         this.parentMenu = parentMenu;
14766         if(!this.el){
14767             this.render();
14768         }
14769         if(_e !== false){
14770             this.fireEvent("beforeshow", this);
14771             xy = this.el.adjustForConstraints(xy);
14772         }
14773         this.el.setXY(xy);
14774         this.el.show();
14775         this.hidden = false;
14776         this.focus();
14777         this.fireEvent("show", this);
14778     },
14779
14780     focus : function(){
14781         if(!this.hidden){
14782             this.doFocus.defer(50, this);
14783         }
14784     },
14785
14786     doFocus : function(){
14787         if(!this.hidden){
14788             this.focusEl.focus();
14789         }
14790     },
14791
14792     /**
14793      * Hides this menu and optionally all parent menus
14794      * @param {Boolean} deep (optional) True to hide all parent menus recursively, if any (defaults to false)
14795      */
14796     hide : function(deep){
14797         if(this.el && this.isVisible()){
14798             this.fireEvent("beforehide", this);
14799             if(this.activeItem){
14800                 this.activeItem.deactivate();
14801                 this.activeItem = null;
14802             }
14803             this.el.hide();
14804             this.hidden = true;
14805             this.fireEvent("hide", this);
14806         }
14807         if(deep === true && this.parentMenu){
14808             this.parentMenu.hide(true);
14809         }
14810     },
14811
14812     /**
14813      * Addds one or more items of any type supported by the Menu class, or that can be converted into menu items.
14814      * Any of the following are valid:
14815      * <ul>
14816      * <li>Any menu item object based on {@link Roo.menu.Item}</li>
14817      * <li>An HTMLElement object which will be converted to a menu item</li>
14818      * <li>A menu item config object that will be created as a new menu item</li>
14819      * <li>A string, which can either be '-' or 'separator' to add a menu separator, otherwise
14820      * it will be converted into a {@link Roo.menu.TextItem} and added</li>
14821      * </ul>
14822      * Usage:
14823      * <pre><code>
14824 // Create the menu
14825 var menu = new Roo.menu.Menu();
14826
14827 // Create a menu item to add by reference
14828 var menuItem = new Roo.menu.Item({ text: 'New Item!' });
14829
14830 // Add a bunch of items at once using different methods.
14831 // Only the last item added will be returned.
14832 var item = menu.add(
14833     menuItem,                // add existing item by ref
14834     'Dynamic Item',          // new TextItem
14835     '-',                     // new separator
14836     { text: 'Config Item' }  // new item by config
14837 );
14838 </code></pre>
14839      * @param {Mixed} args One or more menu items, menu item configs or other objects that can be converted to menu items
14840      * @return {Roo.menu.Item} The menu item that was added, or the last one if multiple items were added
14841      */
14842     add : function(){
14843         var a = arguments, l = a.length, item;
14844         for(var i = 0; i < l; i++){
14845             var el = a[i];
14846             if ((typeof(el) == "object") && el.xtype && el.xns) {
14847                 el = Roo.factory(el, Roo.menu);
14848             }
14849             
14850             if(el.render){ // some kind of Item
14851                 item = this.addItem(el);
14852             }else if(typeof el == "string"){ // string
14853                 if(el == "separator" || el == "-"){
14854                     item = this.addSeparator();
14855                 }else{
14856                     item = this.addText(el);
14857                 }
14858             }else if(el.tagName || el.el){ // element
14859                 item = this.addElement(el);
14860             }else if(typeof el == "object"){ // must be menu item config?
14861                 item = this.addMenuItem(el);
14862             }
14863         }
14864         return item;
14865     },
14866
14867     /**
14868      * Returns this menu's underlying {@link Roo.Element} object
14869      * @return {Roo.Element} The element
14870      */
14871     getEl : function(){
14872         if(!this.el){
14873             this.render();
14874         }
14875         return this.el;
14876     },
14877
14878     /**
14879      * Adds a separator bar to the menu
14880      * @return {Roo.menu.Item} The menu item that was added
14881      */
14882     addSeparator : function(){
14883         return this.addItem(new Roo.menu.Separator());
14884     },
14885
14886     /**
14887      * Adds an {@link Roo.Element} object to the menu
14888      * @param {String/HTMLElement/Roo.Element} el The element or DOM node to add, or its id
14889      * @return {Roo.menu.Item} The menu item that was added
14890      */
14891     addElement : function(el){
14892         return this.addItem(new Roo.menu.BaseItem(el));
14893     },
14894
14895     /**
14896      * Adds an existing object based on {@link Roo.menu.Item} to the menu
14897      * @param {Roo.menu.Item} item The menu item to add
14898      * @return {Roo.menu.Item} The menu item that was added
14899      */
14900     addItem : function(item){
14901         this.items.add(item);
14902         if(this.ul){
14903             var li = document.createElement("li");
14904             li.className = "x-menu-list-item";
14905             this.ul.dom.appendChild(li);
14906             item.render(li, this);
14907             this.delayAutoWidth();
14908         }
14909         return item;
14910     },
14911
14912     /**
14913      * Creates a new {@link Roo.menu.Item} based an the supplied config object and adds it to the menu
14914      * @param {Object} config A MenuItem config object
14915      * @return {Roo.menu.Item} The menu item that was added
14916      */
14917     addMenuItem : function(config){
14918         if(!(config instanceof Roo.menu.Item)){
14919             if(typeof config.checked == "boolean"){ // must be check menu item config?
14920                 config = new Roo.menu.CheckItem(config);
14921             }else{
14922                 config = new Roo.menu.Item(config);
14923             }
14924         }
14925         return this.addItem(config);
14926     },
14927
14928     /**
14929      * Creates a new {@link Roo.menu.TextItem} with the supplied text and adds it to the menu
14930      * @param {String} text The text to display in the menu item
14931      * @return {Roo.menu.Item} The menu item that was added
14932      */
14933     addText : function(text){
14934         return this.addItem(new Roo.menu.TextItem({ text : text }));
14935     },
14936
14937     /**
14938      * Inserts an existing object based on {@link Roo.menu.Item} to the menu at a specified index
14939      * @param {Number} index The index in the menu's list of current items where the new item should be inserted
14940      * @param {Roo.menu.Item} item The menu item to add
14941      * @return {Roo.menu.Item} The menu item that was added
14942      */
14943     insert : function(index, item){
14944         this.items.insert(index, item);
14945         if(this.ul){
14946             var li = document.createElement("li");
14947             li.className = "x-menu-list-item";
14948             this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
14949             item.render(li, this);
14950             this.delayAutoWidth();
14951         }
14952         return item;
14953     },
14954
14955     /**
14956      * Removes an {@link Roo.menu.Item} from the menu and destroys the object
14957      * @param {Roo.menu.Item} item The menu item to remove
14958      */
14959     remove : function(item){
14960         this.items.removeKey(item.id);
14961         item.destroy();
14962     },
14963
14964     /**
14965      * Removes and destroys all items in the menu
14966      */
14967     removeAll : function(){
14968         var f;
14969         while(f = this.items.first()){
14970             this.remove(f);
14971         }
14972     }
14973 });
14974
14975 // MenuNav is a private utility class used internally by the Menu
14976 Roo.menu.MenuNav = function(menu){
14977     Roo.menu.MenuNav.superclass.constructor.call(this, menu.el);
14978     this.scope = this.menu = menu;
14979 };
14980
14981 Roo.extend(Roo.menu.MenuNav, Roo.KeyNav, {
14982     doRelay : function(e, h){
14983         var k = e.getKey();
14984         if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
14985             this.menu.tryActivate(0, 1);
14986             return false;
14987         }
14988         return h.call(this.scope || this, e, this.menu);
14989     },
14990
14991     up : function(e, m){
14992         if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
14993             m.tryActivate(m.items.length-1, -1);
14994         }
14995     },
14996
14997     down : function(e, m){
14998         if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
14999             m.tryActivate(0, 1);
15000         }
15001     },
15002
15003     right : function(e, m){
15004         if(m.activeItem){
15005             m.activeItem.expandMenu(true);
15006         }
15007     },
15008
15009     left : function(e, m){
15010         m.hide();
15011         if(m.parentMenu && m.parentMenu.activeItem){
15012             m.parentMenu.activeItem.activate();
15013         }
15014     },
15015
15016     enter : function(e, m){
15017         if(m.activeItem){
15018             e.stopPropagation();
15019             m.activeItem.onClick(e);
15020             m.fireEvent("click", this, m.activeItem);
15021             return true;
15022         }
15023     }
15024 });/*
15025  * Based on:
15026  * Ext JS Library 1.1.1
15027  * Copyright(c) 2006-2007, Ext JS, LLC.
15028  *
15029  * Originally Released Under LGPL - original licence link has changed is not relivant.
15030  *
15031  * Fork - LGPL
15032  * <script type="text/javascript">
15033  */
15034  
15035 /**
15036  * @class Roo.menu.MenuMgr
15037  * Provides a common registry of all menu items on a page so that they can be easily accessed by id.
15038  * @static
15039  */
15040 Roo.menu.MenuMgr = function(){
15041    var menus, active, groups = {}, attached = false, lastShow = new Date();
15042
15043    // private - called when first menu is created
15044    function init(){
15045        menus = {};
15046        active = new Roo.util.MixedCollection();
15047        Roo.get(document).addKeyListener(27, function(){
15048            if(active.length > 0){
15049                hideAll();
15050            }
15051        });
15052    }
15053
15054    // private
15055    function hideAll(){
15056        if(active && active.length > 0){
15057            var c = active.clone();
15058            c.each(function(m){
15059                m.hide();
15060            });
15061        }
15062    }
15063
15064    // private
15065    function onHide(m){
15066        active.remove(m);
15067        if(active.length < 1){
15068            Roo.get(document).un("mousedown", onMouseDown);
15069            attached = false;
15070        }
15071    }
15072
15073    // private
15074    function onShow(m){
15075        var last = active.last();
15076        lastShow = new Date();
15077        active.add(m);
15078        if(!attached){
15079            Roo.get(document).on("mousedown", onMouseDown);
15080            attached = true;
15081        }
15082        if(m.parentMenu){
15083           m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
15084           m.parentMenu.activeChild = m;
15085        }else if(last && last.isVisible()){
15086           m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
15087        }
15088    }
15089
15090    // private
15091    function onBeforeHide(m){
15092        if(m.activeChild){
15093            m.activeChild.hide();
15094        }
15095        if(m.autoHideTimer){
15096            clearTimeout(m.autoHideTimer);
15097            delete m.autoHideTimer;
15098        }
15099    }
15100
15101    // private
15102    function onBeforeShow(m){
15103        var pm = m.parentMenu;
15104        if(!pm && !m.allowOtherMenus){
15105            hideAll();
15106        }else if(pm && pm.activeChild && active != m){
15107            pm.activeChild.hide();
15108        }
15109    }
15110
15111    // private
15112    function onMouseDown(e){
15113        if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
15114            hideAll();
15115        }
15116    }
15117
15118    // private
15119    function onBeforeCheck(mi, state){
15120        if(state){
15121            var g = groups[mi.group];
15122            for(var i = 0, l = g.length; i < l; i++){
15123                if(g[i] != mi){
15124                    g[i].setChecked(false);
15125                }
15126            }
15127        }
15128    }
15129
15130    return {
15131
15132        /**
15133         * Hides all menus that are currently visible
15134         */
15135        hideAll : function(){
15136             hideAll();  
15137        },
15138
15139        // private
15140        register : function(menu){
15141            if(!menus){
15142                init();
15143            }
15144            menus[menu.id] = menu;
15145            menu.on("beforehide", onBeforeHide);
15146            menu.on("hide", onHide);
15147            menu.on("beforeshow", onBeforeShow);
15148            menu.on("show", onShow);
15149            var g = menu.group;
15150            if(g && menu.events["checkchange"]){
15151                if(!groups[g]){
15152                    groups[g] = [];
15153                }
15154                groups[g].push(menu);
15155                menu.on("checkchange", onCheck);
15156            }
15157        },
15158
15159         /**
15160          * Returns a {@link Roo.menu.Menu} object
15161          * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
15162          * be used to generate and return a new Menu instance.
15163          */
15164        get : function(menu){
15165            if(typeof menu == "string"){ // menu id
15166                return menus[menu];
15167            }else if(menu.events){  // menu instance
15168                return menu;
15169            }else if(typeof menu.length == 'number'){ // array of menu items?
15170                return new Roo.menu.Menu({items:menu});
15171            }else{ // otherwise, must be a config
15172                return new Roo.menu.Menu(menu);
15173            }
15174        },
15175
15176        // private
15177        unregister : function(menu){
15178            delete menus[menu.id];
15179            menu.un("beforehide", onBeforeHide);
15180            menu.un("hide", onHide);
15181            menu.un("beforeshow", onBeforeShow);
15182            menu.un("show", onShow);
15183            var g = menu.group;
15184            if(g && menu.events["checkchange"]){
15185                groups[g].remove(menu);
15186                menu.un("checkchange", onCheck);
15187            }
15188        },
15189
15190        // private
15191        registerCheckable : function(menuItem){
15192            var g = menuItem.group;
15193            if(g){
15194                if(!groups[g]){
15195                    groups[g] = [];
15196                }
15197                groups[g].push(menuItem);
15198                menuItem.on("beforecheckchange", onBeforeCheck);
15199            }
15200        },
15201
15202        // private
15203        unregisterCheckable : function(menuItem){
15204            var g = menuItem.group;
15205            if(g){
15206                groups[g].remove(menuItem);
15207                menuItem.un("beforecheckchange", onBeforeCheck);
15208            }
15209        }
15210    };
15211 }();/*
15212  * Based on:
15213  * Ext JS Library 1.1.1
15214  * Copyright(c) 2006-2007, Ext JS, LLC.
15215  *
15216  * Originally Released Under LGPL - original licence link has changed is not relivant.
15217  *
15218  * Fork - LGPL
15219  * <script type="text/javascript">
15220  */
15221  
15222
15223 /**
15224  * @class Roo.menu.BaseItem
15225  * @extends Roo.Component
15226  * @abstract
15227  * The base class for all items that render into menus.  BaseItem provides default rendering, activated state
15228  * management and base configuration options shared by all menu components.
15229  * @constructor
15230  * Creates a new BaseItem
15231  * @param {Object} config Configuration options
15232  */
15233 Roo.menu.BaseItem = function(config){
15234     Roo.menu.BaseItem.superclass.constructor.call(this, config);
15235
15236     this.addEvents({
15237         /**
15238          * @event click
15239          * Fires when this item is clicked
15240          * @param {Roo.menu.BaseItem} this
15241          * @param {Roo.EventObject} e
15242          */
15243         click: true,
15244         /**
15245          * @event activate
15246          * Fires when this item is activated
15247          * @param {Roo.menu.BaseItem} this
15248          */
15249         activate : true,
15250         /**
15251          * @event deactivate
15252          * Fires when this item is deactivated
15253          * @param {Roo.menu.BaseItem} this
15254          */
15255         deactivate : true
15256     });
15257
15258     if(this.handler){
15259         this.on("click", this.handler, this.scope, true);
15260     }
15261 };
15262
15263 Roo.extend(Roo.menu.BaseItem, Roo.Component, {
15264     /**
15265      * @cfg {Function} handler
15266      * A function that will handle the click event of this menu item (defaults to undefined)
15267      */
15268     /**
15269      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to false)
15270      */
15271     canActivate : false,
15272     
15273      /**
15274      * @cfg {Boolean} hidden True to prevent creation of this menu item (defaults to false)
15275      */
15276     hidden: false,
15277     
15278     /**
15279      * @cfg {String} activeClass The CSS class to use when the item becomes activated (defaults to "x-menu-item-active")
15280      */
15281     activeClass : "x-menu-item-active",
15282     /**
15283      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to true)
15284      */
15285     hideOnClick : true,
15286     /**
15287      * @cfg {Number} hideDelay Length of time in milliseconds to wait before hiding after a click (defaults to 100)
15288      */
15289     hideDelay : 100,
15290
15291     // private
15292     ctype: "Roo.menu.BaseItem",
15293
15294     // private
15295     actionMode : "container",
15296
15297     // private
15298     render : function(container, parentMenu){
15299         this.parentMenu = parentMenu;
15300         Roo.menu.BaseItem.superclass.render.call(this, container);
15301         this.container.menuItemId = this.id;
15302     },
15303
15304     // private
15305     onRender : function(container, position){
15306         this.el = Roo.get(this.el);
15307         container.dom.appendChild(this.el.dom);
15308     },
15309
15310     // private
15311     onClick : function(e){
15312         if(!this.disabled && this.fireEvent("click", this, e) !== false
15313                 && this.parentMenu.fireEvent("itemclick", this, e) !== false){
15314             this.handleClick(e);
15315         }else{
15316             e.stopEvent();
15317         }
15318     },
15319
15320     // private
15321     activate : function(){
15322         if(this.disabled){
15323             return false;
15324         }
15325         var li = this.container;
15326         li.addClass(this.activeClass);
15327         this.region = li.getRegion().adjust(2, 2, -2, -2);
15328         this.fireEvent("activate", this);
15329         return true;
15330     },
15331
15332     // private
15333     deactivate : function(){
15334         this.container.removeClass(this.activeClass);
15335         this.fireEvent("deactivate", this);
15336     },
15337
15338     // private
15339     shouldDeactivate : function(e){
15340         return !this.region || !this.region.contains(e.getPoint());
15341     },
15342
15343     // private
15344     handleClick : function(e){
15345         if(this.hideOnClick){
15346             this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
15347         }
15348     },
15349
15350     // private
15351     expandMenu : function(autoActivate){
15352         // do nothing
15353     },
15354
15355     // private
15356     hideMenu : function(){
15357         // do nothing
15358     }
15359 });/*
15360  * Based on:
15361  * Ext JS Library 1.1.1
15362  * Copyright(c) 2006-2007, Ext JS, LLC.
15363  *
15364  * Originally Released Under LGPL - original licence link has changed is not relivant.
15365  *
15366  * Fork - LGPL
15367  * <script type="text/javascript">
15368  */
15369  
15370 /**
15371  * @class Roo.menu.Adapter
15372  * @extends Roo.menu.BaseItem
15373  * @abstract
15374  * 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.
15375  * It provides basic rendering, activation management and enable/disable logic required to work in menus.
15376  * @constructor
15377  * Creates a new Adapter
15378  * @param {Object} config Configuration options
15379  */
15380 Roo.menu.Adapter = function(component, config){
15381     Roo.menu.Adapter.superclass.constructor.call(this, config);
15382     this.component = component;
15383 };
15384 Roo.extend(Roo.menu.Adapter, Roo.menu.BaseItem, {
15385     // private
15386     canActivate : true,
15387
15388     // private
15389     onRender : function(container, position){
15390         this.component.render(container);
15391         this.el = this.component.getEl();
15392     },
15393
15394     // private
15395     activate : function(){
15396         if(this.disabled){
15397             return false;
15398         }
15399         this.component.focus();
15400         this.fireEvent("activate", this);
15401         return true;
15402     },
15403
15404     // private
15405     deactivate : function(){
15406         this.fireEvent("deactivate", this);
15407     },
15408
15409     // private
15410     disable : function(){
15411         this.component.disable();
15412         Roo.menu.Adapter.superclass.disable.call(this);
15413     },
15414
15415     // private
15416     enable : function(){
15417         this.component.enable();
15418         Roo.menu.Adapter.superclass.enable.call(this);
15419     }
15420 });/*
15421  * Based on:
15422  * Ext JS Library 1.1.1
15423  * Copyright(c) 2006-2007, Ext JS, LLC.
15424  *
15425  * Originally Released Under LGPL - original licence link has changed is not relivant.
15426  *
15427  * Fork - LGPL
15428  * <script type="text/javascript">
15429  */
15430
15431 /**
15432  * @class Roo.menu.TextItem
15433  * @extends Roo.menu.BaseItem
15434  * Adds a static text string to a menu, usually used as either a heading or group separator.
15435  * Note: old style constructor with text is still supported.
15436  * 
15437  * @constructor
15438  * Creates a new TextItem
15439  * @param {Object} cfg Configuration
15440  */
15441 Roo.menu.TextItem = function(cfg){
15442     if (typeof(cfg) == 'string') {
15443         this.text = cfg;
15444     } else {
15445         Roo.apply(this,cfg);
15446     }
15447     
15448     Roo.menu.TextItem.superclass.constructor.call(this);
15449 };
15450
15451 Roo.extend(Roo.menu.TextItem, Roo.menu.BaseItem, {
15452     /**
15453      * @cfg {String} text Text to show on item.
15454      */
15455     text : '',
15456     
15457     /**
15458      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15459      */
15460     hideOnClick : false,
15461     /**
15462      * @cfg {String} itemCls The default CSS class to use for text items (defaults to "x-menu-text")
15463      */
15464     itemCls : "x-menu-text",
15465
15466     // private
15467     onRender : function(){
15468         var s = document.createElement("span");
15469         s.className = this.itemCls;
15470         s.innerHTML = this.text;
15471         this.el = s;
15472         Roo.menu.TextItem.superclass.onRender.apply(this, arguments);
15473     }
15474 });/*
15475  * Based on:
15476  * Ext JS Library 1.1.1
15477  * Copyright(c) 2006-2007, Ext JS, LLC.
15478  *
15479  * Originally Released Under LGPL - original licence link has changed is not relivant.
15480  *
15481  * Fork - LGPL
15482  * <script type="text/javascript">
15483  */
15484
15485 /**
15486  * @class Roo.menu.Separator
15487  * @extends Roo.menu.BaseItem
15488  * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
15489  * add one of these by using "-" in you call to add() or in your items config rather than creating one directly.
15490  * @constructor
15491  * @param {Object} config Configuration options
15492  */
15493 Roo.menu.Separator = function(config){
15494     Roo.menu.Separator.superclass.constructor.call(this, config);
15495 };
15496
15497 Roo.extend(Roo.menu.Separator, Roo.menu.BaseItem, {
15498     /**
15499      * @cfg {String} itemCls The default CSS class to use for separators (defaults to "x-menu-sep")
15500      */
15501     itemCls : "x-menu-sep",
15502     /**
15503      * @cfg {Boolean} hideOnClick True to hide the containing menu after this item is clicked (defaults to false)
15504      */
15505     hideOnClick : false,
15506
15507     // private
15508     onRender : function(li){
15509         var s = document.createElement("span");
15510         s.className = this.itemCls;
15511         s.innerHTML = "&#160;";
15512         this.el = s;
15513         li.addClass("x-menu-sep-li");
15514         Roo.menu.Separator.superclass.onRender.apply(this, arguments);
15515     }
15516 });/*
15517  * Based on:
15518  * Ext JS Library 1.1.1
15519  * Copyright(c) 2006-2007, Ext JS, LLC.
15520  *
15521  * Originally Released Under LGPL - original licence link has changed is not relivant.
15522  *
15523  * Fork - LGPL
15524  * <script type="text/javascript">
15525  */
15526 /**
15527  * @class Roo.menu.Item
15528  * @extends Roo.menu.BaseItem
15529  * A base class for all menu items that require menu-related functionality (like sub-menus) and are not static
15530  * display items.  Item extends the base functionality of {@link Roo.menu.BaseItem} by adding menu-specific
15531  * activation and click handling.
15532  * @constructor
15533  * Creates a new Item
15534  * @param {Object} config Configuration options
15535  */
15536 Roo.menu.Item = function(config){
15537     Roo.menu.Item.superclass.constructor.call(this, config);
15538     if(this.menu){
15539         this.menu = Roo.menu.MenuMgr.get(this.menu);
15540     }
15541 };
15542 Roo.extend(Roo.menu.Item, Roo.menu.BaseItem, {
15543     /**
15544      * @cfg {Roo.menu.Menu} menu
15545      * A Sub menu
15546      */
15547     /**
15548      * @cfg {String} text
15549      * The text to show on the menu item.
15550      */
15551     text: '',
15552      /**
15553      * @cfg {String} html to render in menu
15554      * The text to show on the menu item (HTML version).
15555      */
15556     html: '',
15557     /**
15558      * @cfg {String} icon
15559      * The path to an icon to display in this menu item (defaults to Roo.BLANK_IMAGE_URL)
15560      */
15561     icon: undefined,
15562     /**
15563      * @cfg {String} itemCls The default CSS class to use for menu items (defaults to "x-menu-item")
15564      */
15565     itemCls : "x-menu-item",
15566     /**
15567      * @cfg {Boolean} canActivate True if this item can be visually activated (defaults to true)
15568      */
15569     canActivate : true,
15570     /**
15571      * @cfg {Number} showDelay Length of time in milliseconds to wait before showing this item (defaults to 200)
15572      */
15573     showDelay: 200,
15574     // doc'd in BaseItem
15575     hideDelay: 200,
15576
15577     // private
15578     ctype: "Roo.menu.Item",
15579     
15580     // private
15581     onRender : function(container, position){
15582         var el = document.createElement("a");
15583         el.hideFocus = true;
15584         el.unselectable = "on";
15585         el.href = this.href || "#";
15586         if(this.hrefTarget){
15587             el.target = this.hrefTarget;
15588         }
15589         el.className = this.itemCls + (this.menu ?  " x-menu-item-arrow" : "") + (this.cls ?  " " + this.cls : "");
15590         
15591         var html = this.html.length ? this.html  : String.format('{0}',this.text);
15592         
15593         el.innerHTML = String.format(
15594                 '<img src="{0}" class="x-menu-item-icon {1}" />' + html,
15595                 this.icon || Roo.BLANK_IMAGE_URL, this.iconCls || '');
15596         this.el = el;
15597         Roo.menu.Item.superclass.onRender.call(this, container, position);
15598     },
15599
15600     /**
15601      * Sets the text to display in this menu item
15602      * @param {String} text The text to display
15603      * @param {Boolean} isHTML true to indicate text is pure html.
15604      */
15605     setText : function(text, isHTML){
15606         if (isHTML) {
15607             this.html = text;
15608         } else {
15609             this.text = text;
15610             this.html = '';
15611         }
15612         if(this.rendered){
15613             var html = this.html.length ? this.html  : String.format('{0}',this.text);
15614      
15615             this.el.update(String.format(
15616                 '<img src="{0}" class="x-menu-item-icon {2}">' + html,
15617                 this.icon || Roo.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
15618             this.parentMenu.autoWidth();
15619         }
15620     },
15621
15622     // private
15623     handleClick : function(e){
15624         if(!this.href){ // if no link defined, stop the event automatically
15625             e.stopEvent();
15626         }
15627         Roo.menu.Item.superclass.handleClick.apply(this, arguments);
15628     },
15629
15630     // private
15631     activate : function(autoExpand){
15632         if(Roo.menu.Item.superclass.activate.apply(this, arguments)){
15633             this.focus();
15634             if(autoExpand){
15635                 this.expandMenu();
15636             }
15637         }
15638         return true;
15639     },
15640
15641     // private
15642     shouldDeactivate : function(e){
15643         if(Roo.menu.Item.superclass.shouldDeactivate.call(this, e)){
15644             if(this.menu && this.menu.isVisible()){
15645                 return !this.menu.getEl().getRegion().contains(e.getPoint());
15646             }
15647             return true;
15648         }
15649         return false;
15650     },
15651
15652     // private
15653     deactivate : function(){
15654         Roo.menu.Item.superclass.deactivate.apply(this, arguments);
15655         this.hideMenu();
15656     },
15657
15658     // private
15659     expandMenu : function(autoActivate){
15660         if(!this.disabled && this.menu){
15661             clearTimeout(this.hideTimer);
15662             delete this.hideTimer;
15663             if(!this.menu.isVisible() && !this.showTimer){
15664                 this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
15665             }else if (this.menu.isVisible() && autoActivate){
15666                 this.menu.tryActivate(0, 1);
15667             }
15668         }
15669     },
15670
15671     // private
15672     deferExpand : function(autoActivate){
15673         delete this.showTimer;
15674         this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
15675         if(autoActivate){
15676             this.menu.tryActivate(0, 1);
15677         }
15678     },
15679
15680     // private
15681     hideMenu : function(){
15682         clearTimeout(this.showTimer);
15683         delete this.showTimer;
15684         if(!this.hideTimer && this.menu && this.menu.isVisible()){
15685             this.hideTimer = this.deferHide.defer(this.hideDelay, this);
15686         }
15687     },
15688
15689     // private
15690     deferHide : function(){
15691         delete this.hideTimer;
15692         this.menu.hide();
15693     }
15694 });/*
15695  * Based on:
15696  * Ext JS Library 1.1.1
15697  * Copyright(c) 2006-2007, Ext JS, LLC.
15698  *
15699  * Originally Released Under LGPL - original licence link has changed is not relivant.
15700  *
15701  * Fork - LGPL
15702  * <script type="text/javascript">
15703  */
15704  
15705 /**
15706  * @class Roo.menu.CheckItem
15707  * @extends Roo.menu.Item
15708  * Adds a menu item that contains a checkbox by default, but can also be part of a radio group.
15709  * @constructor
15710  * Creates a new CheckItem
15711  * @param {Object} config Configuration options
15712  */
15713 Roo.menu.CheckItem = function(config){
15714     Roo.menu.CheckItem.superclass.constructor.call(this, config);
15715     this.addEvents({
15716         /**
15717          * @event beforecheckchange
15718          * Fires before the checked value is set, providing an opportunity to cancel if needed
15719          * @param {Roo.menu.CheckItem} this
15720          * @param {Boolean} checked The new checked value that will be set
15721          */
15722         "beforecheckchange" : true,
15723         /**
15724          * @event checkchange
15725          * Fires after the checked value has been set
15726          * @param {Roo.menu.CheckItem} this
15727          * @param {Boolean} checked The checked value that was set
15728          */
15729         "checkchange" : true
15730     });
15731     if(this.checkHandler){
15732         this.on('checkchange', this.checkHandler, this.scope);
15733     }
15734 };
15735 Roo.extend(Roo.menu.CheckItem, Roo.menu.Item, {
15736     /**
15737      * @cfg {String} group
15738      * All check items with the same group name will automatically be grouped into a single-select
15739      * radio button group (defaults to '')
15740      */
15741     /**
15742      * @cfg {String} itemCls The default CSS class to use for check items (defaults to "x-menu-item x-menu-check-item")
15743      */
15744     itemCls : "x-menu-item x-menu-check-item",
15745     /**
15746      * @cfg {String} groupClass The default CSS class to use for radio group check items (defaults to "x-menu-group-item")
15747      */
15748     groupClass : "x-menu-group-item",
15749
15750     /**
15751      * @cfg {Boolean} checked True to initialize this checkbox as checked (defaults to false).  Note that
15752      * if this checkbox is part of a radio group (group = true) only the last item in the group that is
15753      * initialized with checked = true will be rendered as checked.
15754      */
15755     checked: false,
15756
15757     // private
15758     ctype: "Roo.menu.CheckItem",
15759
15760     // private
15761     onRender : function(c){
15762         Roo.menu.CheckItem.superclass.onRender.apply(this, arguments);
15763         if(this.group){
15764             this.el.addClass(this.groupClass);
15765         }
15766         Roo.menu.MenuMgr.registerCheckable(this);
15767         if(this.checked){
15768             this.checked = false;
15769             this.setChecked(true, true);
15770         }
15771     },
15772
15773     // private
15774     destroy : function(){
15775         if(this.rendered){
15776             Roo.menu.MenuMgr.unregisterCheckable(this);
15777         }
15778         Roo.menu.CheckItem.superclass.destroy.apply(this, arguments);
15779     },
15780
15781     /**
15782      * Set the checked state of this item
15783      * @param {Boolean} checked The new checked value
15784      * @param {Boolean} suppressEvent (optional) True to prevent the checkchange event from firing (defaults to false)
15785      */
15786     setChecked : function(state, suppressEvent){
15787         if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
15788             if(this.container){
15789                 this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
15790             }
15791             this.checked = state;
15792             if(suppressEvent !== true){
15793                 this.fireEvent("checkchange", this, state);
15794             }
15795         }
15796     },
15797
15798     // private
15799     handleClick : function(e){
15800        if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
15801            this.setChecked(!this.checked);
15802        }
15803        Roo.menu.CheckItem.superclass.handleClick.apply(this, arguments);
15804     }
15805 });/*
15806  * Based on:
15807  * Ext JS Library 1.1.1
15808  * Copyright(c) 2006-2007, Ext JS, LLC.
15809  *
15810  * Originally Released Under LGPL - original licence link has changed is not relivant.
15811  *
15812  * Fork - LGPL
15813  * <script type="text/javascript">
15814  */
15815  
15816 /**
15817  * @class Roo.menu.DateItem
15818  * @extends Roo.menu.Adapter
15819  * A menu item that wraps the {@link Roo.DatPicker} component.
15820  * @constructor
15821  * Creates a new DateItem
15822  * @param {Object} config Configuration options
15823  */
15824 Roo.menu.DateItem = function(config){
15825     Roo.menu.DateItem.superclass.constructor.call(this, new Roo.DatePicker(config), config);
15826     /** The Roo.DatePicker object @type Roo.DatePicker */
15827     this.picker = this.component;
15828     this.addEvents({select: true});
15829     
15830     this.picker.on("render", function(picker){
15831         picker.getEl().swallowEvent("click");
15832         picker.container.addClass("x-menu-date-item");
15833     });
15834
15835     this.picker.on("select", this.onSelect, this);
15836 };
15837
15838 Roo.extend(Roo.menu.DateItem, Roo.menu.Adapter, {
15839     // private
15840     onSelect : function(picker, date){
15841         this.fireEvent("select", this, date, picker);
15842         Roo.menu.DateItem.superclass.handleClick.call(this);
15843     }
15844 });/*
15845  * Based on:
15846  * Ext JS Library 1.1.1
15847  * Copyright(c) 2006-2007, Ext JS, LLC.
15848  *
15849  * Originally Released Under LGPL - original licence link has changed is not relivant.
15850  *
15851  * Fork - LGPL
15852  * <script type="text/javascript">
15853  */
15854  
15855 /**
15856  * @class Roo.menu.ColorItem
15857  * @extends Roo.menu.Adapter
15858  * A menu item that wraps the {@link Roo.ColorPalette} component.
15859  * @constructor
15860  * Creates a new ColorItem
15861  * @param {Object} config Configuration options
15862  */
15863 Roo.menu.ColorItem = function(config){
15864     Roo.menu.ColorItem.superclass.constructor.call(this, new Roo.ColorPalette(config), config);
15865     /** The Roo.ColorPalette object @type Roo.ColorPalette */
15866     this.palette = this.component;
15867     this.relayEvents(this.palette, ["select"]);
15868     if(this.selectHandler){
15869         this.on('select', this.selectHandler, this.scope);
15870     }
15871 };
15872 Roo.extend(Roo.menu.ColorItem, Roo.menu.Adapter);/*
15873  * Based on:
15874  * Ext JS Library 1.1.1
15875  * Copyright(c) 2006-2007, Ext JS, LLC.
15876  *
15877  * Originally Released Under LGPL - original licence link has changed is not relivant.
15878  *
15879  * Fork - LGPL
15880  * <script type="text/javascript">
15881  */
15882  
15883
15884 /**
15885  * @class Roo.menu.DateMenu
15886  * @extends Roo.menu.Menu
15887  * A menu containing a {@link Roo.menu.DateItem} component (which provides a date picker).
15888  * @constructor
15889  * Creates a new DateMenu
15890  * @param {Object} config Configuration options
15891  */
15892 Roo.menu.DateMenu = function(config){
15893     Roo.menu.DateMenu.superclass.constructor.call(this, config);
15894     this.plain = true;
15895     var di = new Roo.menu.DateItem(config);
15896     this.add(di);
15897     /**
15898      * The {@link Roo.DatePicker} instance for this DateMenu
15899      * @type DatePicker
15900      */
15901     this.picker = di.picker;
15902     /**
15903      * @event select
15904      * @param {DatePicker} picker
15905      * @param {Date} date
15906      */
15907     this.relayEvents(di, ["select"]);
15908     this.on('beforeshow', function(){
15909         if(this.picker){
15910             this.picker.hideMonthPicker(false);
15911         }
15912     }, this);
15913 };
15914 Roo.extend(Roo.menu.DateMenu, Roo.menu.Menu, {
15915     cls:'x-date-menu'
15916 });/*
15917  * Based on:
15918  * Ext JS Library 1.1.1
15919  * Copyright(c) 2006-2007, Ext JS, LLC.
15920  *
15921  * Originally Released Under LGPL - original licence link has changed is not relivant.
15922  *
15923  * Fork - LGPL
15924  * <script type="text/javascript">
15925  */
15926  
15927
15928 /**
15929  * @class Roo.menu.ColorMenu
15930  * @extends Roo.menu.Menu
15931  * A menu containing a {@link Roo.menu.ColorItem} component (which provides a basic color picker).
15932  * @constructor
15933  * Creates a new ColorMenu
15934  * @param {Object} config Configuration options
15935  */
15936 Roo.menu.ColorMenu = function(config){
15937     Roo.menu.ColorMenu.superclass.constructor.call(this, config);
15938     this.plain = true;
15939     var ci = new Roo.menu.ColorItem(config);
15940     this.add(ci);
15941     /**
15942      * The {@link Roo.ColorPalette} instance for this ColorMenu
15943      * @type ColorPalette
15944      */
15945     this.palette = ci.palette;
15946     /**
15947      * @event select
15948      * @param {ColorPalette} palette
15949      * @param {String} color
15950      */
15951     this.relayEvents(ci, ["select"]);
15952 };
15953 Roo.extend(Roo.menu.ColorMenu, Roo.menu.Menu);/*
15954  * Based on:
15955  * Ext JS Library 1.1.1
15956  * Copyright(c) 2006-2007, Ext JS, LLC.
15957  *
15958  * Originally Released Under LGPL - original licence link has changed is not relivant.
15959  *
15960  * Fork - LGPL
15961  * <script type="text/javascript">
15962  */
15963  
15964 /**
15965  * @class Roo.form.TextItem
15966  * @extends Roo.BoxComponent
15967  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
15968  * @constructor
15969  * Creates a new TextItem
15970  * @param {Object} config Configuration options
15971  */
15972 Roo.form.TextItem = function(config){
15973     Roo.form.TextItem.superclass.constructor.call(this, config);
15974 };
15975
15976 Roo.extend(Roo.form.TextItem, Roo.BoxComponent,  {
15977     
15978     /**
15979      * @cfg {String} tag the tag for this item (default div)
15980      */
15981     tag : 'div',
15982     /**
15983      * @cfg {String} html the content for this item
15984      */
15985     html : '',
15986     
15987     getAutoCreate : function()
15988     {
15989         var cfg = {
15990             id: this.id,
15991             tag: this.tag,
15992             html: this.html,
15993             cls: 'x-form-item'
15994         };
15995         
15996         return cfg;
15997         
15998     },
15999     
16000     onRender : function(ct, position)
16001     {
16002         Roo.form.TextItem.superclass.onRender.call(this, ct, position);
16003         
16004         if(!this.el){
16005             var cfg = this.getAutoCreate();
16006             if(!cfg.name){
16007                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
16008             }
16009             if (!cfg.name.length) {
16010                 delete cfg.name;
16011             }
16012             this.el = ct.createChild(cfg, position);
16013         }
16014     },
16015     /*
16016      * setHTML
16017      * @param {String} html update the Contents of the element.
16018      */
16019     setHTML : function(html)
16020     {
16021         this.fieldEl.dom.innerHTML = html;
16022     }
16023     
16024 });/*
16025  * Based on:
16026  * Ext JS Library 1.1.1
16027  * Copyright(c) 2006-2007, Ext JS, LLC.
16028  *
16029  * Originally Released Under LGPL - original licence link has changed is not relivant.
16030  *
16031  * Fork - LGPL
16032  * <script type="text/javascript">
16033  */
16034  
16035 /**
16036  * @class Roo.form.Field
16037  * @extends Roo.BoxComponent
16038  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
16039  * @constructor
16040  * Creates a new Field
16041  * @param {Object} config Configuration options
16042  */
16043 Roo.form.Field = function(config){
16044     Roo.form.Field.superclass.constructor.call(this, config);
16045 };
16046
16047 Roo.extend(Roo.form.Field, Roo.BoxComponent,  {
16048     /**
16049      * @cfg {String} fieldLabel Label to use when rendering a form.
16050      */
16051         /**
16052      * @cfg {String} labelSeparator the ':' after a field label (default :)  = set it to empty string to hide the field label.
16053      */
16054        /**
16055      * @cfg {String} qtip Mouse over tip
16056      */
16057      
16058     /**
16059      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
16060      */
16061     invalidClass : "x-form-invalid",
16062     /**
16063      * @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")
16064      */
16065     invalidText : "The value in this field is invalid",
16066     /**
16067      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus")
16068      */
16069     focusClass : "x-form-focus",
16070     /**
16071      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
16072       automatic validation (defaults to "keyup").
16073      */
16074     validationEvent : "keyup",
16075     /**
16076      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
16077      */
16078     validateOnBlur : true,
16079     /**
16080      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
16081      */
16082     validationDelay : 250,
16083     /**
16084      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
16085      * {tag: "input", type: "text", size: "20", autocomplete: "off"})
16086      */
16087     defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "new-password"},
16088     /**
16089      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
16090      */
16091     fieldClass : "x-form-field",
16092     /**
16093      * @cfg {String} msgTarget The location where error text should display.  Should be one of the following values (defaults to 'qtip'):
16094      *<pre>
16095 Value         Description
16096 -----------   ----------------------------------------------------------------------
16097 qtip          Display a quick tip when the user hovers over the field
16098 title         Display a default browser title attribute popup
16099 under         Add a block div beneath the field containing the error text
16100 side          Add an error icon to the right of the field with a popup on hover
16101 [element id]  Add the error text directly to the innerHTML of the specified element
16102 </pre>
16103      */
16104     msgTarget : 'qtip',
16105     /**
16106      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field (defaults to 'normal').
16107      */
16108     msgFx : 'normal',
16109
16110     /**
16111      * @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.
16112      */
16113     readOnly : false,
16114
16115     /**
16116      * @cfg {Boolean} disabled True to disable the field (defaults to false).
16117      */
16118     disabled : false,
16119
16120     /**
16121      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text").
16122      */
16123     inputType : undefined,
16124     
16125     /**
16126      * @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).
16127          */
16128         tabIndex : undefined,
16129         
16130     // private
16131     isFormField : true,
16132
16133     // private
16134     hasFocus : false,
16135     /**
16136      * @property {Roo.Element} fieldEl
16137      * Element Containing the rendered Field (with label etc.)
16138      */
16139     /**
16140      * @cfg {Mixed} value A value to initialize this field with.
16141      */
16142     value : undefined,
16143
16144     /**
16145      * @cfg {String} name The field's HTML name attribute.
16146      */
16147     /**
16148      * @cfg {String} cls A CSS class to apply to the field's underlying element.
16149      */
16150     // private
16151     loadedValue : false,
16152      
16153      
16154         // private ??
16155         initComponent : function(){
16156         Roo.form.Field.superclass.initComponent.call(this);
16157         this.addEvents({
16158             /**
16159              * @event focus
16160              * Fires when this field receives input focus.
16161              * @param {Roo.form.Field} this
16162              */
16163             focus : true,
16164             /**
16165              * @event blur
16166              * Fires when this field loses input focus.
16167              * @param {Roo.form.Field} this
16168              */
16169             blur : true,
16170             /**
16171              * @event specialkey
16172              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
16173              * {@link Roo.EventObject#getKey} to determine which key was pressed.
16174              * @param {Roo.form.Field} this
16175              * @param {Roo.EventObject} e The event object
16176              */
16177             specialkey : true,
16178             /**
16179              * @event change
16180              * Fires just before the field blurs if the field value has changed.
16181              * @param {Roo.form.Field} this
16182              * @param {Mixed} newValue The new value
16183              * @param {Mixed} oldValue The original value
16184              */
16185             change : true,
16186             /**
16187              * @event invalid
16188              * Fires after the field has been marked as invalid.
16189              * @param {Roo.form.Field} this
16190              * @param {String} msg The validation message
16191              */
16192             invalid : true,
16193             /**
16194              * @event valid
16195              * Fires after the field has been validated with no errors.
16196              * @param {Roo.form.Field} this
16197              */
16198             valid : true,
16199              /**
16200              * @event keyup
16201              * Fires after the key up
16202              * @param {Roo.form.Field} this
16203              * @param {Roo.EventObject}  e The event Object
16204              */
16205             keyup : true
16206         });
16207     },
16208
16209     /**
16210      * Returns the name attribute of the field if available
16211      * @return {String} name The field name
16212      */
16213     getName: function(){
16214          return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
16215     },
16216
16217     // private
16218     onRender : function(ct, position){
16219         Roo.form.Field.superclass.onRender.call(this, ct, position);
16220         if(!this.el){
16221             var cfg = this.getAutoCreate();
16222             if(!cfg.name){
16223                 cfg.name = typeof(this.name) == 'undefined' ? this.id : this.name;
16224             }
16225             if (!cfg.name.length) {
16226                 delete cfg.name;
16227             }
16228             if(this.inputType){
16229                 cfg.type = this.inputType;
16230             }
16231             this.el = ct.createChild(cfg, position);
16232         }
16233         var type = this.el.dom.type;
16234         if(type){
16235             if(type == 'password'){
16236                 type = 'text';
16237             }
16238             this.el.addClass('x-form-'+type);
16239         }
16240         if(this.readOnly){
16241             this.el.dom.readOnly = true;
16242         }
16243         if(this.tabIndex !== undefined){
16244             this.el.dom.setAttribute('tabIndex', this.tabIndex);
16245         }
16246
16247         this.el.addClass([this.fieldClass, this.cls]);
16248         this.initValue();
16249     },
16250
16251     /**
16252      * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b>
16253      * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element
16254      * @return {Roo.form.Field} this
16255      */
16256     applyTo : function(target){
16257         this.allowDomMove = false;
16258         this.el = Roo.get(target);
16259         this.render(this.el.dom.parentNode);
16260         return this;
16261     },
16262
16263     // private
16264     initValue : function(){
16265         if(this.value !== undefined){
16266             this.setValue(this.value);
16267         }else if(this.el.dom.value.length > 0){
16268             this.setValue(this.el.dom.value);
16269         }
16270     },
16271
16272     /**
16273      * Returns true if this field has been changed since it was originally loaded and is not disabled.
16274      * DEPRICATED  - it never worked well - use hasChanged/resetHasChanged.
16275      */
16276     isDirty : function() {
16277         if(this.disabled) {
16278             return false;
16279         }
16280         return String(this.getValue()) !== String(this.originalValue);
16281     },
16282
16283     /**
16284      * stores the current value in loadedValue
16285      */
16286     resetHasChanged : function()
16287     {
16288         this.loadedValue = String(this.getValue());
16289     },
16290     /**
16291      * checks the current value against the 'loaded' value.
16292      * Note - will return false if 'resetHasChanged' has not been called first.
16293      */
16294     hasChanged : function()
16295     {
16296         if(this.disabled || this.readOnly) {
16297             return false;
16298         }
16299         return this.loadedValue !== false && String(this.getValue()) !== this.loadedValue;
16300     },
16301     
16302     
16303     
16304     // private
16305     afterRender : function(){
16306         Roo.form.Field.superclass.afterRender.call(this);
16307         this.initEvents();
16308     },
16309
16310     // private
16311     fireKey : function(e){
16312         //Roo.log('field ' + e.getKey());
16313         if(e.isNavKeyPress()){
16314             this.fireEvent("specialkey", this, e);
16315         }
16316     },
16317
16318     /**
16319      * Resets the current field value to the originally loaded value and clears any validation messages
16320      */
16321     reset : function(){
16322         this.setValue(this.resetValue);
16323         this.originalValue = this.getValue();
16324         this.clearInvalid();
16325     },
16326
16327     // private
16328     initEvents : function(){
16329         // safari killled keypress - so keydown is now used..
16330         this.el.on("keydown" , this.fireKey,  this);
16331         this.el.on("focus", this.onFocus,  this);
16332         this.el.on("blur", this.onBlur,  this);
16333         this.el.relayEvent('keyup', this);
16334
16335         // reference to original value for reset
16336         this.originalValue = this.getValue();
16337         this.resetValue =  this.getValue();
16338     },
16339
16340     // private
16341     onFocus : function(){
16342         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16343             this.el.addClass(this.focusClass);
16344         }
16345         if(!this.hasFocus){
16346             this.hasFocus = true;
16347             this.startValue = this.getValue();
16348             this.fireEvent("focus", this);
16349         }
16350     },
16351
16352     beforeBlur : Roo.emptyFn,
16353
16354     // private
16355     onBlur : function(){
16356         this.beforeBlur();
16357         if(!Roo.isOpera && this.focusClass){ // don't touch in Opera
16358             this.el.removeClass(this.focusClass);
16359         }
16360         this.hasFocus = false;
16361         if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
16362             this.validate();
16363         }
16364         var v = this.getValue();
16365         if(String(v) !== String(this.startValue)){
16366             this.fireEvent('change', this, v, this.startValue);
16367         }
16368         this.fireEvent("blur", this);
16369     },
16370
16371     /**
16372      * Returns whether or not the field value is currently valid
16373      * @param {Boolean} preventMark True to disable marking the field invalid
16374      * @return {Boolean} True if the value is valid, else false
16375      */
16376     isValid : function(preventMark){
16377         if(this.disabled){
16378             return true;
16379         }
16380         var restore = this.preventMark;
16381         this.preventMark = preventMark === true;
16382         var v = this.validateValue(this.processValue(this.getRawValue()));
16383         this.preventMark = restore;
16384         return v;
16385     },
16386
16387     /**
16388      * Validates the field value
16389      * @return {Boolean} True if the value is valid, else false
16390      */
16391     validate : function(){
16392         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
16393             this.clearInvalid();
16394             return true;
16395         }
16396         return false;
16397     },
16398
16399     processValue : function(value){
16400         return value;
16401     },
16402
16403     // private
16404     // Subclasses should provide the validation implementation by overriding this
16405     validateValue : function(value){
16406         return true;
16407     },
16408
16409     /**
16410      * Mark this field as invalid
16411      * @param {String} msg The validation message
16412      */
16413     markInvalid : function(msg){
16414         if(!this.rendered || this.preventMark){ // not rendered
16415             return;
16416         }
16417         
16418         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16419         
16420         obj.el.addClass(this.invalidClass);
16421         msg = msg || this.invalidText;
16422         switch(this.msgTarget){
16423             case 'qtip':
16424                 obj.el.dom.qtip = msg;
16425                 obj.el.dom.qclass = 'x-form-invalid-tip';
16426                 if(Roo.QuickTips){ // fix for floating editors interacting with DND
16427                     Roo.QuickTips.enable();
16428                 }
16429                 break;
16430             case 'title':
16431                 this.el.dom.title = msg;
16432                 break;
16433             case 'under':
16434                 if(!this.errorEl){
16435                     var elp = this.el.findParent('.x-form-element', 5, true);
16436                     this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
16437                     this.errorEl.setWidth(elp.getWidth(true)-20);
16438                 }
16439                 this.errorEl.update(msg);
16440                 Roo.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
16441                 break;
16442             case 'side':
16443                 if(!this.errorIcon){
16444                     var elp = this.el.findParent('.x-form-element', 5, true);
16445                     this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
16446                 }
16447                 this.alignErrorIcon();
16448                 this.errorIcon.dom.qtip = msg;
16449                 this.errorIcon.dom.qclass = 'x-form-invalid-tip';
16450                 this.errorIcon.show();
16451                 this.on('resize', this.alignErrorIcon, this);
16452                 break;
16453             default:
16454                 var t = Roo.getDom(this.msgTarget);
16455                 t.innerHTML = msg;
16456                 t.style.display = this.msgDisplay;
16457                 break;
16458         }
16459         this.fireEvent('invalid', this, msg);
16460     },
16461
16462     // private
16463     alignErrorIcon : function(){
16464         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
16465     },
16466
16467     /**
16468      * Clear any invalid styles/messages for this field
16469      */
16470     clearInvalid : function(){
16471         if(!this.rendered || this.preventMark){ // not rendered
16472             return;
16473         }
16474         var obj = (typeof(this.combo) != 'undefined') ? this.combo : this; // fix the combox array!!
16475         
16476         obj.el.removeClass(this.invalidClass);
16477         switch(this.msgTarget){
16478             case 'qtip':
16479                 obj.el.dom.qtip = '';
16480                 break;
16481             case 'title':
16482                 this.el.dom.title = '';
16483                 break;
16484             case 'under':
16485                 if(this.errorEl){
16486                     Roo.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
16487                 }
16488                 break;
16489             case 'side':
16490                 if(this.errorIcon){
16491                     this.errorIcon.dom.qtip = '';
16492                     this.errorIcon.hide();
16493                     this.un('resize', this.alignErrorIcon, this);
16494                 }
16495                 break;
16496             default:
16497                 var t = Roo.getDom(this.msgTarget);
16498                 t.innerHTML = '';
16499                 t.style.display = 'none';
16500                 break;
16501         }
16502         this.fireEvent('valid', this);
16503     },
16504
16505     /**
16506      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
16507      * @return {Mixed} value The field value
16508      */
16509     getRawValue : function(){
16510         var v = this.el.getValue();
16511         
16512         return v;
16513     },
16514
16515     /**
16516      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
16517      * @return {Mixed} value The field value
16518      */
16519     getValue : function(){
16520         var v = this.el.getValue();
16521          
16522         return v;
16523     },
16524
16525     /**
16526      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
16527      * @param {Mixed} value The value to set
16528      */
16529     setRawValue : function(v){
16530         return this.el.dom.value = (v === null || v === undefined ? '' : v);
16531     },
16532
16533     /**
16534      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
16535      * @param {Mixed} value The value to set
16536      */
16537     setValue : function(v){
16538         this.value = v;
16539         if(this.rendered){
16540             this.el.dom.value = (v === null || v === undefined ? '' : v);
16541              this.validate();
16542         }
16543     },
16544
16545     adjustSize : function(w, h){
16546         var s = Roo.form.Field.superclass.adjustSize.call(this, w, h);
16547         s.width = this.adjustWidth(this.el.dom.tagName, s.width);
16548         return s;
16549     },
16550
16551     adjustWidth : function(tag, w){
16552         tag = tag.toLowerCase();
16553         if(typeof w == 'number' && Roo.isStrict && !Roo.isSafari){
16554             if(Roo.isIE && (tag == 'input' || tag == 'textarea')){
16555                 if(tag == 'input'){
16556                     return w + 2;
16557                 }
16558                 if(tag == 'textarea'){
16559                     return w-2;
16560                 }
16561             }else if(Roo.isOpera){
16562                 if(tag == 'input'){
16563                     return w + 2;
16564                 }
16565                 if(tag == 'textarea'){
16566                     return w-2;
16567                 }
16568             }
16569         }
16570         return w;
16571     }
16572 });
16573
16574
16575 // anything other than normal should be considered experimental
16576 Roo.form.Field.msgFx = {
16577     normal : {
16578         show: function(msgEl, f){
16579             msgEl.setDisplayed('block');
16580         },
16581
16582         hide : function(msgEl, f){
16583             msgEl.setDisplayed(false).update('');
16584         }
16585     },
16586
16587     slide : {
16588         show: function(msgEl, f){
16589             msgEl.slideIn('t', {stopFx:true});
16590         },
16591
16592         hide : function(msgEl, f){
16593             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
16594         }
16595     },
16596
16597     slideRight : {
16598         show: function(msgEl, f){
16599             msgEl.fixDisplay();
16600             msgEl.alignTo(f.el, 'tl-tr');
16601             msgEl.slideIn('l', {stopFx:true});
16602         },
16603
16604         hide : function(msgEl, f){
16605             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
16606         }
16607     }
16608 };/*
16609  * Based on:
16610  * Ext JS Library 1.1.1
16611  * Copyright(c) 2006-2007, Ext JS, LLC.
16612  *
16613  * Originally Released Under LGPL - original licence link has changed is not relivant.
16614  *
16615  * Fork - LGPL
16616  * <script type="text/javascript">
16617  */
16618  
16619
16620 /**
16621  * @class Roo.form.TextField
16622  * @extends Roo.form.Field
16623  * Basic text field.  Can be used as a direct replacement for traditional text inputs, or as the base
16624  * class for more sophisticated input controls (like {@link Roo.form.TextArea} and {@link Roo.form.ComboBox}).
16625  * @constructor
16626  * Creates a new TextField
16627  * @param {Object} config Configuration options
16628  */
16629 Roo.form.TextField = function(config){
16630     Roo.form.TextField.superclass.constructor.call(this, config);
16631     this.addEvents({
16632         /**
16633          * @event autosize
16634          * Fires when the autosize function is triggered.  The field may or may not have actually changed size
16635          * according to the default logic, but this event provides a hook for the developer to apply additional
16636          * logic at runtime to resize the field if needed.
16637              * @param {Roo.form.Field} this This text field
16638              * @param {Number} width The new field width
16639              */
16640         autosize : true
16641     });
16642 };
16643
16644 Roo.extend(Roo.form.TextField, Roo.form.Field,  {
16645     /**
16646      * @cfg {Boolean} grow True if this field should automatically grow and shrink to its content
16647      */
16648     grow : false,
16649     /**
16650      * @cfg {Number} growMin The minimum width to allow when grow = true (defaults to 30)
16651      */
16652     growMin : 30,
16653     /**
16654      * @cfg {Number} growMax The maximum width to allow when grow = true (defaults to 800)
16655      */
16656     growMax : 800,
16657     /**
16658      * @cfg {String} vtype A validation type name as defined in {@link Roo.form.VTypes} (defaults to null)
16659      */
16660     vtype : null,
16661     /**
16662      * @cfg {String} maskRe An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
16663      */
16664     maskRe : null,
16665     /**
16666      * @cfg {Boolean} disableKeyFilter True to disable input keystroke filtering (defaults to false)
16667      */
16668     disableKeyFilter : false,
16669     /**
16670      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to true)
16671      */
16672     allowBlank : true,
16673     /**
16674      * @cfg {Number} minLength Minimum input field length required (defaults to 0)
16675      */
16676     minLength : 0,
16677     /**
16678      * @cfg {Number} maxLength Maximum input field length allowed (defaults to Number.MAX_VALUE)
16679      */
16680     maxLength : Number.MAX_VALUE,
16681     /**
16682      * @cfg {String} minLengthText Error text to display if the minimum length validation fails (defaults to "The minimum length for this field is {minLength}")
16683      */
16684     minLengthText : "The minimum length for this field is {0}",
16685     /**
16686      * @cfg {String} maxLengthText Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
16687      */
16688     maxLengthText : "The maximum length for this field is {0}",
16689     /**
16690      * @cfg {Boolean} selectOnFocus True to automatically select any existing field text when the field receives input focus (defaults to false)
16691      */
16692     selectOnFocus : false,
16693     /**
16694      * @cfg {Boolean} allowLeadingSpace True to prevent the stripping of leading white space 
16695      */    
16696     allowLeadingSpace : false,
16697     /**
16698      * @cfg {String} blankText Error text to display if the allow blank validation fails (defaults to "This field is required")
16699      */
16700     blankText : "This field is required",
16701     /**
16702      * @cfg {Function} validator A custom validation function to be called during field validation (defaults to null).
16703      * If available, this function will be called only after the basic validators all return true, and will be passed the
16704      * current field value and expected to return boolean true if the value is valid or a string error message if invalid.
16705      */
16706     validator : null,
16707     /**
16708      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
16709      * If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
16710      * current field value.  If the test fails, the field will be marked invalid using {@link #regexText}.
16711      */
16712     regex : null,
16713     /**
16714      * @cfg {String} regexText The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
16715      */
16716     regexText : "",
16717     /**
16718      * @cfg {String} emptyText The default text to display in an empty field - placeholder... (defaults to null).
16719      */
16720     emptyText : null,
16721    
16722
16723     // private
16724     initEvents : function()
16725     {
16726         if (this.emptyText) {
16727             this.el.attr('placeholder', this.emptyText);
16728         }
16729         
16730         Roo.form.TextField.superclass.initEvents.call(this);
16731         if(this.validationEvent == 'keyup'){
16732             this.validationTask = new Roo.util.DelayedTask(this.validate, this);
16733             this.el.on('keyup', this.filterValidation, this);
16734         }
16735         else if(this.validationEvent !== false){
16736             this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay});
16737         }
16738         
16739         if(this.selectOnFocus){
16740             this.on("focus", this.preFocus, this);
16741         }
16742         if (!this.allowLeadingSpace) {
16743             this.on('blur', this.cleanLeadingSpace, this);
16744         }
16745         
16746         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Roo.form.VTypes[this.vtype+'Mask']))){
16747             this.el.on("keypress", this.filterKeys, this);
16748         }
16749         if(this.grow){
16750             this.el.on("keyup", this.onKeyUp,  this, {buffer:50});
16751             this.el.on("click", this.autoSize,  this);
16752         }
16753         if(this.el.is('input[type=password]') && Roo.isSafari){
16754             this.el.on('keydown', this.SafariOnKeyDown, this);
16755         }
16756     },
16757
16758     processValue : function(value){
16759         if(this.stripCharsRe){
16760             var newValue = value.replace(this.stripCharsRe, '');
16761             if(newValue !== value){
16762                 this.setRawValue(newValue);
16763                 return newValue;
16764             }
16765         }
16766         return value;
16767     },
16768
16769     filterValidation : function(e){
16770         if(!e.isNavKeyPress()){
16771             this.validationTask.delay(this.validationDelay);
16772         }
16773     },
16774
16775     // private
16776     onKeyUp : function(e){
16777         if(!e.isNavKeyPress()){
16778             this.autoSize();
16779         }
16780     },
16781     // private - clean the leading white space
16782     cleanLeadingSpace : function(e)
16783     {
16784         if ( this.inputType == 'file') {
16785             return;
16786         }
16787         
16788         this.setValue((this.getValue() + '').replace(/^\s+/,''));
16789     },
16790     /**
16791      * Resets the current field value to the originally-loaded value and clears any validation messages.
16792      *  
16793      */
16794     reset : function(){
16795         Roo.form.TextField.superclass.reset.call(this);
16796        
16797     }, 
16798     // private
16799     preFocus : function(){
16800         
16801         if(this.selectOnFocus){
16802             this.el.dom.select();
16803         }
16804     },
16805
16806     
16807     // private
16808     filterKeys : function(e){
16809         var k = e.getKey();
16810         if(!Roo.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
16811             return;
16812         }
16813         var c = e.getCharCode(), cc = String.fromCharCode(c);
16814         if(Roo.isIE && (e.isSpecialKey() || !cc)){
16815             return;
16816         }
16817         if(!this.maskRe.test(cc)){
16818             e.stopEvent();
16819         }
16820     },
16821
16822     setValue : function(v){
16823         
16824         Roo.form.TextField.superclass.setValue.apply(this, arguments);
16825         
16826         this.autoSize();
16827     },
16828
16829     /**
16830      * Validates a value according to the field's validation rules and marks the field as invalid
16831      * if the validation fails
16832      * @param {Mixed} value The value to validate
16833      * @return {Boolean} True if the value is valid, else false
16834      */
16835     validateValue : function(value){
16836         if(value.length < 1)  { // if it's blank
16837              if(this.allowBlank){
16838                 this.clearInvalid();
16839                 return true;
16840              }else{
16841                 this.markInvalid(this.blankText);
16842                 return false;
16843              }
16844         }
16845         if(value.length < this.minLength){
16846             this.markInvalid(String.format(this.minLengthText, this.minLength));
16847             return false;
16848         }
16849         if(value.length > this.maxLength){
16850             this.markInvalid(String.format(this.maxLengthText, this.maxLength));
16851             return false;
16852         }
16853         if(this.vtype){
16854             var vt = Roo.form.VTypes;
16855             if(!vt[this.vtype](value, this)){
16856                 this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
16857                 return false;
16858             }
16859         }
16860         if(typeof this.validator == "function"){
16861             var msg = this.validator(value);
16862             if(msg !== true){
16863                 this.markInvalid(msg);
16864                 return false;
16865             }
16866         }
16867         if(this.regex && !this.regex.test(value)){
16868             this.markInvalid(this.regexText);
16869             return false;
16870         }
16871         return true;
16872     },
16873
16874     /**
16875      * Selects text in this field
16876      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
16877      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
16878      */
16879     selectText : function(start, end){
16880         var v = this.getRawValue();
16881         if(v.length > 0){
16882             start = start === undefined ? 0 : start;
16883             end = end === undefined ? v.length : end;
16884             var d = this.el.dom;
16885             if(d.setSelectionRange){
16886                 d.setSelectionRange(start, end);
16887             }else if(d.createTextRange){
16888                 var range = d.createTextRange();
16889                 range.moveStart("character", start);
16890                 range.moveEnd("character", v.length-end);
16891                 range.select();
16892             }
16893         }
16894     },
16895
16896     /**
16897      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
16898      * This only takes effect if grow = true, and fires the autosize event.
16899      */
16900     autoSize : function(){
16901         if(!this.grow || !this.rendered){
16902             return;
16903         }
16904         if(!this.metrics){
16905             this.metrics = Roo.util.TextMetrics.createInstance(this.el);
16906         }
16907         var el = this.el;
16908         var v = el.dom.value;
16909         var d = document.createElement('div');
16910         d.appendChild(document.createTextNode(v));
16911         v = d.innerHTML;
16912         d = null;
16913         v += "&#160;";
16914         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
16915         this.el.setWidth(w);
16916         this.fireEvent("autosize", this, w);
16917     },
16918     
16919     // private
16920     SafariOnKeyDown : function(event)
16921     {
16922         // this is a workaround for a password hang bug on chrome/ webkit.
16923         
16924         var isSelectAll = false;
16925         
16926         if(this.el.dom.selectionEnd > 0){
16927             isSelectAll = (this.el.dom.selectionEnd - this.el.dom.selectionStart - this.getValue().length == 0) ? true : false;
16928         }
16929         if(((event.getKey() == 8 || event.getKey() == 46) && this.getValue().length ==1)){ // backspace and delete key
16930             event.preventDefault();
16931             this.setValue('');
16932             return;
16933         }
16934         
16935         if(isSelectAll && event.getCharCode() > 31){ // backspace and delete key
16936             
16937             event.preventDefault();
16938             // this is very hacky as keydown always get's upper case.
16939             
16940             var cc = String.fromCharCode(event.getCharCode());
16941             
16942             
16943             this.setValue( event.shiftKey ?  cc : cc.toLowerCase());
16944             
16945         }
16946         
16947         
16948     }
16949 });/*
16950  * Based on:
16951  * Ext JS Library 1.1.1
16952  * Copyright(c) 2006-2007, Ext JS, LLC.
16953  *
16954  * Originally Released Under LGPL - original licence link has changed is not relivant.
16955  *
16956  * Fork - LGPL
16957  * <script type="text/javascript">
16958  */
16959  
16960 /**
16961  * @class Roo.form.Hidden
16962  * @extends Roo.form.TextField
16963  * Simple Hidden element used on forms 
16964  * 
16965  * usage: form.add(new Roo.form.HiddenField({ 'name' : 'test1' }));
16966  * 
16967  * @constructor
16968  * Creates a new Hidden form element.
16969  * @param {Object} config Configuration options
16970  */
16971
16972
16973
16974 // easy hidden field...
16975 Roo.form.Hidden = function(config){
16976     Roo.form.Hidden.superclass.constructor.call(this, config);
16977 };
16978   
16979 Roo.extend(Roo.form.Hidden, Roo.form.TextField, {
16980     fieldLabel:      '',
16981     inputType:      'hidden',
16982     width:          50,
16983     allowBlank:     true,
16984     labelSeparator: '',
16985     hidden:         true,
16986     itemCls :       'x-form-item-display-none'
16987
16988
16989 });
16990
16991
16992 /*
16993  * Based on:
16994  * Ext JS Library 1.1.1
16995  * Copyright(c) 2006-2007, Ext JS, LLC.
16996  *
16997  * Originally Released Under LGPL - original licence link has changed is not relivant.
16998  *
16999  * Fork - LGPL
17000  * <script type="text/javascript">
17001  */
17002  
17003 /**
17004  * @class Roo.form.TriggerField
17005  * @extends Roo.form.TextField
17006  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
17007  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
17008  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
17009  * for which you can provide a custom implementation.  For example:
17010  * <pre><code>
17011 var trigger = new Roo.form.TriggerField();
17012 trigger.onTriggerClick = myTriggerFn;
17013 trigger.applyTo('my-field');
17014 </code></pre>
17015  *
17016  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
17017  * {@link Roo.form.DateField} and {@link Roo.form.ComboBox} are perfect examples of this.
17018  * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
17019  * class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
17020  * @constructor
17021  * Create a new TriggerField.
17022  * @param {Object} config Configuration options (valid {@Roo.form.TextField} config options will also be applied
17023  * to the base TextField)
17024  */
17025 Roo.form.TriggerField = function(config){
17026     this.mimicing = false;
17027     Roo.form.TriggerField.superclass.constructor.call(this, config);
17028 };
17029
17030 Roo.extend(Roo.form.TriggerField, Roo.form.TextField,  {
17031     /**
17032      * @cfg {String} triggerClass A CSS class to apply to the trigger
17033      */
17034     /**
17035      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17036      * {tag: "input", type: "text", size: "16", autocomplete: "off"})
17037      */
17038     defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "new-password"},
17039     /**
17040      * @cfg {Boolean} hideTrigger True to hide the trigger element and display only the base text field (defaults to false)
17041      */
17042     hideTrigger:false,
17043
17044     /** @cfg {Boolean} grow @hide */
17045     /** @cfg {Number} growMin @hide */
17046     /** @cfg {Number} growMax @hide */
17047
17048     /**
17049      * @hide 
17050      * @method
17051      */
17052     autoSize: Roo.emptyFn,
17053     // private
17054     monitorTab : true,
17055     // private
17056     deferHeight : true,
17057
17058     
17059     actionMode : 'wrap',
17060     // private
17061     onResize : function(w, h){
17062         Roo.form.TriggerField.superclass.onResize.apply(this, arguments);
17063         if(typeof w == 'number'){
17064             var x = w - this.trigger.getWidth();
17065             this.el.setWidth(this.adjustWidth('input', x));
17066             this.trigger.setStyle('left', x+'px');
17067         }
17068     },
17069
17070     // private
17071     adjustSize : Roo.BoxComponent.prototype.adjustSize,
17072
17073     // private
17074     getResizeEl : function(){
17075         return this.wrap;
17076     },
17077
17078     // private
17079     getPositionEl : function(){
17080         return this.wrap;
17081     },
17082
17083     // private
17084     alignErrorIcon : function(){
17085         this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
17086     },
17087
17088     // private
17089     onRender : function(ct, position){
17090         Roo.form.TriggerField.superclass.onRender.call(this, ct, position);
17091         this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
17092         this.trigger = this.wrap.createChild(this.triggerConfig ||
17093                 {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
17094         if(this.hideTrigger){
17095             this.trigger.setDisplayed(false);
17096         }
17097         this.initTrigger();
17098         if(!this.width){
17099             this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
17100         }
17101     },
17102
17103     // private
17104     initTrigger : function(){
17105         this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
17106         this.trigger.addClassOnOver('x-form-trigger-over');
17107         this.trigger.addClassOnClick('x-form-trigger-click');
17108     },
17109
17110     // private
17111     onDestroy : function(){
17112         if(this.trigger){
17113             this.trigger.removeAllListeners();
17114             this.trigger.remove();
17115         }
17116         if(this.wrap){
17117             this.wrap.remove();
17118         }
17119         Roo.form.TriggerField.superclass.onDestroy.call(this);
17120     },
17121
17122     // private
17123     onFocus : function(){
17124         Roo.form.TriggerField.superclass.onFocus.call(this);
17125         if(!this.mimicing){
17126             this.wrap.addClass('x-trigger-wrap-focus');
17127             this.mimicing = true;
17128             Roo.get(Roo.isIE ? document.body : document).on("mousedown", this.mimicBlur, this);
17129             if(this.monitorTab){
17130                 this.el.on("keydown", this.checkTab, this);
17131             }
17132         }
17133     },
17134
17135     // private
17136     checkTab : function(e){
17137         if(e.getKey() == e.TAB){
17138             this.triggerBlur();
17139         }
17140     },
17141
17142     // private
17143     onBlur : function(){
17144         // do nothing
17145     },
17146
17147     // private
17148     mimicBlur : function(e, t){
17149         if(!this.wrap.contains(t) && this.validateBlur()){
17150             this.triggerBlur();
17151         }
17152     },
17153
17154     // private
17155     triggerBlur : function(){
17156         this.mimicing = false;
17157         Roo.get(Roo.isIE ? document.body : document).un("mousedown", this.mimicBlur);
17158         if(this.monitorTab){
17159             this.el.un("keydown", this.checkTab, this);
17160         }
17161         this.wrap.removeClass('x-trigger-wrap-focus');
17162         Roo.form.TriggerField.superclass.onBlur.call(this);
17163     },
17164
17165     // private
17166     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
17167     validateBlur : function(e, t){
17168         return true;
17169     },
17170
17171     // private
17172     onDisable : function(){
17173         Roo.form.TriggerField.superclass.onDisable.call(this);
17174         if(this.wrap){
17175             this.wrap.addClass('x-item-disabled');
17176         }
17177     },
17178
17179     // private
17180     onEnable : function(){
17181         Roo.form.TriggerField.superclass.onEnable.call(this);
17182         if(this.wrap){
17183             this.wrap.removeClass('x-item-disabled');
17184         }
17185     },
17186
17187     // private
17188     onShow : function(){
17189         var ae = this.getActionEl();
17190         
17191         if(ae){
17192             ae.dom.style.display = '';
17193             ae.dom.style.visibility = 'visible';
17194         }
17195     },
17196
17197     // private
17198     
17199     onHide : function(){
17200         var ae = this.getActionEl();
17201         ae.dom.style.display = 'none';
17202     },
17203
17204     /**
17205      * The function that should handle the trigger's click event.  This method does nothing by default until overridden
17206      * by an implementing function.
17207      * @method
17208      * @param {EventObject} e
17209      */
17210     onTriggerClick : Roo.emptyFn
17211 });
17212
17213 // TwinTriggerField is not a public class to be used directly.  It is meant as an abstract base class
17214 // to be extended by an implementing class.  For an example of implementing this class, see the custom
17215 // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
17216 Roo.form.TwinTriggerField = Roo.extend(Roo.form.TriggerField, {
17217     initComponent : function(){
17218         Roo.form.TwinTriggerField.superclass.initComponent.call(this);
17219
17220         this.triggerConfig = {
17221             tag:'span', cls:'x-form-twin-triggers', cn:[
17222             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
17223             {tag: "img", src: Roo.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
17224         ]};
17225     },
17226
17227     getTrigger : function(index){
17228         return this.triggers[index];
17229     },
17230
17231     initTrigger : function(){
17232         var ts = this.trigger.select('.x-form-trigger', true);
17233         this.wrap.setStyle('overflow', 'hidden');
17234         var triggerField = this;
17235         ts.each(function(t, all, index){
17236             t.hide = function(){
17237                 var w = triggerField.wrap.getWidth();
17238                 this.dom.style.display = 'none';
17239                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17240             };
17241             t.show = function(){
17242                 var w = triggerField.wrap.getWidth();
17243                 this.dom.style.display = '';
17244                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
17245             };
17246             var triggerIndex = 'Trigger'+(index+1);
17247
17248             if(this['hide'+triggerIndex]){
17249                 t.dom.style.display = 'none';
17250             }
17251             t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
17252             t.addClassOnOver('x-form-trigger-over');
17253             t.addClassOnClick('x-form-trigger-click');
17254         }, this);
17255         this.triggers = ts.elements;
17256     },
17257
17258     onTrigger1Click : Roo.emptyFn,
17259     onTrigger2Click : Roo.emptyFn
17260 });/*
17261  * Based on:
17262  * Ext JS Library 1.1.1
17263  * Copyright(c) 2006-2007, Ext JS, LLC.
17264  *
17265  * Originally Released Under LGPL - original licence link has changed is not relivant.
17266  *
17267  * Fork - LGPL
17268  * <script type="text/javascript">
17269  */
17270  
17271 /**
17272  * @class Roo.form.TextArea
17273  * @extends Roo.form.TextField
17274  * Multiline text field.  Can be used as a direct replacement for traditional textarea fields, plus adds
17275  * support for auto-sizing.
17276  * @constructor
17277  * Creates a new TextArea
17278  * @param {Object} config Configuration options
17279  */
17280 Roo.form.TextArea = function(config){
17281     Roo.form.TextArea.superclass.constructor.call(this, config);
17282     // these are provided exchanges for backwards compat
17283     // minHeight/maxHeight were replaced by growMin/growMax to be
17284     // compatible with TextField growing config values
17285     if(this.minHeight !== undefined){
17286         this.growMin = this.minHeight;
17287     }
17288     if(this.maxHeight !== undefined){
17289         this.growMax = this.maxHeight;
17290     }
17291 };
17292
17293 Roo.extend(Roo.form.TextArea, Roo.form.TextField,  {
17294     /**
17295      * @cfg {Number} growMin The minimum height to allow when grow = true (defaults to 60)
17296      */
17297     growMin : 60,
17298     /**
17299      * @cfg {Number} growMax The maximum height to allow when grow = true (defaults to 1000)
17300      */
17301     growMax: 1000,
17302     /**
17303      * @cfg {Boolean} preventScrollbars True to prevent scrollbars from appearing regardless of how much text is
17304      * in the field (equivalent to setting overflow: hidden, defaults to false)
17305      */
17306     preventScrollbars: false,
17307     /**
17308      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
17309      * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"})
17310      */
17311
17312     // private
17313     onRender : function(ct, position){
17314         if(!this.el){
17315             this.defaultAutoCreate = {
17316                 tag: "textarea",
17317                 style:"width:300px;height:60px;",
17318                 autocomplete: "new-password"
17319             };
17320         }
17321         Roo.form.TextArea.superclass.onRender.call(this, ct, position);
17322         if(this.grow){
17323             this.textSizeEl = Roo.DomHelper.append(document.body, {
17324                 tag: "pre", cls: "x-form-grow-sizer"
17325             });
17326             if(this.preventScrollbars){
17327                 this.el.setStyle("overflow", "hidden");
17328             }
17329             this.el.setHeight(this.growMin);
17330         }
17331     },
17332
17333     onDestroy : function(){
17334         if(this.textSizeEl){
17335             this.textSizeEl.parentNode.removeChild(this.textSizeEl);
17336         }
17337         Roo.form.TextArea.superclass.onDestroy.call(this);
17338     },
17339
17340     // private
17341     onKeyUp : function(e){
17342         if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
17343             this.autoSize();
17344         }
17345     },
17346
17347     /**
17348      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
17349      * This only takes effect if grow = true, and fires the autosize event if the height changes.
17350      */
17351     autoSize : function(){
17352         if(!this.grow || !this.textSizeEl){
17353             return;
17354         }
17355         var el = this.el;
17356         var v = el.dom.value;
17357         var ts = this.textSizeEl;
17358
17359         ts.innerHTML = '';
17360         ts.appendChild(document.createTextNode(v));
17361         v = ts.innerHTML;
17362
17363         Roo.fly(ts).setWidth(this.el.getWidth());
17364         if(v.length < 1){
17365             v = "&#160;&#160;";
17366         }else{
17367             if(Roo.isIE){
17368                 v = v.replace(/\n/g, '<p>&#160;</p>');
17369             }
17370             v += "&#160;\n&#160;";
17371         }
17372         ts.innerHTML = v;
17373         var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
17374         if(h != this.lastHeight){
17375             this.lastHeight = h;
17376             this.el.setHeight(h);
17377             this.fireEvent("autosize", this, h);
17378         }
17379     }
17380 });/*
17381  * Based on:
17382  * Ext JS Library 1.1.1
17383  * Copyright(c) 2006-2007, Ext JS, LLC.
17384  *
17385  * Originally Released Under LGPL - original licence link has changed is not relivant.
17386  *
17387  * Fork - LGPL
17388  * <script type="text/javascript">
17389  */
17390  
17391
17392 /**
17393  * @class Roo.form.NumberField
17394  * @extends Roo.form.TextField
17395  * Numeric text field that provides automatic keystroke filtering and numeric validation.
17396  * @constructor
17397  * Creates a new NumberField
17398  * @param {Object} config Configuration options
17399  */
17400 Roo.form.NumberField = function(config){
17401     Roo.form.NumberField.superclass.constructor.call(this, config);
17402 };
17403
17404 Roo.extend(Roo.form.NumberField, Roo.form.TextField,  {
17405     /**
17406      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
17407      */
17408     fieldClass: "x-form-field x-form-num-field",
17409     /**
17410      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
17411      */
17412     allowDecimals : true,
17413     /**
17414      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
17415      */
17416     decimalSeparator : ".",
17417     /**
17418      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
17419      */
17420     decimalPrecision : 2,
17421     /**
17422      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
17423      */
17424     allowNegative : true,
17425     /**
17426      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
17427      */
17428     minValue : Number.NEGATIVE_INFINITY,
17429     /**
17430      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
17431      */
17432     maxValue : Number.MAX_VALUE,
17433     /**
17434      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
17435      */
17436     minText : "The minimum value for this field is {0}",
17437     /**
17438      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
17439      */
17440     maxText : "The maximum value for this field is {0}",
17441     /**
17442      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
17443      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
17444      */
17445     nanText : "{0} is not a valid number",
17446
17447     // private
17448     initEvents : function(){
17449         Roo.form.NumberField.superclass.initEvents.call(this);
17450         var allowed = "0123456789";
17451         if(this.allowDecimals){
17452             allowed += this.decimalSeparator;
17453         }
17454         if(this.allowNegative){
17455             allowed += "-";
17456         }
17457         this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
17458         var keyPress = function(e){
17459             var k = e.getKey();
17460             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
17461                 return;
17462             }
17463             var c = e.getCharCode();
17464             if(allowed.indexOf(String.fromCharCode(c)) === -1){
17465                 e.stopEvent();
17466             }
17467         };
17468         this.el.on("keypress", keyPress, this);
17469     },
17470
17471     // private
17472     validateValue : function(value){
17473         if(!Roo.form.NumberField.superclass.validateValue.call(this, value)){
17474             return false;
17475         }
17476         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
17477              return true;
17478         }
17479         var num = this.parseValue(value);
17480         if(isNaN(num)){
17481             this.markInvalid(String.format(this.nanText, value));
17482             return false;
17483         }
17484         if(num < this.minValue){
17485             this.markInvalid(String.format(this.minText, this.minValue));
17486             return false;
17487         }
17488         if(num > this.maxValue){
17489             this.markInvalid(String.format(this.maxText, this.maxValue));
17490             return false;
17491         }
17492         return true;
17493     },
17494
17495     getValue : function(){
17496         return this.fixPrecision(this.parseValue(Roo.form.NumberField.superclass.getValue.call(this)));
17497     },
17498
17499     // private
17500     parseValue : function(value){
17501         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
17502         return isNaN(value) ? '' : value;
17503     },
17504
17505     // private
17506     fixPrecision : function(value){
17507         var nan = isNaN(value);
17508         if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
17509             return nan ? '' : value;
17510         }
17511         return parseFloat(value).toFixed(this.decimalPrecision);
17512     },
17513
17514     setValue : function(v){
17515         v = this.fixPrecision(v);
17516         Roo.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
17517     },
17518
17519     // private
17520     decimalPrecisionFcn : function(v){
17521         return Math.floor(v);
17522     },
17523
17524     beforeBlur : function(){
17525         var v = this.parseValue(this.getRawValue());
17526         if(v){
17527             this.setValue(v);
17528         }
17529     }
17530 });/*
17531  * Based on:
17532  * Ext JS Library 1.1.1
17533  * Copyright(c) 2006-2007, Ext JS, LLC.
17534  *
17535  * Originally Released Under LGPL - original licence link has changed is not relivant.
17536  *
17537  * Fork - LGPL
17538  * <script type="text/javascript">
17539  */
17540  
17541 /**
17542  * @class Roo.form.DateField
17543  * @extends Roo.form.TriggerField
17544  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
17545 * @constructor
17546 * Create a new DateField
17547 * @param {Object} config
17548  */
17549 Roo.form.DateField = function(config)
17550 {
17551     Roo.form.DateField.superclass.constructor.call(this, config);
17552     
17553       this.addEvents({
17554          
17555         /**
17556          * @event select
17557          * Fires when a date is selected
17558              * @param {Roo.form.DateField} combo This combo box
17559              * @param {Date} date The date selected
17560              */
17561         'select' : true
17562          
17563     });
17564     
17565     
17566     if(typeof this.minValue == "string") {
17567         this.minValue = this.parseDate(this.minValue);
17568     }
17569     if(typeof this.maxValue == "string") {
17570         this.maxValue = this.parseDate(this.maxValue);
17571     }
17572     this.ddMatch = null;
17573     if(this.disabledDates){
17574         var dd = this.disabledDates;
17575         var re = "(?:";
17576         for(var i = 0; i < dd.length; i++){
17577             re += dd[i];
17578             if(i != dd.length-1) {
17579                 re += "|";
17580             }
17581         }
17582         this.ddMatch = new RegExp(re + ")");
17583     }
17584 };
17585
17586 Roo.extend(Roo.form.DateField, Roo.form.TriggerField,  {
17587     /**
17588      * @cfg {String} format
17589      * The default date format string which can be overriden for localization support.  The format must be
17590      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
17591      */
17592     format : "m/d/y",
17593     /**
17594      * @cfg {String} altFormats
17595      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
17596      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
17597      */
17598     altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d",
17599     /**
17600      * @cfg {Array} disabledDays
17601      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
17602      */
17603     disabledDays : null,
17604     /**
17605      * @cfg {String} disabledDaysText
17606      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
17607      */
17608     disabledDaysText : "Disabled",
17609     /**
17610      * @cfg {Array} disabledDates
17611      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
17612      * expression so they are very powerful. Some examples:
17613      * <ul>
17614      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
17615      * <li>["03/08", "09/16"] would disable those days for every year</li>
17616      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
17617      * <li>["03/../2006"] would disable every day in March 2006</li>
17618      * <li>["^03"] would disable every day in every March</li>
17619      * </ul>
17620      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
17621      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
17622      */
17623     disabledDates : null,
17624     /**
17625      * @cfg {String} disabledDatesText
17626      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
17627      */
17628     disabledDatesText : "Disabled",
17629         
17630         
17631         /**
17632      * @cfg {Date/String} zeroValue
17633      * if the date is less that this number, then the field is rendered as empty
17634      * default is 1800
17635      */
17636         zeroValue : '1800-01-01',
17637         
17638         
17639     /**
17640      * @cfg {Date/String} minValue
17641      * The minimum allowed date. Can be either a Javascript date object or a string date in a
17642      * valid format (defaults to null).
17643      */
17644     minValue : null,
17645     /**
17646      * @cfg {Date/String} maxValue
17647      * The maximum allowed date. Can be either a Javascript date object or a string date in a
17648      * valid format (defaults to null).
17649      */
17650     maxValue : null,
17651     /**
17652      * @cfg {String} minText
17653      * The error text to display when the date in the cell is before minValue (defaults to
17654      * 'The date in this field must be after {minValue}').
17655      */
17656     minText : "The date in this field must be equal to or after {0}",
17657     /**
17658      * @cfg {String} maxText
17659      * The error text to display when the date in the cell is after maxValue (defaults to
17660      * 'The date in this field must be before {maxValue}').
17661      */
17662     maxText : "The date in this field must be equal to or before {0}",
17663     /**
17664      * @cfg {String} invalidText
17665      * The error text to display when the date in the field is invalid (defaults to
17666      * '{value} is not a valid date - it must be in the format {format}').
17667      */
17668     invalidText : "{0} is not a valid date - it must be in the format {1}",
17669     /**
17670      * @cfg {String} triggerClass
17671      * An additional CSS class used to style the trigger button.  The trigger will always get the
17672      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
17673      * which displays a calendar icon).
17674      */
17675     triggerClass : 'x-form-date-trigger',
17676     
17677
17678     /**
17679      * @cfg {Boolean} useIso
17680      * if enabled, then the date field will use a hidden field to store the 
17681      * real value as iso formated date. default (false)
17682      */ 
17683     useIso : false,
17684     /**
17685      * @cfg {String/Object} autoCreate
17686      * A DomHelper element spec, or true for a default element spec (defaults to
17687      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
17688      */ 
17689     // private
17690     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
17691     
17692     // private
17693     hiddenField: false,
17694     
17695     onRender : function(ct, position)
17696     {
17697         Roo.form.DateField.superclass.onRender.call(this, ct, position);
17698         if (this.useIso) {
17699             //this.el.dom.removeAttribute('name'); 
17700             Roo.log("Changing name?");
17701             this.el.dom.setAttribute('name', this.name + '____hidden___' ); 
17702             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
17703                     'before', true);
17704             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
17705             // prevent input submission
17706             this.hiddenName = this.name;
17707         }
17708             
17709             
17710     },
17711     
17712     // private
17713     validateValue : function(value)
17714     {
17715         value = this.formatDate(value);
17716         if(!Roo.form.DateField.superclass.validateValue.call(this, value)){
17717             Roo.log('super failed');
17718             return false;
17719         }
17720         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
17721              return true;
17722         }
17723         var svalue = value;
17724         value = this.parseDate(value);
17725         if(!value){
17726             Roo.log('parse date failed' + svalue);
17727             this.markInvalid(String.format(this.invalidText, svalue, this.format));
17728             return false;
17729         }
17730         var time = value.getTime();
17731         if(this.minValue && time < this.minValue.getTime()){
17732             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
17733             return false;
17734         }
17735         if(this.maxValue && time > this.maxValue.getTime()){
17736             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
17737             return false;
17738         }
17739         if(this.disabledDays){
17740             var day = value.getDay();
17741             for(var i = 0; i < this.disabledDays.length; i++) {
17742                 if(day === this.disabledDays[i]){
17743                     this.markInvalid(this.disabledDaysText);
17744                     return false;
17745                 }
17746             }
17747         }
17748         var fvalue = this.formatDate(value);
17749         if(this.ddMatch && this.ddMatch.test(fvalue)){
17750             this.markInvalid(String.format(this.disabledDatesText, fvalue));
17751             return false;
17752         }
17753         return true;
17754     },
17755
17756     // private
17757     // Provides logic to override the default TriggerField.validateBlur which just returns true
17758     validateBlur : function(){
17759         return !this.menu || !this.menu.isVisible();
17760     },
17761     
17762     getName: function()
17763     {
17764         // returns hidden if it's set..
17765         if (!this.rendered) {return ''};
17766         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
17767         
17768     },
17769
17770     /**
17771      * Returns the current date value of the date field.
17772      * @return {Date} The date value
17773      */
17774     getValue : function(){
17775         
17776         return  this.hiddenField ?
17777                 this.hiddenField.value :
17778                 this.parseDate(Roo.form.DateField.superclass.getValue.call(this)) || "";
17779     },
17780
17781     /**
17782      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
17783      * date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
17784      * (the default format used is "m/d/y").
17785      * <br />Usage:
17786      * <pre><code>
17787 //All of these calls set the same date value (May 4, 2006)
17788
17789 //Pass a date object:
17790 var dt = new Date('5/4/06');
17791 dateField.setValue(dt);
17792
17793 //Pass a date string (default format):
17794 dateField.setValue('5/4/06');
17795
17796 //Pass a date string (custom format):
17797 dateField.format = 'Y-m-d';
17798 dateField.setValue('2006-5-4');
17799 </code></pre>
17800      * @param {String/Date} date The date or valid date string
17801      */
17802     setValue : function(date){
17803         if (this.hiddenField) {
17804             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
17805         }
17806         Roo.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
17807         // make sure the value field is always stored as a date..
17808         this.value = this.parseDate(date);
17809         
17810         
17811     },
17812
17813     // private
17814     parseDate : function(value){
17815                 
17816                 if (value instanceof Date) {
17817                         if (value < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
17818                                 return  '';
17819                         }
17820                         return value;
17821                 }
17822                 
17823                 
17824         if(!value || value instanceof Date){
17825             return value;
17826         }
17827         var v = Date.parseDate(value, this.format);
17828          if (!v && this.useIso) {
17829             v = Date.parseDate(value, 'Y-m-d');
17830         }
17831         if(!v && this.altFormats){
17832             if(!this.altFormatsArray){
17833                 this.altFormatsArray = this.altFormats.split("|");
17834             }
17835             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
17836                 v = Date.parseDate(value, this.altFormatsArray[i]);
17837             }
17838         }
17839                 if (v < Date.parseDate(this.zeroValue, 'Y-m-d') ) {
17840                         v = '';
17841                 }
17842         return v;
17843     },
17844
17845     // private
17846     formatDate : function(date, fmt){
17847         return (!date || !(date instanceof Date)) ?
17848                date : date.dateFormat(fmt || this.format);
17849     },
17850
17851     // private
17852     menuListeners : {
17853         select: function(m, d){
17854             
17855             this.setValue(d);
17856             this.fireEvent('select', this, d);
17857         },
17858         show : function(){ // retain focus styling
17859             this.onFocus();
17860         },
17861         hide : function(){
17862             this.focus.defer(10, this);
17863             var ml = this.menuListeners;
17864             this.menu.un("select", ml.select,  this);
17865             this.menu.un("show", ml.show,  this);
17866             this.menu.un("hide", ml.hide,  this);
17867         }
17868     },
17869
17870     // private
17871     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
17872     onTriggerClick : function(){
17873         if(this.disabled){
17874             return;
17875         }
17876         if(this.menu == null){
17877             this.menu = new Roo.menu.DateMenu();
17878         }
17879         Roo.apply(this.menu.picker,  {
17880             showClear: this.allowBlank,
17881             minDate : this.minValue,
17882             maxDate : this.maxValue,
17883             disabledDatesRE : this.ddMatch,
17884             disabledDatesText : this.disabledDatesText,
17885             disabledDays : this.disabledDays,
17886             disabledDaysText : this.disabledDaysText,
17887             format : this.useIso ? 'Y-m-d' : this.format,
17888             minText : String.format(this.minText, this.formatDate(this.minValue)),
17889             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
17890         });
17891         this.menu.on(Roo.apply({}, this.menuListeners, {
17892             scope:this
17893         }));
17894         this.menu.picker.setValue(this.getValue() || new Date());
17895         this.menu.show(this.el, "tl-bl?");
17896     },
17897
17898     beforeBlur : function(){
17899         var v = this.parseDate(this.getRawValue());
17900         if(v){
17901             this.setValue(v);
17902         }
17903     },
17904
17905     /*@
17906      * overide
17907      * 
17908      */
17909     isDirty : function() {
17910         if(this.disabled) {
17911             return false;
17912         }
17913         
17914         if(typeof(this.startValue) === 'undefined'){
17915             return false;
17916         }
17917         
17918         return String(this.getValue()) !== String(this.startValue);
17919         
17920     },
17921     // @overide
17922     cleanLeadingSpace : function(e)
17923     {
17924        return;
17925     }
17926     
17927 });/*
17928  * Based on:
17929  * Ext JS Library 1.1.1
17930  * Copyright(c) 2006-2007, Ext JS, LLC.
17931  *
17932  * Originally Released Under LGPL - original licence link has changed is not relivant.
17933  *
17934  * Fork - LGPL
17935  * <script type="text/javascript">
17936  */
17937  
17938 /**
17939  * @class Roo.form.MonthField
17940  * @extends Roo.form.TriggerField
17941  * Provides a date input field with a {@link Roo.DatePicker} dropdown and automatic date validation.
17942 * @constructor
17943 * Create a new MonthField
17944 * @param {Object} config
17945  */
17946 Roo.form.MonthField = function(config){
17947     
17948     Roo.form.MonthField.superclass.constructor.call(this, config);
17949     
17950       this.addEvents({
17951          
17952         /**
17953          * @event select
17954          * Fires when a date is selected
17955              * @param {Roo.form.MonthFieeld} combo This combo box
17956              * @param {Date} date The date selected
17957              */
17958         'select' : true
17959          
17960     });
17961     
17962     
17963     if(typeof this.minValue == "string") {
17964         this.minValue = this.parseDate(this.minValue);
17965     }
17966     if(typeof this.maxValue == "string") {
17967         this.maxValue = this.parseDate(this.maxValue);
17968     }
17969     this.ddMatch = null;
17970     if(this.disabledDates){
17971         var dd = this.disabledDates;
17972         var re = "(?:";
17973         for(var i = 0; i < dd.length; i++){
17974             re += dd[i];
17975             if(i != dd.length-1) {
17976                 re += "|";
17977             }
17978         }
17979         this.ddMatch = new RegExp(re + ")");
17980     }
17981 };
17982
17983 Roo.extend(Roo.form.MonthField, Roo.form.TriggerField,  {
17984     /**
17985      * @cfg {String} format
17986      * The default date format string which can be overriden for localization support.  The format must be
17987      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
17988      */
17989     format : "M Y",
17990     /**
17991      * @cfg {String} altFormats
17992      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
17993      * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d').
17994      */
17995     altFormats : "M Y|m/Y|m-y|m-Y|my|mY",
17996     /**
17997      * @cfg {Array} disabledDays
17998      * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
17999      */
18000     disabledDays : [0,1,2,3,4,5,6],
18001     /**
18002      * @cfg {String} disabledDaysText
18003      * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
18004      */
18005     disabledDaysText : "Disabled",
18006     /**
18007      * @cfg {Array} disabledDates
18008      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
18009      * expression so they are very powerful. Some examples:
18010      * <ul>
18011      * <li>["03/08/2003", "09/16/2003"] would disable those exact dates</li>
18012      * <li>["03/08", "09/16"] would disable those days for every year</li>
18013      * <li>["^03/08"] would only match the beginning (useful if you are using short years)</li>
18014      * <li>["03/../2006"] would disable every day in March 2006</li>
18015      * <li>["^03"] would disable every day in every March</li>
18016      * </ul>
18017      * In order to support regular expressions, if you are using a date format that has "." in it, you will have to
18018      * escape the dot when restricting dates. For example: ["03\\.08\\.03"].
18019      */
18020     disabledDates : null,
18021     /**
18022      * @cfg {String} disabledDatesText
18023      * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
18024      */
18025     disabledDatesText : "Disabled",
18026     /**
18027      * @cfg {Date/String} minValue
18028      * The minimum allowed date. Can be either a Javascript date object or a string date in a
18029      * valid format (defaults to null).
18030      */
18031     minValue : null,
18032     /**
18033      * @cfg {Date/String} maxValue
18034      * The maximum allowed date. Can be either a Javascript date object or a string date in a
18035      * valid format (defaults to null).
18036      */
18037     maxValue : null,
18038     /**
18039      * @cfg {String} minText
18040      * The error text to display when the date in the cell is before minValue (defaults to
18041      * 'The date in this field must be after {minValue}').
18042      */
18043     minText : "The date in this field must be equal to or after {0}",
18044     /**
18045      * @cfg {String} maxTextf
18046      * The error text to display when the date in the cell is after maxValue (defaults to
18047      * 'The date in this field must be before {maxValue}').
18048      */
18049     maxText : "The date in this field must be equal to or before {0}",
18050     /**
18051      * @cfg {String} invalidText
18052      * The error text to display when the date in the field is invalid (defaults to
18053      * '{value} is not a valid date - it must be in the format {format}').
18054      */
18055     invalidText : "{0} is not a valid date - it must be in the format {1}",
18056     /**
18057      * @cfg {String} triggerClass
18058      * An additional CSS class used to style the trigger button.  The trigger will always get the
18059      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
18060      * which displays a calendar icon).
18061      */
18062     triggerClass : 'x-form-date-trigger',
18063     
18064
18065     /**
18066      * @cfg {Boolean} useIso
18067      * if enabled, then the date field will use a hidden field to store the 
18068      * real value as iso formated date. default (true)
18069      */ 
18070     useIso : true,
18071     /**
18072      * @cfg {String/Object} autoCreate
18073      * A DomHelper element spec, or true for a default element spec (defaults to
18074      * {tag: "input", type: "text", size: "10", autocomplete: "off"})
18075      */ 
18076     // private
18077     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "new-password"},
18078     
18079     // private
18080     hiddenField: false,
18081     
18082     hideMonthPicker : false,
18083     
18084     onRender : function(ct, position)
18085     {
18086         Roo.form.MonthField.superclass.onRender.call(this, ct, position);
18087         if (this.useIso) {
18088             this.el.dom.removeAttribute('name'); 
18089             this.hiddenField = this.el.insertSibling({ tag:'input', type:'hidden', name: this.name },
18090                     'before', true);
18091             this.hiddenField.value = this.value ? this.formatDate(this.value, 'Y-m-d') : '';
18092             // prevent input submission
18093             this.hiddenName = this.name;
18094         }
18095             
18096             
18097     },
18098     
18099     // private
18100     validateValue : function(value)
18101     {
18102         value = this.formatDate(value);
18103         if(!Roo.form.MonthField.superclass.validateValue.call(this, value)){
18104             return false;
18105         }
18106         if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
18107              return true;
18108         }
18109         var svalue = value;
18110         value = this.parseDate(value);
18111         if(!value){
18112             this.markInvalid(String.format(this.invalidText, svalue, this.format));
18113             return false;
18114         }
18115         var time = value.getTime();
18116         if(this.minValue && time < this.minValue.getTime()){
18117             this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
18118             return false;
18119         }
18120         if(this.maxValue && time > this.maxValue.getTime()){
18121             this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
18122             return false;
18123         }
18124         /*if(this.disabledDays){
18125             var day = value.getDay();
18126             for(var i = 0; i < this.disabledDays.length; i++) {
18127                 if(day === this.disabledDays[i]){
18128                     this.markInvalid(this.disabledDaysText);
18129                     return false;
18130                 }
18131             }
18132         }
18133         */
18134         var fvalue = this.formatDate(value);
18135         /*if(this.ddMatch && this.ddMatch.test(fvalue)){
18136             this.markInvalid(String.format(this.disabledDatesText, fvalue));
18137             return false;
18138         }
18139         */
18140         return true;
18141     },
18142
18143     // private
18144     // Provides logic to override the default TriggerField.validateBlur which just returns true
18145     validateBlur : function(){
18146         return !this.menu || !this.menu.isVisible();
18147     },
18148
18149     /**
18150      * Returns the current date value of the date field.
18151      * @return {Date} The date value
18152      */
18153     getValue : function(){
18154         
18155         
18156         
18157         return  this.hiddenField ?
18158                 this.hiddenField.value :
18159                 this.parseDate(Roo.form.MonthField.superclass.getValue.call(this)) || "";
18160     },
18161
18162     /**
18163      * Sets the value of the date field.  You can pass a date object or any string that can be parsed into a valid
18164      * date, using MonthField.format as the date format, according to the same rules as {@link Date#parseDate}
18165      * (the default format used is "m/d/y").
18166      * <br />Usage:
18167      * <pre><code>
18168 //All of these calls set the same date value (May 4, 2006)
18169
18170 //Pass a date object:
18171 var dt = new Date('5/4/06');
18172 monthField.setValue(dt);
18173
18174 //Pass a date string (default format):
18175 monthField.setValue('5/4/06');
18176
18177 //Pass a date string (custom format):
18178 monthField.format = 'Y-m-d';
18179 monthField.setValue('2006-5-4');
18180 </code></pre>
18181      * @param {String/Date} date The date or valid date string
18182      */
18183     setValue : function(date){
18184         Roo.log('month setValue' + date);
18185         // can only be first of month..
18186         
18187         var val = this.parseDate(date);
18188         
18189         if (this.hiddenField) {
18190             this.hiddenField.value = this.formatDate(this.parseDate(date), 'Y-m-d');
18191         }
18192         Roo.form.MonthField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
18193         this.value = this.parseDate(date);
18194     },
18195
18196     // private
18197     parseDate : function(value){
18198         if(!value || value instanceof Date){
18199             value = value ? Date.parseDate(value.format('Y-m') + '-01', 'Y-m-d') : null;
18200             return value;
18201         }
18202         var v = Date.parseDate(value, this.format);
18203         if (!v && this.useIso) {
18204             v = Date.parseDate(value, 'Y-m-d');
18205         }
18206         if (v) {
18207             // 
18208             v = Date.parseDate(v.format('Y-m') +'-01', 'Y-m-d');
18209         }
18210         
18211         
18212         if(!v && this.altFormats){
18213             if(!this.altFormatsArray){
18214                 this.altFormatsArray = this.altFormats.split("|");
18215             }
18216             for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
18217                 v = Date.parseDate(value, this.altFormatsArray[i]);
18218             }
18219         }
18220         return v;
18221     },
18222
18223     // private
18224     formatDate : function(date, fmt){
18225         return (!date || !(date instanceof Date)) ?
18226                date : date.dateFormat(fmt || this.format);
18227     },
18228
18229     // private
18230     menuListeners : {
18231         select: function(m, d){
18232             this.setValue(d);
18233             this.fireEvent('select', this, d);
18234         },
18235         show : function(){ // retain focus styling
18236             this.onFocus();
18237         },
18238         hide : function(){
18239             this.focus.defer(10, this);
18240             var ml = this.menuListeners;
18241             this.menu.un("select", ml.select,  this);
18242             this.menu.un("show", ml.show,  this);
18243             this.menu.un("hide", ml.hide,  this);
18244         }
18245     },
18246     // private
18247     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
18248     onTriggerClick : function(){
18249         if(this.disabled){
18250             return;
18251         }
18252         if(this.menu == null){
18253             this.menu = new Roo.menu.DateMenu();
18254            
18255         }
18256         
18257         Roo.apply(this.menu.picker,  {
18258             
18259             showClear: this.allowBlank,
18260             minDate : this.minValue,
18261             maxDate : this.maxValue,
18262             disabledDatesRE : this.ddMatch,
18263             disabledDatesText : this.disabledDatesText,
18264             
18265             format : this.useIso ? 'Y-m-d' : this.format,
18266             minText : String.format(this.minText, this.formatDate(this.minValue)),
18267             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
18268             
18269         });
18270          this.menu.on(Roo.apply({}, this.menuListeners, {
18271             scope:this
18272         }));
18273        
18274         
18275         var m = this.menu;
18276         var p = m.picker;
18277         
18278         // hide month picker get's called when we called by 'before hide';
18279         
18280         var ignorehide = true;
18281         p.hideMonthPicker  = function(disableAnim){
18282             if (ignorehide) {
18283                 return;
18284             }
18285              if(this.monthPicker){
18286                 Roo.log("hideMonthPicker called");
18287                 if(disableAnim === true){
18288                     this.monthPicker.hide();
18289                 }else{
18290                     this.monthPicker.slideOut('t', {duration:.2});
18291                     p.setValue(new Date(m.picker.mpSelYear, m.picker.mpSelMonth, 1));
18292                     p.fireEvent("select", this, this.value);
18293                     m.hide();
18294                 }
18295             }
18296         }
18297         
18298         Roo.log('picker set value');
18299         Roo.log(this.getValue());
18300         p.setValue(this.getValue() ? this.parseDate(this.getValue()) : new Date());
18301         m.show(this.el, 'tl-bl?');
18302         ignorehide  = false;
18303         // this will trigger hideMonthPicker..
18304         
18305         
18306         // hidden the day picker
18307         Roo.select('.x-date-picker table', true).first().dom.style.visibility = "hidden";
18308         
18309         
18310         
18311       
18312         
18313         p.showMonthPicker.defer(100, p);
18314     
18315         
18316        
18317     },
18318
18319     beforeBlur : function(){
18320         var v = this.parseDate(this.getRawValue());
18321         if(v){
18322             this.setValue(v);
18323         }
18324     }
18325
18326     /** @cfg {Boolean} grow @hide */
18327     /** @cfg {Number} growMin @hide */
18328     /** @cfg {Number} growMax @hide */
18329     /**
18330      * @hide
18331      * @method autoSize
18332      */
18333 });/*
18334  * Based on:
18335  * Ext JS Library 1.1.1
18336  * Copyright(c) 2006-2007, Ext JS, LLC.
18337  *
18338  * Originally Released Under LGPL - original licence link has changed is not relivant.
18339  *
18340  * Fork - LGPL
18341  * <script type="text/javascript">
18342  */
18343  
18344
18345 /**
18346  * @class Roo.form.ComboBox
18347  * @extends Roo.form.TriggerField
18348  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
18349  * @constructor
18350  * Create a new ComboBox.
18351  * @param {Object} config Configuration options
18352  */
18353 Roo.form.ComboBox = function(config){
18354     Roo.form.ComboBox.superclass.constructor.call(this, config);
18355     this.addEvents({
18356         /**
18357          * @event expand
18358          * Fires when the dropdown list is expanded
18359              * @param {Roo.form.ComboBox} combo This combo box
18360              */
18361         'expand' : true,
18362         /**
18363          * @event collapse
18364          * Fires when the dropdown list is collapsed
18365              * @param {Roo.form.ComboBox} combo This combo box
18366              */
18367         'collapse' : true,
18368         /**
18369          * @event beforeselect
18370          * Fires before a list item is selected. Return false to cancel the selection.
18371              * @param {Roo.form.ComboBox} combo This combo box
18372              * @param {Roo.data.Record} record The data record returned from the underlying store
18373              * @param {Number} index The index of the selected item in the dropdown list
18374              */
18375         'beforeselect' : true,
18376         /**
18377          * @event select
18378          * Fires when a list item is selected
18379              * @param {Roo.form.ComboBox} combo This combo box
18380              * @param {Roo.data.Record} record The data record returned from the underlying store (or false on clear)
18381              * @param {Number} index The index of the selected item in the dropdown list
18382              */
18383         'select' : true,
18384         /**
18385          * @event beforequery
18386          * Fires before all queries are processed. Return false to cancel the query or set cancel to true.
18387          * The event object passed has these properties:
18388              * @param {Roo.form.ComboBox} combo This combo box
18389              * @param {String} query The query
18390              * @param {Boolean} forceAll true to force "all" query
18391              * @param {Boolean} cancel true to cancel the query
18392              * @param {Object} e The query event object
18393              */
18394         'beforequery': true,
18395          /**
18396          * @event add
18397          * Fires when the 'add' icon is pressed (add a listener to enable add button)
18398              * @param {Roo.form.ComboBox} combo This combo box
18399              */
18400         'add' : true,
18401         /**
18402          * @event edit
18403          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
18404              * @param {Roo.form.ComboBox} combo This combo box
18405              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
18406              */
18407         'edit' : true
18408         
18409         
18410     });
18411     if(this.transform){
18412         this.allowDomMove = false;
18413         var s = Roo.getDom(this.transform);
18414         if(!this.hiddenName){
18415             this.hiddenName = s.name;
18416         }
18417         if(!this.store){
18418             this.mode = 'local';
18419             var d = [], opts = s.options;
18420             for(var i = 0, len = opts.length;i < len; i++){
18421                 var o = opts[i];
18422                 var value = (Roo.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
18423                 if(o.selected) {
18424                     this.value = value;
18425                 }
18426                 d.push([value, o.text]);
18427             }
18428             this.store = new Roo.data.SimpleStore({
18429                 'id': 0,
18430                 fields: ['value', 'text'],
18431                 data : d
18432             });
18433             this.valueField = 'value';
18434             this.displayField = 'text';
18435         }
18436         s.name = Roo.id(); // wipe out the name in case somewhere else they have a reference
18437         if(!this.lazyRender){
18438             this.target = true;
18439             this.el = Roo.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
18440             s.parentNode.removeChild(s); // remove it
18441             this.render(this.el.parentNode);
18442         }else{
18443             s.parentNode.removeChild(s); // remove it
18444         }
18445
18446     }
18447     if (this.store) {
18448         this.store = Roo.factory(this.store, Roo.data);
18449     }
18450     
18451     this.selectedIndex = -1;
18452     if(this.mode == 'local'){
18453         if(config.queryDelay === undefined){
18454             this.queryDelay = 10;
18455         }
18456         if(config.minChars === undefined){
18457             this.minChars = 0;
18458         }
18459     }
18460 };
18461
18462 Roo.extend(Roo.form.ComboBox, Roo.form.TriggerField, {
18463     /**
18464      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
18465      */
18466     /**
18467      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
18468      * rendering into an Roo.Editor, defaults to false)
18469      */
18470     /**
18471      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
18472      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
18473      */
18474     /**
18475      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
18476      */
18477     /**
18478      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
18479      * the dropdown list (defaults to undefined, with no header element)
18480      */
18481
18482      /**
18483      * @cfg {String/Roo.Template} tpl The template to use to render the output
18484      */
18485      
18486     // private
18487     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
18488     /**
18489      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
18490      */
18491     listWidth: undefined,
18492     /**
18493      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
18494      * mode = 'remote' or 'text' if mode = 'local')
18495      */
18496     displayField: undefined,
18497     /**
18498      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
18499      * mode = 'remote' or 'value' if mode = 'local'). 
18500      * Note: use of a valueField requires the user make a selection
18501      * in order for a value to be mapped.
18502      */
18503     valueField: undefined,
18504     
18505     
18506     /**
18507      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
18508      * field's data value (defaults to the underlying DOM element's name)
18509      */
18510     hiddenName: undefined,
18511     /**
18512      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
18513      */
18514     listClass: '',
18515     /**
18516      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
18517      */
18518     selectedClass: 'x-combo-selected',
18519     /**
18520      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
18521      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
18522      * which displays a downward arrow icon).
18523      */
18524     triggerClass : 'x-form-arrow-trigger',
18525     /**
18526      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
18527      */
18528     shadow:'sides',
18529     /**
18530      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
18531      * anchor positions (defaults to 'tl-bl')
18532      */
18533     listAlign: 'tl-bl?',
18534     /**
18535      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
18536      */
18537     maxHeight: 300,
18538     /**
18539      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
18540      * query specified by the allQuery config option (defaults to 'query')
18541      */
18542     triggerAction: 'query',
18543     /**
18544      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
18545      * (defaults to 4, does not apply if editable = false)
18546      */
18547     minChars : 4,
18548     /**
18549      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
18550      * delay (typeAheadDelay) if it matches a known value (defaults to false)
18551      */
18552     typeAhead: false,
18553     /**
18554      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
18555      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
18556      */
18557     queryDelay: 500,
18558     /**
18559      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
18560      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
18561      */
18562     pageSize: 0,
18563     /**
18564      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
18565      * when editable = true (defaults to false)
18566      */
18567     selectOnFocus:false,
18568     /**
18569      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
18570      */
18571     queryParam: 'query',
18572     /**
18573      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
18574      * when mode = 'remote' (defaults to 'Loading...')
18575      */
18576     loadingText: 'Loading...',
18577     /**
18578      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
18579      */
18580     resizable: false,
18581     /**
18582      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
18583      */
18584     handleHeight : 8,
18585     /**
18586      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
18587      * traditional select (defaults to true)
18588      */
18589     editable: true,
18590     /**
18591      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
18592      */
18593     allQuery: '',
18594     /**
18595      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
18596      */
18597     mode: 'remote',
18598     /**
18599      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
18600      * listWidth has a higher value)
18601      */
18602     minListWidth : 70,
18603     /**
18604      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
18605      * allow the user to set arbitrary text into the field (defaults to false)
18606      */
18607     forceSelection:false,
18608     /**
18609      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
18610      * if typeAhead = true (defaults to 250)
18611      */
18612     typeAheadDelay : 250,
18613     /**
18614      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
18615      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
18616      */
18617     valueNotFoundText : undefined,
18618     /**
18619      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
18620      */
18621     blockFocus : false,
18622     
18623     /**
18624      * @cfg {Boolean} disableClear Disable showing of clear button.
18625      */
18626     disableClear : false,
18627     /**
18628      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
18629      */
18630     alwaysQuery : false,
18631     
18632     //private
18633     addicon : false,
18634     editicon: false,
18635     
18636     // element that contains real text value.. (when hidden is used..)
18637      
18638     // private
18639     onRender : function(ct, position)
18640     {
18641         Roo.form.ComboBox.superclass.onRender.call(this, ct, position);
18642         
18643                 if(this.hiddenName){
18644             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
18645                     'before', true);
18646             this.hiddenField.value =
18647                 this.hiddenValue !== undefined ? this.hiddenValue :
18648                 this.value !== undefined ? this.value : '';
18649
18650             // prevent input submission
18651             this.el.dom.removeAttribute('name');
18652              
18653              
18654         }
18655         
18656         if(Roo.isGecko){
18657             this.el.dom.setAttribute('autocomplete', 'off');
18658         }
18659
18660         var cls = 'x-combo-list';
18661
18662         this.list = new Roo.Layer({
18663             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
18664         });
18665
18666         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
18667         this.list.setWidth(lw);
18668         this.list.swallowEvent('mousewheel');
18669         this.assetHeight = 0;
18670
18671         if(this.title){
18672             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
18673             this.assetHeight += this.header.getHeight();
18674         }
18675
18676         this.innerList = this.list.createChild({cls:cls+'-inner'});
18677         this.innerList.on('mouseover', this.onViewOver, this);
18678         this.innerList.on('mousemove', this.onViewMove, this);
18679         this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
18680         
18681         if(this.allowBlank && !this.pageSize && !this.disableClear){
18682             this.footer = this.list.createChild({cls:cls+'-ft'});
18683             this.pageTb = new Roo.Toolbar(this.footer);
18684            
18685         }
18686         if(this.pageSize){
18687             this.footer = this.list.createChild({cls:cls+'-ft'});
18688             this.pageTb = new Roo.PagingToolbar(this.footer, this.store,
18689                     {pageSize: this.pageSize});
18690             
18691         }
18692         
18693         if (this.pageTb && this.allowBlank && !this.disableClear) {
18694             var _this = this;
18695             this.pageTb.add(new Roo.Toolbar.Fill(), {
18696                 cls: 'x-btn-icon x-btn-clear',
18697                 text: '&#160;',
18698                 handler: function()
18699                 {
18700                     _this.collapse();
18701                     _this.clearValue();
18702                     _this.onSelect(false, -1);
18703                 }
18704             });
18705         }
18706         if (this.footer) {
18707             this.assetHeight += this.footer.getHeight();
18708         }
18709         
18710
18711         if(!this.tpl){
18712             this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>';
18713         }
18714
18715         this.view = new Roo.View(this.innerList, this.tpl, {
18716             singleSelect:true,
18717             store: this.store,
18718             selectedClass: this.selectedClass
18719         });
18720
18721         this.view.on('click', this.onViewClick, this);
18722
18723         this.store.on('beforeload', this.onBeforeLoad, this);
18724         this.store.on('load', this.onLoad, this);
18725         this.store.on('loadexception', this.onLoadException, this);
18726
18727         if(this.resizable){
18728             this.resizer = new Roo.Resizable(this.list,  {
18729                pinned:true, handles:'se'
18730             });
18731             this.resizer.on('resize', function(r, w, h){
18732                 this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
18733                 this.listWidth = w;
18734                 this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
18735                 this.restrictHeight();
18736             }, this);
18737             this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
18738         }
18739         if(!this.editable){
18740             this.editable = true;
18741             this.setEditable(false);
18742         }  
18743         
18744         
18745         if (typeof(this.events.add.listeners) != 'undefined') {
18746             
18747             this.addicon = this.wrap.createChild(
18748                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-add' });  
18749        
18750             this.addicon.on('click', function(e) {
18751                 this.fireEvent('add', this);
18752             }, this);
18753         }
18754         if (typeof(this.events.edit.listeners) != 'undefined') {
18755             
18756             this.editicon = this.wrap.createChild(
18757                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-combo-edit' });  
18758             if (this.addicon) {
18759                 this.editicon.setStyle('margin-left', '40px');
18760             }
18761             this.editicon.on('click', function(e) {
18762                 
18763                 // we fire even  if inothing is selected..
18764                 this.fireEvent('edit', this, this.lastData );
18765                 
18766             }, this);
18767         }
18768         
18769         
18770         
18771     },
18772
18773     // private
18774     initEvents : function(){
18775         Roo.form.ComboBox.superclass.initEvents.call(this);
18776
18777         this.keyNav = new Roo.KeyNav(this.el, {
18778             "up" : function(e){
18779                 this.inKeyMode = true;
18780                 this.selectPrev();
18781             },
18782
18783             "down" : function(e){
18784                 if(!this.isExpanded()){
18785                     this.onTriggerClick();
18786                 }else{
18787                     this.inKeyMode = true;
18788                     this.selectNext();
18789                 }
18790             },
18791
18792             "enter" : function(e){
18793                 this.onViewClick();
18794                 //return true;
18795             },
18796
18797             "esc" : function(e){
18798                 this.collapse();
18799             },
18800
18801             "tab" : function(e){
18802                 this.onViewClick(false);
18803                 this.fireEvent("specialkey", this, e);
18804                 return true;
18805             },
18806
18807             scope : this,
18808
18809             doRelay : function(foo, bar, hname){
18810                 if(hname == 'down' || this.scope.isExpanded()){
18811                    return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
18812                 }
18813                 return true;
18814             },
18815
18816             forceKeyDown: true
18817         });
18818         this.queryDelay = Math.max(this.queryDelay || 10,
18819                 this.mode == 'local' ? 10 : 250);
18820         this.dqTask = new Roo.util.DelayedTask(this.initQuery, this);
18821         if(this.typeAhead){
18822             this.taTask = new Roo.util.DelayedTask(this.onTypeAhead, this);
18823         }
18824         if(this.editable !== false){
18825             this.el.on("keyup", this.onKeyUp, this);
18826         }
18827         if(this.forceSelection){
18828             this.on('blur', this.doForce, this);
18829         }
18830     },
18831
18832     onDestroy : function(){
18833         if(this.view){
18834             this.view.setStore(null);
18835             this.view.el.removeAllListeners();
18836             this.view.el.remove();
18837             this.view.purgeListeners();
18838         }
18839         if(this.list){
18840             this.list.destroy();
18841         }
18842         if(this.store){
18843             this.store.un('beforeload', this.onBeforeLoad, this);
18844             this.store.un('load', this.onLoad, this);
18845             this.store.un('loadexception', this.onLoadException, this);
18846         }
18847         Roo.form.ComboBox.superclass.onDestroy.call(this);
18848     },
18849
18850     // private
18851     fireKey : function(e){
18852         if(e.isNavKeyPress() && !this.list.isVisible()){
18853             this.fireEvent("specialkey", this, e);
18854         }
18855     },
18856
18857     // private
18858     onResize: function(w, h){
18859         Roo.form.ComboBox.superclass.onResize.apply(this, arguments);
18860         
18861         if(typeof w != 'number'){
18862             // we do not handle it!?!?
18863             return;
18864         }
18865         var tw = this.trigger.getWidth();
18866         tw += this.addicon ? this.addicon.getWidth() : 0;
18867         tw += this.editicon ? this.editicon.getWidth() : 0;
18868         var x = w - tw;
18869         this.el.setWidth( this.adjustWidth('input', x));
18870             
18871         this.trigger.setStyle('left', x+'px');
18872         
18873         if(this.list && this.listWidth === undefined){
18874             var lw = Math.max(x + this.trigger.getWidth(), this.minListWidth);
18875             this.list.setWidth(lw);
18876             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
18877         }
18878         
18879     
18880         
18881     },
18882
18883     /**
18884      * Allow or prevent the user from directly editing the field text.  If false is passed,
18885      * the user will only be able to select from the items defined in the dropdown list.  This method
18886      * is the runtime equivalent of setting the 'editable' config option at config time.
18887      * @param {Boolean} value True to allow the user to directly edit the field text
18888      */
18889     setEditable : function(value){
18890         if(value == this.editable){
18891             return;
18892         }
18893         this.editable = value;
18894         if(!value){
18895             this.el.dom.setAttribute('readOnly', true);
18896             this.el.on('mousedown', this.onTriggerClick,  this);
18897             this.el.addClass('x-combo-noedit');
18898         }else{
18899             this.el.dom.setAttribute('readOnly', false);
18900             this.el.un('mousedown', this.onTriggerClick,  this);
18901             this.el.removeClass('x-combo-noedit');
18902         }
18903     },
18904
18905     // private
18906     onBeforeLoad : function(){
18907         if(!this.hasFocus){
18908             return;
18909         }
18910         this.innerList.update(this.loadingText ?
18911                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
18912         this.restrictHeight();
18913         this.selectedIndex = -1;
18914     },
18915
18916     // private
18917     onLoad : function(){
18918         if(!this.hasFocus){
18919             return;
18920         }
18921         if(this.store.getCount() > 0){
18922             this.expand();
18923             this.restrictHeight();
18924             if(this.lastQuery == this.allQuery){
18925                 if(this.editable){
18926                     this.el.dom.select();
18927                 }
18928                 if(!this.selectByValue(this.value, true)){
18929                     this.select(0, true);
18930                 }
18931             }else{
18932                 this.selectNext();
18933                 if(this.typeAhead && this.lastKey != Roo.EventObject.BACKSPACE && this.lastKey != Roo.EventObject.DELETE){
18934                     this.taTask.delay(this.typeAheadDelay);
18935                 }
18936             }
18937         }else{
18938             this.onEmptyResults();
18939         }
18940         //this.el.focus();
18941     },
18942     // private
18943     onLoadException : function()
18944     {
18945         this.collapse();
18946         Roo.log(this.store.reader.jsonData);
18947         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
18948             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
18949         }
18950         
18951         
18952     },
18953     // private
18954     onTypeAhead : function(){
18955         if(this.store.getCount() > 0){
18956             var r = this.store.getAt(0);
18957             var newValue = r.data[this.displayField];
18958             var len = newValue.length;
18959             var selStart = this.getRawValue().length;
18960             if(selStart != len){
18961                 this.setRawValue(newValue);
18962                 this.selectText(selStart, newValue.length);
18963             }
18964         }
18965     },
18966
18967     // private
18968     onSelect : function(record, index){
18969         if(this.fireEvent('beforeselect', this, record, index) !== false){
18970             this.setFromData(index > -1 ? record.data : false);
18971             this.collapse();
18972             this.fireEvent('select', this, record, index);
18973         }
18974     },
18975
18976     /**
18977      * Returns the currently selected field value or empty string if no value is set.
18978      * @return {String} value The selected value
18979      */
18980     getValue : function(){
18981         if(this.valueField){
18982             return typeof this.value != 'undefined' ? this.value : '';
18983         }
18984         return Roo.form.ComboBox.superclass.getValue.call(this);
18985     },
18986
18987     /**
18988      * Clears any text/value currently set in the field
18989      */
18990     clearValue : function(){
18991         if(this.hiddenField){
18992             this.hiddenField.value = '';
18993         }
18994         this.value = '';
18995         this.setRawValue('');
18996         this.lastSelectionText = '';
18997         
18998     },
18999
19000     /**
19001      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
19002      * will be displayed in the field.  If the value does not match the data value of an existing item,
19003      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
19004      * Otherwise the field will be blank (although the value will still be set).
19005      * @param {String} value The value to match
19006      */
19007     setValue : function(v){
19008         var text = v;
19009         if(this.valueField){
19010             var r = this.findRecord(this.valueField, v);
19011             if(r){
19012                 text = r.data[this.displayField];
19013             }else if(this.valueNotFoundText !== undefined){
19014                 text = this.valueNotFoundText;
19015             }
19016         }
19017         this.lastSelectionText = text;
19018         if(this.hiddenField){
19019             this.hiddenField.value = v;
19020         }
19021         Roo.form.ComboBox.superclass.setValue.call(this, text);
19022         this.value = v;
19023     },
19024     /**
19025      * @property {Object} the last set data for the element
19026      */
19027     
19028     lastData : false,
19029     /**
19030      * Sets the value of the field based on a object which is related to the record format for the store.
19031      * @param {Object} value the value to set as. or false on reset?
19032      */
19033     setFromData : function(o){
19034         var dv = ''; // display value
19035         var vv = ''; // value value..
19036         this.lastData = o;
19037         if (this.displayField) {
19038             dv = !o || typeof(o[this.displayField]) == 'undefined' ? '' : o[this.displayField];
19039         } else {
19040             // this is an error condition!!!
19041             Roo.log('no  displayField value set for '+ (this.name ? this.name : this.id));
19042         }
19043         
19044         if(this.valueField){
19045             vv = !o || typeof(o[this.valueField]) == 'undefined' ? dv : o[this.valueField];
19046         }
19047         if(this.hiddenField){
19048             this.hiddenField.value = vv;
19049             
19050             this.lastSelectionText = dv;
19051             Roo.form.ComboBox.superclass.setValue.call(this, dv);
19052             this.value = vv;
19053             return;
19054         }
19055         // no hidden field.. - we store the value in 'value', but still display
19056         // display field!!!!
19057         this.lastSelectionText = dv;
19058         Roo.form.ComboBox.superclass.setValue.call(this, dv);
19059         this.value = vv;
19060         
19061         
19062     },
19063     // private
19064     reset : function(){
19065         // overridden so that last data is reset..
19066         this.setValue(this.resetValue);
19067         this.originalValue = this.getValue();
19068         this.clearInvalid();
19069         this.lastData = false;
19070         if (this.view) {
19071             this.view.clearSelections();
19072         }
19073     },
19074     // private
19075     findRecord : function(prop, value){
19076         var record;
19077         if(this.store.getCount() > 0){
19078             this.store.each(function(r){
19079                 if(r.data[prop] == value){
19080                     record = r;
19081                     return false;
19082                 }
19083                 return true;
19084             });
19085         }
19086         return record;
19087     },
19088     
19089     getName: function()
19090     {
19091         // returns hidden if it's set..
19092         if (!this.rendered) {return ''};
19093         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
19094         
19095     },
19096     // private
19097     onViewMove : function(e, t){
19098         this.inKeyMode = false;
19099     },
19100
19101     // private
19102     onViewOver : function(e, t){
19103         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
19104             return;
19105         }
19106         var item = this.view.findItemFromChild(t);
19107         if(item){
19108             var index = this.view.indexOf(item);
19109             this.select(index, false);
19110         }
19111     },
19112
19113     // private
19114     onViewClick : function(doFocus)
19115     {
19116         var index = this.view.getSelectedIndexes()[0];
19117         var r = this.store.getAt(index);
19118         if(r){
19119             this.onSelect(r, index);
19120         }
19121         if(doFocus !== false && !this.blockFocus){
19122             this.el.focus();
19123         }
19124     },
19125
19126     // private
19127     restrictHeight : function(){
19128         this.innerList.dom.style.height = '';
19129         var inner = this.innerList.dom;
19130         var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
19131         this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
19132         this.list.beginUpdate();
19133         this.list.setHeight(this.innerList.getHeight()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight);
19134         this.list.alignTo(this.el, this.listAlign);
19135         this.list.endUpdate();
19136     },
19137
19138     // private
19139     onEmptyResults : function(){
19140         this.collapse();
19141     },
19142
19143     /**
19144      * Returns true if the dropdown list is expanded, else false.
19145      */
19146     isExpanded : function(){
19147         return this.list.isVisible();
19148     },
19149
19150     /**
19151      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
19152      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19153      * @param {String} value The data value of the item to select
19154      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19155      * selected item if it is not currently in view (defaults to true)
19156      * @return {Boolean} True if the value matched an item in the list, else false
19157      */
19158     selectByValue : function(v, scrollIntoView){
19159         if(v !== undefined && v !== null){
19160             var r = this.findRecord(this.valueField || this.displayField, v);
19161             if(r){
19162                 this.select(this.store.indexOf(r), scrollIntoView);
19163                 return true;
19164             }
19165         }
19166         return false;
19167     },
19168
19169     /**
19170      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
19171      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
19172      * @param {Number} index The zero-based index of the list item to select
19173      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
19174      * selected item if it is not currently in view (defaults to true)
19175      */
19176     select : function(index, scrollIntoView){
19177         this.selectedIndex = index;
19178         this.view.select(index);
19179         if(scrollIntoView !== false){
19180             var el = this.view.getNode(index);
19181             if(el){
19182                 this.innerList.scrollChildIntoView(el, false);
19183             }
19184         }
19185     },
19186
19187     // private
19188     selectNext : function(){
19189         var ct = this.store.getCount();
19190         if(ct > 0){
19191             if(this.selectedIndex == -1){
19192                 this.select(0);
19193             }else if(this.selectedIndex < ct-1){
19194                 this.select(this.selectedIndex+1);
19195             }
19196         }
19197     },
19198
19199     // private
19200     selectPrev : function(){
19201         var ct = this.store.getCount();
19202         if(ct > 0){
19203             if(this.selectedIndex == -1){
19204                 this.select(0);
19205             }else if(this.selectedIndex != 0){
19206                 this.select(this.selectedIndex-1);
19207             }
19208         }
19209     },
19210
19211     // private
19212     onKeyUp : function(e){
19213         if(this.editable !== false && !e.isSpecialKey()){
19214             this.lastKey = e.getKey();
19215             this.dqTask.delay(this.queryDelay);
19216         }
19217     },
19218
19219     // private
19220     validateBlur : function(){
19221         return !this.list || !this.list.isVisible();   
19222     },
19223
19224     // private
19225     initQuery : function(){
19226         this.doQuery(this.getRawValue());
19227     },
19228
19229     // private
19230     doForce : function(){
19231         if(this.el.dom.value.length > 0){
19232             this.el.dom.value =
19233                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
19234              
19235         }
19236     },
19237
19238     /**
19239      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
19240      * query allowing the query action to be canceled if needed.
19241      * @param {String} query The SQL query to execute
19242      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
19243      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
19244      * saved in the current store (defaults to false)
19245      */
19246     doQuery : function(q, forceAll){
19247         if(q === undefined || q === null){
19248             q = '';
19249         }
19250         var qe = {
19251             query: q,
19252             forceAll: forceAll,
19253             combo: this,
19254             cancel:false
19255         };
19256         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
19257             return false;
19258         }
19259         q = qe.query;
19260         forceAll = qe.forceAll;
19261         if(forceAll === true || (q.length >= this.minChars)){
19262             if(this.lastQuery != q || this.alwaysQuery){
19263                 this.lastQuery = q;
19264                 if(this.mode == 'local'){
19265                     this.selectedIndex = -1;
19266                     if(forceAll){
19267                         this.store.clearFilter();
19268                     }else{
19269                         this.store.filter(this.displayField, q);
19270                     }
19271                     this.onLoad();
19272                 }else{
19273                     this.store.baseParams[this.queryParam] = q;
19274                     this.store.load({
19275                         params: this.getParams(q)
19276                     });
19277                     this.expand();
19278                 }
19279             }else{
19280                 this.selectedIndex = -1;
19281                 this.onLoad();   
19282             }
19283         }
19284     },
19285
19286     // private
19287     getParams : function(q){
19288         var p = {};
19289         //p[this.queryParam] = q;
19290         if(this.pageSize){
19291             p.start = 0;
19292             p.limit = this.pageSize;
19293         }
19294         return p;
19295     },
19296
19297     /**
19298      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
19299      */
19300     collapse : function(){
19301         if(!this.isExpanded()){
19302             return;
19303         }
19304         this.list.hide();
19305         Roo.get(document).un('mousedown', this.collapseIf, this);
19306         Roo.get(document).un('mousewheel', this.collapseIf, this);
19307         if (!this.editable) {
19308             Roo.get(document).un('keydown', this.listKeyPress, this);
19309         }
19310         this.fireEvent('collapse', this);
19311     },
19312
19313     // private
19314     collapseIf : function(e){
19315         if(!e.within(this.wrap) && !e.within(this.list)){
19316             this.collapse();
19317         }
19318     },
19319
19320     /**
19321      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
19322      */
19323     expand : function(){
19324         if(this.isExpanded() || !this.hasFocus){
19325             return;
19326         }
19327         this.list.alignTo(this.el, this.listAlign);
19328         this.list.show();
19329         Roo.get(document).on('mousedown', this.collapseIf, this);
19330         Roo.get(document).on('mousewheel', this.collapseIf, this);
19331         if (!this.editable) {
19332             Roo.get(document).on('keydown', this.listKeyPress, this);
19333         }
19334         
19335         this.fireEvent('expand', this);
19336     },
19337
19338     // private
19339     // Implements the default empty TriggerField.onTriggerClick function
19340     onTriggerClick : function(){
19341         if(this.disabled){
19342             return;
19343         }
19344         if(this.isExpanded()){
19345             this.collapse();
19346             if (!this.blockFocus) {
19347                 this.el.focus();
19348             }
19349             
19350         }else {
19351             this.hasFocus = true;
19352             if(this.triggerAction == 'all') {
19353                 this.doQuery(this.allQuery, true);
19354             } else {
19355                 this.doQuery(this.getRawValue());
19356             }
19357             if (!this.blockFocus) {
19358                 this.el.focus();
19359             }
19360         }
19361     },
19362     listKeyPress : function(e)
19363     {
19364         //Roo.log('listkeypress');
19365         // scroll to first matching element based on key pres..
19366         if (e.isSpecialKey()) {
19367             return false;
19368         }
19369         var k = String.fromCharCode(e.getKey()).toUpperCase();
19370         //Roo.log(k);
19371         var match  = false;
19372         var csel = this.view.getSelectedNodes();
19373         var cselitem = false;
19374         if (csel.length) {
19375             var ix = this.view.indexOf(csel[0]);
19376             cselitem  = this.store.getAt(ix);
19377             if (!cselitem.get(this.displayField) || cselitem.get(this.displayField).substring(0,1).toUpperCase() != k) {
19378                 cselitem = false;
19379             }
19380             
19381         }
19382         
19383         this.store.each(function(v) { 
19384             if (cselitem) {
19385                 // start at existing selection.
19386                 if (cselitem.id == v.id) {
19387                     cselitem = false;
19388                 }
19389                 return;
19390             }
19391                 
19392             if (v.get(this.displayField) && v.get(this.displayField).substring(0,1).toUpperCase() == k) {
19393                 match = this.store.indexOf(v);
19394                 return false;
19395             }
19396         }, this);
19397         
19398         if (match === false) {
19399             return true; // no more action?
19400         }
19401         // scroll to?
19402         this.view.select(match);
19403         var sn = Roo.get(this.view.getSelectedNodes()[0]);
19404         sn.scrollIntoView(sn.dom.parentNode, false);
19405     },
19406         cleanLeadingSpace : function()
19407         {
19408                 // override textfield strip white space (trigers set on blur)
19409         }
19410
19411     /** 
19412     * @cfg {Boolean} grow 
19413     * @hide 
19414     */
19415     /** 
19416     * @cfg {Number} growMin 
19417     * @hide 
19418     */
19419     /** 
19420     * @cfg {Number} growMax 
19421     * @hide 
19422     */
19423     /**
19424      * @hide
19425      * @method autoSize
19426      */
19427 });/*
19428  * Copyright(c) 2010-2012, Roo J Solutions Limited
19429  *
19430  * Licence LGPL
19431  *
19432  */
19433
19434 /**
19435  * @class Roo.form.ComboBoxArray
19436  * @extends Roo.form.TextField
19437  * A facebook style adder... for lists of email / people / countries  etc...
19438  * pick multiple items from a combo box, and shows each one.
19439  *
19440  *  Fred [x]  Brian [x]  [Pick another |v]
19441  *
19442  *
19443  *  For this to work: it needs various extra information
19444  *    - normal combo problay has
19445  *      name, hiddenName
19446  *    + displayField, valueField
19447  *
19448  *    For our purpose...
19449  *
19450  *
19451  *   If we change from 'extends' to wrapping...
19452  *   
19453  *  
19454  *
19455  
19456  
19457  * @constructor
19458  * Create a new ComboBoxArray.
19459  * @param {Object} config Configuration options
19460  */
19461  
19462
19463 Roo.form.ComboBoxArray = function(config)
19464 {
19465     this.addEvents({
19466         /**
19467          * @event beforeremove
19468          * Fires before remove the value from the list
19469              * @param {Roo.form.ComboBoxArray} _self This combo box array
19470              * @param {Roo.form.ComboBoxArray.Item} item removed item
19471              */
19472         'beforeremove' : true,
19473         /**
19474          * @event remove
19475          * Fires when remove the value from the list
19476              * @param {Roo.form.ComboBoxArray} _self This combo box array
19477              * @param {Roo.form.ComboBoxArray.Item} item removed item
19478              */
19479         'remove' : true
19480         
19481         
19482     });
19483     
19484     Roo.form.ComboBoxArray.superclass.constructor.call(this, config);
19485     
19486     this.items = new Roo.util.MixedCollection(false);
19487     
19488     // construct the child combo...
19489     
19490     
19491     
19492     
19493    
19494     
19495 }
19496
19497  
19498 Roo.extend(Roo.form.ComboBoxArray, Roo.form.TextField,
19499
19500     /**
19501      * @cfg {Roo.form.ComboBox} combo [required] The combo box that is wrapped
19502      */
19503     
19504     lastData : false,
19505     
19506     // behavies liek a hiddne field
19507     inputType:      'hidden',
19508     /**
19509      * @cfg {Number} width The width of the box that displays the selected element
19510      */ 
19511     width:          300,
19512
19513     
19514     
19515     /**
19516      * @cfg {String} name    The name of the visable items on this form (eg. titles not ids)
19517      */
19518     name : false,
19519     /**
19520      * @cfg {String} hiddenName    The hidden name of the field, often contains an comma seperated list of names
19521      */
19522     hiddenName : false,
19523       /**
19524      * @cfg {String} seperator    The value seperator normally ',' 
19525      */
19526     seperator : ',',
19527     
19528     
19529         // private the array of items that are displayed..
19530     items  : false,
19531     // private - the hidden field el.
19532     hiddenEl : false,
19533     // private - the filed el..
19534     el : false,
19535     
19536     //validateValue : function() { return true; }, // all values are ok!
19537     //onAddClick: function() { },
19538     
19539     onRender : function(ct, position) 
19540     {
19541         
19542         // create the standard hidden element
19543         //Roo.form.ComboBoxArray.superclass.onRender.call(this, ct, position);
19544         
19545         
19546         // give fake names to child combo;
19547         this.combo.hiddenName = this.hiddenName ? (this.hiddenName+'-subcombo') : this.hiddenName;
19548         this.combo.name = this.name ? (this.name+'-subcombo') : this.name;
19549         
19550         this.combo = Roo.factory(this.combo, Roo.form);
19551         this.combo.onRender(ct, position);
19552         if (typeof(this.combo.width) != 'undefined') {
19553             this.combo.onResize(this.combo.width,0);
19554         }
19555         
19556         this.combo.initEvents();
19557         
19558         // assigned so form know we need to do this..
19559         this.store          = this.combo.store;
19560         this.valueField     = this.combo.valueField;
19561         this.displayField   = this.combo.displayField ;
19562         
19563         
19564         this.combo.wrap.addClass('x-cbarray-grp');
19565         
19566         var cbwrap = this.combo.wrap.createChild(
19567             {tag: 'div', cls: 'x-cbarray-cb'},
19568             this.combo.el.dom
19569         );
19570         
19571              
19572         this.hiddenEl = this.combo.wrap.createChild({
19573             tag: 'input',  type:'hidden' , name: this.hiddenName, value : ''
19574         });
19575         this.el = this.combo.wrap.createChild({
19576             tag: 'input',  type:'hidden' , name: this.name, value : ''
19577         });
19578          //   this.el.dom.removeAttribute("name");
19579         
19580         
19581         this.outerWrap = this.combo.wrap;
19582         this.wrap = cbwrap;
19583         
19584         this.outerWrap.setWidth(this.width);
19585         this.outerWrap.dom.removeChild(this.el.dom);
19586         
19587         this.wrap.dom.appendChild(this.el.dom);
19588         this.outerWrap.dom.removeChild(this.combo.trigger.dom);
19589         this.combo.wrap.dom.appendChild(this.combo.trigger.dom);
19590         
19591         this.combo.trigger.setStyle('position','relative');
19592         this.combo.trigger.setStyle('left', '0px');
19593         this.combo.trigger.setStyle('top', '2px');
19594         
19595         this.combo.el.setStyle('vertical-align', 'text-bottom');
19596         
19597         //this.trigger.setStyle('vertical-align', 'top');
19598         
19599         // this should use the code from combo really... on('add' ....)
19600         if (this.adder) {
19601             
19602         
19603             this.adder = this.outerWrap.createChild(
19604                 {tag: 'img', src: Roo.BLANK_IMAGE_URL, cls: 'x-form-adder', style: 'margin-left:2px'});  
19605             var _t = this;
19606             this.adder.on('click', function(e) {
19607                 _t.fireEvent('adderclick', this, e);
19608             }, _t);
19609         }
19610         //var _t = this;
19611         //this.adder.on('click', this.onAddClick, _t);
19612         
19613         
19614         this.combo.on('select', function(cb, rec, ix) {
19615             this.addItem(rec.data);
19616             
19617             cb.setValue('');
19618             cb.el.dom.value = '';
19619             //cb.lastData = rec.data;
19620             // add to list
19621             
19622         }, this);
19623          
19624         
19625         
19626             
19627     },
19628     
19629     
19630     getName: function()
19631     {
19632         // returns hidden if it's set..
19633         if (!this.rendered) {return ''};
19634         return  this.hiddenName ? this.hiddenName : this.name;
19635         
19636     },
19637     
19638     
19639     onResize: function(w, h){
19640         
19641         return;
19642         // not sure if this is needed..
19643         //this.combo.onResize(w,h);
19644         
19645         if(typeof w != 'number'){
19646             // we do not handle it!?!?
19647             return;
19648         }
19649         var tw = this.combo.trigger.getWidth();
19650         tw += this.addicon ? this.addicon.getWidth() : 0;
19651         tw += this.editicon ? this.editicon.getWidth() : 0;
19652         var x = w - tw;
19653         this.combo.el.setWidth( this.combo.adjustWidth('input', x));
19654             
19655         this.combo.trigger.setStyle('left', '0px');
19656         
19657         if(this.list && this.listWidth === undefined){
19658             var lw = Math.max(x + this.combo.trigger.getWidth(), this.combo.minListWidth);
19659             this.list.setWidth(lw);
19660             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
19661         }
19662         
19663     
19664         
19665     },
19666     
19667     addItem: function(rec)
19668     {
19669         var valueField = this.combo.valueField;
19670         var displayField = this.combo.displayField;
19671         
19672         if (this.items.indexOfKey(rec[valueField]) > -1) {
19673             //console.log("GOT " + rec.data.id);
19674             return;
19675         }
19676         
19677         var x = new Roo.form.ComboBoxArray.Item({
19678             //id : rec[this.idField],
19679             data : rec,
19680             displayField : displayField ,
19681             tipField : displayField ,
19682             cb : this
19683         });
19684         // use the 
19685         this.items.add(rec[valueField],x);
19686         // add it before the element..
19687         this.updateHiddenEl();
19688         x.render(this.outerWrap, this.wrap.dom);
19689         // add the image handler..
19690     },
19691     
19692     updateHiddenEl : function()
19693     {
19694         this.validate();
19695         if (!this.hiddenEl) {
19696             return;
19697         }
19698         var ar = [];
19699         var idField = this.combo.valueField;
19700         
19701         this.items.each(function(f) {
19702             ar.push(f.data[idField]);
19703         });
19704         this.hiddenEl.dom.value = ar.join(this.seperator);
19705         this.validate();
19706     },
19707     
19708     reset : function()
19709     {
19710         this.items.clear();
19711         
19712         Roo.each(this.outerWrap.select('.x-cbarray-item', true).elements, function(el){
19713            el.remove();
19714         });
19715         
19716         this.el.dom.value = '';
19717         if (this.hiddenEl) {
19718             this.hiddenEl.dom.value = '';
19719         }
19720         
19721     },
19722     getValue: function()
19723     {
19724         return this.hiddenEl ? this.hiddenEl.dom.value : '';
19725     },
19726     setValue: function(v) // not a valid action - must use addItems..
19727     {
19728         
19729         this.reset();
19730          
19731         if (this.store.isLocal && (typeof(v) == 'string')) {
19732             // then we can use the store to find the values..
19733             // comma seperated at present.. this needs to allow JSON based encoding..
19734             this.hiddenEl.value  = v;
19735             var v_ar = [];
19736             Roo.each(v.split(this.seperator), function(k) {
19737                 Roo.log("CHECK " + this.valueField + ',' + k);
19738                 var li = this.store.query(this.valueField, k);
19739                 if (!li.length) {
19740                     return;
19741                 }
19742                 var add = {};
19743                 add[this.valueField] = k;
19744                 add[this.displayField] = li.item(0).data[this.displayField];
19745                 
19746                 this.addItem(add);
19747             }, this) 
19748              
19749         }
19750         if (typeof(v) == 'object' ) {
19751             // then let's assume it's an array of objects..
19752             Roo.each(v, function(l) {
19753                 var add = l;
19754                 if (typeof(l) == 'string') {
19755                     add = {};
19756                     add[this.valueField] = l;
19757                     add[this.displayField] = l
19758                 }
19759                 this.addItem(add);
19760             }, this);
19761              
19762         }
19763         
19764         
19765     },
19766     setFromData: function(v)
19767     {
19768         // this recieves an object, if setValues is called.
19769         this.reset();
19770         this.el.dom.value = v[this.displayField];
19771         this.hiddenEl.dom.value = v[this.valueField];
19772         if (typeof(v[this.valueField]) != 'string' || !v[this.valueField].length) {
19773             return;
19774         }
19775         var kv = v[this.valueField];
19776         var dv = v[this.displayField];
19777         kv = typeof(kv) != 'string' ? '' : kv;
19778         dv = typeof(dv) != 'string' ? '' : dv;
19779         
19780         
19781         var keys = kv.split(this.seperator);
19782         var display = dv.split(this.seperator);
19783         for (var i = 0 ; i < keys.length; i++) {
19784             add = {};
19785             add[this.valueField] = keys[i];
19786             add[this.displayField] = display[i];
19787             this.addItem(add);
19788         }
19789       
19790         
19791     },
19792     
19793     /**
19794      * Validates the combox array value
19795      * @return {Boolean} True if the value is valid, else false
19796      */
19797     validate : function(){
19798         if(this.disabled || this.validateValue(this.processValue(this.getValue()))){
19799             this.clearInvalid();
19800             return true;
19801         }
19802         return false;
19803     },
19804     
19805     validateValue : function(value){
19806         return Roo.form.ComboBoxArray.superclass.validateValue.call(this, this.getValue());
19807         
19808     },
19809     
19810     /*@
19811      * overide
19812      * 
19813      */
19814     isDirty : function() {
19815         if(this.disabled) {
19816             return false;
19817         }
19818         
19819         try {
19820             var d = Roo.decode(String(this.originalValue));
19821         } catch (e) {
19822             return String(this.getValue()) !== String(this.originalValue);
19823         }
19824         
19825         var originalValue = [];
19826         
19827         for (var i = 0; i < d.length; i++){
19828             originalValue.push(d[i][this.valueField]);
19829         }
19830         
19831         return String(this.getValue()) !== String(originalValue.join(this.seperator));
19832         
19833     }
19834     
19835 });
19836
19837
19838
19839 /**
19840  * @class Roo.form.ComboBoxArray.Item
19841  * @extends Roo.BoxComponent
19842  * A selected item in the list
19843  *  Fred [x]  Brian [x]  [Pick another |v]
19844  * 
19845  * @constructor
19846  * Create a new item.
19847  * @param {Object} config Configuration options
19848  */
19849  
19850 Roo.form.ComboBoxArray.Item = function(config) {
19851     config.id = Roo.id();
19852     Roo.form.ComboBoxArray.Item.superclass.constructor.call(this, config);
19853 }
19854
19855 Roo.extend(Roo.form.ComboBoxArray.Item, Roo.BoxComponent, {
19856     data : {},
19857     cb: false,
19858     displayField : false,
19859     tipField : false,
19860      
19861     
19862     defaultAutoCreate : {
19863         tag: 'div',
19864         cls: 'x-cbarray-item',
19865         cn : [ 
19866             { tag: 'div' },
19867             {
19868                 tag: 'img',
19869                 width:16,
19870                 height : 16,
19871                 src : Roo.BLANK_IMAGE_URL ,
19872                 align: 'center'
19873             }
19874         ]
19875         
19876     },
19877     
19878  
19879     onRender : function(ct, position)
19880     {
19881         Roo.form.Field.superclass.onRender.call(this, ct, position);
19882         
19883         if(!this.el){
19884             var cfg = this.getAutoCreate();
19885             this.el = ct.createChild(cfg, position);
19886         }
19887         
19888         this.el.child('img').dom.setAttribute('src', Roo.BLANK_IMAGE_URL);
19889         
19890         this.el.child('div').dom.innerHTML = this.cb.renderer ? 
19891             this.cb.renderer(this.data) :
19892             String.format('{0}',this.data[this.displayField]);
19893         
19894             
19895         this.el.child('div').dom.setAttribute('qtip',
19896                         String.format('{0}',this.data[this.tipField])
19897         );
19898         
19899         this.el.child('img').on('click', this.remove, this);
19900         
19901     },
19902    
19903     remove : function()
19904     {
19905         if(this.cb.disabled){
19906             return;
19907         }
19908         
19909         if(false !== this.cb.fireEvent('beforeremove', this.cb, this)){
19910             this.cb.items.remove(this);
19911             this.el.child('img').un('click', this.remove, this);
19912             this.el.remove();
19913             this.cb.updateHiddenEl();
19914
19915             this.cb.fireEvent('remove', this.cb, this);
19916         }
19917         
19918     }
19919 });/*
19920  * RooJS Library 1.1.1
19921  * Copyright(c) 2008-2011  Alan Knowles
19922  *
19923  * License - LGPL
19924  */
19925  
19926
19927 /**
19928  * @class Roo.form.ComboNested
19929  * @extends Roo.form.ComboBox
19930  * A combobox for that allows selection of nested items in a list,
19931  * eg.
19932  *
19933  *  Book
19934  *    -> red
19935  *    -> green
19936  *  Table
19937  *    -> square
19938  *      ->red
19939  *      ->green
19940  *    -> rectangle
19941  *      ->green
19942  *      
19943  * 
19944  * @constructor
19945  * Create a new ComboNested
19946  * @param {Object} config Configuration options
19947  */
19948 Roo.form.ComboNested = function(config){
19949     Roo.form.ComboCheck.superclass.constructor.call(this, config);
19950     // should verify some data...
19951     // like
19952     // hiddenName = required..
19953     // displayField = required
19954     // valudField == required
19955     var req= [ 'hiddenName', 'displayField', 'valueField' ];
19956     var _t = this;
19957     Roo.each(req, function(e) {
19958         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
19959             throw "Roo.form.ComboNested : missing value for: " + e;
19960         }
19961     });
19962      
19963     
19964 };
19965
19966 Roo.extend(Roo.form.ComboNested, Roo.form.ComboBox, {
19967    
19968     /*
19969      * @config {Number} max Number of columns to show
19970      */
19971     
19972     maxColumns : 3,
19973    
19974     list : null, // the outermost div..
19975     innerLists : null, // the
19976     views : null,
19977     stores : null,
19978     // private
19979     loadingChildren : false,
19980     
19981     onRender : function(ct, position)
19982     {
19983         Roo.form.ComboBox.superclass.onRender.call(this, ct, position); // skip parent call - got to above..
19984         
19985         if(this.hiddenName){
19986             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id:  (this.hiddenId||this.hiddenName)},
19987                     'before', true);
19988             this.hiddenField.value =
19989                 this.hiddenValue !== undefined ? this.hiddenValue :
19990                 this.value !== undefined ? this.value : '';
19991
19992             // prevent input submission
19993             this.el.dom.removeAttribute('name');
19994              
19995              
19996         }
19997         
19998         if(Roo.isGecko){
19999             this.el.dom.setAttribute('autocomplete', 'off');
20000         }
20001
20002         var cls = 'x-combo-list';
20003
20004         this.list = new Roo.Layer({
20005             shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
20006         });
20007
20008         var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
20009         this.list.setWidth(lw);
20010         this.list.swallowEvent('mousewheel');
20011         this.assetHeight = 0;
20012
20013         if(this.title){
20014             this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
20015             this.assetHeight += this.header.getHeight();
20016         }
20017         this.innerLists = [];
20018         this.views = [];
20019         this.stores = [];
20020         for (var i =0 ; i < this.maxColumns; i++) {
20021             this.onRenderList( cls, i);
20022         }
20023         
20024         // always needs footer, as we are going to have an 'OK' button.
20025         this.footer = this.list.createChild({cls:cls+'-ft'});
20026         this.pageTb = new Roo.Toolbar(this.footer);  
20027         var _this = this;
20028         this.pageTb.add(  {
20029             
20030             text: 'Done',
20031             handler: function()
20032             {
20033                 _this.collapse();
20034             }
20035         });
20036         
20037         if ( this.allowBlank && !this.disableClear) {
20038             
20039             this.pageTb.add(new Roo.Toolbar.Fill(), {
20040                 cls: 'x-btn-icon x-btn-clear',
20041                 text: '&#160;',
20042                 handler: function()
20043                 {
20044                     _this.collapse();
20045                     _this.clearValue();
20046                     _this.onSelect(false, -1);
20047                 }
20048             });
20049         }
20050         if (this.footer) {
20051             this.assetHeight += this.footer.getHeight();
20052         }
20053         
20054     },
20055     onRenderList : function (  cls, i)
20056     {
20057         
20058         var lw = Math.floor(
20059                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
20060         );
20061         
20062         this.list.setWidth(lw); // default to '1'
20063
20064         var il = this.innerLists[i] = this.list.createChild({cls:cls+'-inner'});
20065         //il.on('mouseover', this.onViewOver, this, { list:  i });
20066         //il.on('mousemove', this.onViewMove, this, { list:  i });
20067         il.setWidth(lw);
20068         il.setStyle({ 'overflow-x' : 'hidden'});
20069
20070         if(!this.tpl){
20071             this.tpl = new Roo.Template({
20072                 html :  '<div class="'+cls+'-item '+cls+'-item-{cn:this.isEmpty}">{' + this.displayField + '}</div>',
20073                 isEmpty: function (value, allValues) {
20074                     //Roo.log(value);
20075                     var dl = typeof(value.data) != 'undefined' ? value.data.length : value.length; ///json is a nested response..
20076                     return dl ? 'has-children' : 'no-children'
20077                 }
20078             });
20079         }
20080         
20081         var store  = this.store;
20082         if (i > 0) {
20083             store  = new Roo.data.SimpleStore({
20084                 //fields : this.store.reader.meta.fields,
20085                 reader : this.store.reader,
20086                 data : [ ]
20087             });
20088         }
20089         this.stores[i]  = store;
20090                   
20091         var view = this.views[i] = new Roo.View(
20092             il,
20093             this.tpl,
20094             {
20095                 singleSelect:true,
20096                 store: store,
20097                 selectedClass: this.selectedClass
20098             }
20099         );
20100         view.getEl().setWidth(lw);
20101         view.getEl().setStyle({
20102             position: i < 1 ? 'relative' : 'absolute',
20103             top: 0,
20104             left: (i * lw ) + 'px',
20105             display : i > 0 ? 'none' : 'block'
20106         });
20107         view.on('selectionchange', this.onSelectChange.createDelegate(this, {list : i }, true));
20108         view.on('dblclick', this.onDoubleClick.createDelegate(this, {list : i }, true));
20109         //view.on('click', this.onViewClick, this, { list : i });
20110
20111         store.on('beforeload', this.onBeforeLoad, this);
20112         store.on('load',  this.onLoad, this, { list  : i});
20113         store.on('loadexception', this.onLoadException, this);
20114
20115         // hide the other vies..
20116         
20117         
20118         
20119     },
20120       
20121     restrictHeight : function()
20122     {
20123         var mh = 0;
20124         Roo.each(this.innerLists, function(il,i) {
20125             var el = this.views[i].getEl();
20126             el.dom.style.height = '';
20127             var inner = el.dom;
20128             var h = Math.max(il.clientHeight, il.offsetHeight, il.scrollHeight);
20129             // only adjust heights on other ones..
20130             mh = Math.max(h, mh);
20131             if (i < 1) {
20132                 
20133                 el.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
20134                 il.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight);
20135                
20136             }
20137             
20138             
20139         }, this);
20140         
20141         this.list.beginUpdate();
20142         this.list.setHeight(mh+this.list.getFrameWidth('tb')+this.assetHeight);
20143         this.list.alignTo(this.el, this.listAlign);
20144         this.list.endUpdate();
20145         
20146     },
20147      
20148     
20149     // -- store handlers..
20150     // private
20151     onBeforeLoad : function()
20152     {
20153         if(!this.hasFocus){
20154             return;
20155         }
20156         this.innerLists[0].update(this.loadingText ?
20157                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
20158         this.restrictHeight();
20159         this.selectedIndex = -1;
20160     },
20161     // private
20162     onLoad : function(a,b,c,d)
20163     {
20164         if (!this.loadingChildren) {
20165             // then we are loading the top level. - hide the children
20166             for (var i = 1;i < this.views.length; i++) {
20167                 this.views[i].getEl().setStyle({ display : 'none' });
20168             }
20169             var lw = Math.floor(
20170                 ((this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')) / this.maxColumns
20171             );
20172         
20173              this.list.setWidth(lw); // default to '1'
20174
20175             
20176         }
20177         if(!this.hasFocus){
20178             return;
20179         }
20180         
20181         if(this.store.getCount() > 0) {
20182             this.expand();
20183             this.restrictHeight();   
20184         } else {
20185             this.onEmptyResults();
20186         }
20187         
20188         if (!this.loadingChildren) {
20189             this.selectActive();
20190         }
20191         /*
20192         this.stores[1].loadData([]);
20193         this.stores[2].loadData([]);
20194         this.views
20195         */    
20196     
20197         //this.el.focus();
20198     },
20199     
20200     
20201     // private
20202     onLoadException : function()
20203     {
20204         this.collapse();
20205         Roo.log(this.store.reader.jsonData);
20206         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
20207             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
20208         }
20209         
20210         
20211     },
20212     // no cleaning of leading spaces on blur here.
20213     cleanLeadingSpace : function(e) { },
20214     
20215
20216     onSelectChange : function (view, sels, opts )
20217     {
20218         var ix = view.getSelectedIndexes();
20219          
20220         if (opts.list > this.maxColumns - 2) {
20221             if (view.store.getCount()<  1) {
20222                 this.views[opts.list ].getEl().setStyle({ display :   'none' });
20223
20224             } else  {
20225                 if (ix.length) {
20226                     // used to clear ?? but if we are loading unselected 
20227                     this.setFromData(view.store.getAt(ix[0]).data);
20228                 }
20229                 
20230             }
20231             
20232             return;
20233         }
20234         
20235         if (!ix.length) {
20236             // this get's fired when trigger opens..
20237            // this.setFromData({});
20238             var str = this.stores[opts.list+1];
20239             str.data.clear(); // removeall wihtout the fire events..
20240             return;
20241         }
20242         
20243         var rec = view.store.getAt(ix[0]);
20244          
20245         this.setFromData(rec.data);
20246         this.fireEvent('select', this, rec, ix[0]);
20247         
20248         var lw = Math.floor(
20249              (
20250                 (this.listWidth * this.maxColumns || Math.max(this.wrap.getWidth(), this.minListWidth)) - this.list.getFrameWidth('lr')
20251              ) / this.maxColumns
20252         );
20253         this.loadingChildren = true;
20254         this.stores[opts.list+1].loadDataFromChildren( rec );
20255         this.loadingChildren = false;
20256         var dl = this.stores[opts.list+1]. getTotalCount();
20257         
20258         this.views[opts.list+1].getEl().setHeight( this.innerLists[0].getHeight());
20259         
20260         this.views[opts.list+1].getEl().setStyle({ display : dl ? 'block' : 'none' });
20261         for (var i = opts.list+2; i < this.views.length;i++) {
20262             this.views[i].getEl().setStyle({ display : 'none' });
20263         }
20264         
20265         this.innerLists[opts.list+1].setHeight( this.innerLists[0].getHeight());
20266         this.list.setWidth(lw * (opts.list + (dl ? 2 : 1)));
20267         
20268         if (this.isLoading) {
20269            // this.selectActive(opts.list);
20270         }
20271          
20272     },
20273     
20274     
20275     
20276     
20277     onDoubleClick : function()
20278     {
20279         this.collapse(); //??
20280     },
20281     
20282      
20283     
20284     
20285     
20286     // private
20287     recordToStack : function(store, prop, value, stack)
20288     {
20289         var cstore = new Roo.data.SimpleStore({
20290             //fields : this.store.reader.meta.fields, // we need array reader.. for
20291             reader : this.store.reader,
20292             data : [ ]
20293         });
20294         var _this = this;
20295         var record  = false;
20296         var srec = false;
20297         if(store.getCount() < 1){
20298             return false;
20299         }
20300         store.each(function(r){
20301             if(r.data[prop] == value){
20302                 record = r;
20303             srec = r;
20304                 return false;
20305             }
20306             if (r.data.cn && r.data.cn.length) {
20307                 cstore.loadDataFromChildren( r);
20308                 var cret = _this.recordToStack(cstore, prop, value, stack);
20309                 if (cret !== false) {
20310                     record = cret;
20311                     srec = r;
20312                     return false;
20313                 }
20314             }
20315              
20316             return true;
20317         });
20318         if (record == false) {
20319             return false
20320         }
20321         stack.unshift(srec);
20322         return record;
20323     },
20324     
20325     /*
20326      * find the stack of stores that match our value.
20327      *
20328      * 
20329      */
20330     
20331     selectActive : function ()
20332     {
20333         // if store is not loaded, then we will need to wait for that to happen first.
20334         var stack = [];
20335         this.recordToStack(this.store, this.valueField, this.getValue(), stack);
20336         for (var i = 0; i < stack.length; i++ ) {
20337             this.views[i].select(stack[i].store.indexOf(stack[i]), false, false );
20338         }
20339         
20340     }
20341         
20342          
20343     
20344     
20345     
20346     
20347 });/*
20348  * Based on:
20349  * Ext JS Library 1.1.1
20350  * Copyright(c) 2006-2007, Ext JS, LLC.
20351  *
20352  * Originally Released Under LGPL - original licence link has changed is not relivant.
20353  *
20354  * Fork - LGPL
20355  * <script type="text/javascript">
20356  */
20357 /**
20358  * @class Roo.form.Checkbox
20359  * @extends Roo.form.Field
20360  * Single checkbox field.  Can be used as a direct replacement for traditional checkbox fields.
20361  * @constructor
20362  * Creates a new Checkbox
20363  * @param {Object} config Configuration options
20364  */
20365 Roo.form.Checkbox = function(config){
20366     Roo.form.Checkbox.superclass.constructor.call(this, config);
20367     this.addEvents({
20368         /**
20369          * @event check
20370          * Fires when the checkbox is checked or unchecked.
20371              * @param {Roo.form.Checkbox} this This checkbox
20372              * @param {Boolean} checked The new checked value
20373              */
20374         check : true
20375     });
20376 };
20377
20378 Roo.extend(Roo.form.Checkbox, Roo.form.Field,  {
20379     /**
20380      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
20381      */
20382     focusClass : undefined,
20383     /**
20384      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
20385      */
20386     fieldClass: "x-form-field",
20387     /**
20388      * @cfg {Boolean} checked True if the the checkbox should render already checked (defaults to false)
20389      */
20390     checked: false,
20391     /**
20392      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
20393      * {tag: "input", type: "checkbox", autocomplete: "off"})
20394      */
20395     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "off"},
20396     /**
20397      * @cfg {String} boxLabel The text that appears beside the checkbox
20398      */
20399     boxLabel : "",
20400     /**
20401      * @cfg {String} inputValue The value that should go into the generated input element's value attribute
20402      */  
20403     inputValue : '1',
20404     /**
20405      * @cfg {String} valueOff The value that should go into the generated input element's value when unchecked.
20406      */
20407      valueOff: '0', // value when not checked..
20408
20409     actionMode : 'viewEl', 
20410     //
20411     // private
20412     itemCls : 'x-menu-check-item x-form-item',
20413     groupClass : 'x-menu-group-item',
20414     inputType : 'hidden',
20415     
20416     
20417     inSetChecked: false, // check that we are not calling self...
20418     
20419     inputElement: false, // real input element?
20420     basedOn: false, // ????
20421     
20422     isFormField: true, // not sure where this is needed!!!!
20423
20424     onResize : function(){
20425         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
20426         if(!this.boxLabel){
20427             this.el.alignTo(this.wrap, 'c-c');
20428         }
20429     },
20430
20431     initEvents : function(){
20432         Roo.form.Checkbox.superclass.initEvents.call(this);
20433         this.el.on("click", this.onClick,  this);
20434         this.el.on("change", this.onClick,  this);
20435     },
20436
20437
20438     getResizeEl : function(){
20439         return this.wrap;
20440     },
20441
20442     getPositionEl : function(){
20443         return this.wrap;
20444     },
20445
20446     // private
20447     onRender : function(ct, position){
20448         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20449         /*
20450         if(this.inputValue !== undefined){
20451             this.el.dom.value = this.inputValue;
20452         }
20453         */
20454         //this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20455         this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20456         var viewEl = this.wrap.createChild({ 
20457             tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20458         this.viewEl = viewEl;   
20459         this.wrap.on('click', this.onClick,  this); 
20460         
20461         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20462         this.el.on('propertychange', this.setFromHidden,  this);  //ie
20463         
20464         
20465         
20466         if(this.boxLabel){
20467             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20468         //    viewEl.on('click', this.onClick,  this); 
20469         }
20470         //if(this.checked){
20471             this.setChecked(this.checked);
20472         //}else{
20473             //this.checked = this.el.dom;
20474         //}
20475
20476     },
20477
20478     // private
20479     initValue : Roo.emptyFn,
20480
20481     /**
20482      * Returns the checked state of the checkbox.
20483      * @return {Boolean} True if checked, else false
20484      */
20485     getValue : function(){
20486         if(this.el){
20487             return String(this.el.dom.value) == String(this.inputValue ) ? this.inputValue : this.valueOff;
20488         }
20489         return this.valueOff;
20490         
20491     },
20492
20493         // private
20494     onClick : function(){ 
20495         if (this.disabled) {
20496             return;
20497         }
20498         this.setChecked(!this.checked);
20499
20500         //if(this.el.dom.checked != this.checked){
20501         //    this.setValue(this.el.dom.checked);
20502        // }
20503     },
20504
20505     /**
20506      * Sets the checked state of the checkbox.
20507      * On is always based on a string comparison between inputValue and the param.
20508      * @param {Boolean/String} value - the value to set 
20509      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
20510      */
20511     setValue : function(v,suppressEvent){
20512         
20513         
20514         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
20515         //if(this.el && this.el.dom){
20516         //    this.el.dom.checked = this.checked;
20517         //    this.el.dom.defaultChecked = this.checked;
20518         //}
20519         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
20520         //this.fireEvent("check", this, this.checked);
20521     },
20522     // private..
20523     setChecked : function(state,suppressEvent)
20524     {
20525         if (this.inSetChecked) {
20526             this.checked = state;
20527             return;
20528         }
20529         
20530     
20531         if(this.wrap){
20532             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
20533         }
20534         this.checked = state;
20535         if(suppressEvent !== true){
20536             this.fireEvent('check', this, state);
20537         }
20538         this.inSetChecked = true;
20539                  
20540                 this.el.dom.value = state ? this.inputValue : this.valueOff;
20541                  
20542         this.inSetChecked = false;
20543         
20544     },
20545     // handle setting of hidden value by some other method!!?!?
20546     setFromHidden: function()
20547     {
20548         if(!this.el){
20549             return;
20550         }
20551         //console.log("SET FROM HIDDEN");
20552         //alert('setFrom hidden');
20553         this.setValue(this.el.dom.value);
20554     },
20555     
20556     onDestroy : function()
20557     {
20558         if(this.viewEl){
20559             Roo.get(this.viewEl).remove();
20560         }
20561          
20562         Roo.form.Checkbox.superclass.onDestroy.call(this);
20563     },
20564     
20565     setBoxLabel : function(str)
20566     {
20567         this.wrap.select('.x-form-cb-label', true).first().dom.innerHTML = str;
20568     }
20569
20570 });/*
20571  * Based on:
20572  * Ext JS Library 1.1.1
20573  * Copyright(c) 2006-2007, Ext JS, LLC.
20574  *
20575  * Originally Released Under LGPL - original licence link has changed is not relivant.
20576  *
20577  * Fork - LGPL
20578  * <script type="text/javascript">
20579  */
20580  
20581 /**
20582  * @class Roo.form.Radio
20583  * @extends Roo.form.Checkbox
20584  * Single radio field.  Same as Checkbox, but provided as a convenience for automatically setting the input type.
20585  * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
20586  * @constructor
20587  * Creates a new Radio
20588  * @param {Object} config Configuration options
20589  */
20590 Roo.form.Radio = function(){
20591     Roo.form.Radio.superclass.constructor.apply(this, arguments);
20592 };
20593 Roo.extend(Roo.form.Radio, Roo.form.Checkbox, {
20594     inputType: 'radio',
20595
20596     /**
20597      * If this radio is part of a group, it will return the selected value
20598      * @return {String}
20599      */
20600     getGroupValue : function(){
20601         return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value;
20602     },
20603     
20604     
20605     onRender : function(ct, position){
20606         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
20607         
20608         if(this.inputValue !== undefined){
20609             this.el.dom.value = this.inputValue;
20610         }
20611          
20612         this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
20613         //this.wrap = this.el.wrap({cls: 'x-menu-check-item '});
20614         //var viewEl = this.wrap.createChild({ 
20615         //    tag: 'img', cls: 'x-menu-item-icon', style: 'margin: 0px;' ,src : Roo.BLANK_IMAGE_URL });
20616         //this.viewEl = viewEl;   
20617         //this.wrap.on('click', this.onClick,  this); 
20618         
20619         //this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
20620         //this.el.on('propertychange', this.setFromHidden,  this);  //ie
20621         
20622         
20623         
20624         if(this.boxLabel){
20625             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
20626         //    viewEl.on('click', this.onClick,  this); 
20627         }
20628          if(this.checked){
20629             this.el.dom.checked =   'checked' ;
20630         }
20631          
20632     },
20633     /**
20634      * Sets the checked state of the checkbox.
20635      * On is always based on a string comparison between inputValue and the param.
20636      * @param {Boolean/String} value - the value to set 
20637      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
20638      */
20639     setValue : function(v,suppressEvent){
20640         
20641         
20642         //this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
20643         //if(this.el && this.el.dom){
20644         //    this.el.dom.checked = this.checked;
20645         //    this.el.dom.defaultChecked = this.checked;
20646         //}
20647         this.setChecked(String(v) === String(this.inputValue), suppressEvent);
20648         
20649         this.el.dom.form[this.name].value = v;
20650      
20651         //this.fireEvent("check", this, this.checked);
20652     },
20653     // private..
20654     setChecked : function(state,suppressEvent)
20655     {
20656          
20657         if(this.wrap){
20658             this.wrap[state ? 'addClass' : 'removeClass']('x-menu-item-checked');
20659         }
20660         this.checked = state;
20661         if(suppressEvent !== true){
20662             this.fireEvent('check', this, state);
20663         }
20664                  
20665                   
20666        
20667         
20668     },
20669     reset : function(){
20670         // this.setValue(this.resetValue);
20671         //this.originalValue = this.getValue();
20672         this.clearInvalid();
20673     } 
20674     
20675 });Roo.rtf = {}; // namespace
20676 Roo.rtf.Hex = function(hex)
20677 {
20678     this.hexstr = hex;
20679 };
20680 Roo.rtf.Paragraph = function(opts)
20681 {
20682     this.content = []; ///??? is that used?
20683 };Roo.rtf.Span = function(opts)
20684 {
20685     this.value = opts.value;
20686 };
20687
20688 Roo.rtf.Group = function(parent)
20689 {
20690     // we dont want to acutally store parent - it will make debug a nightmare..
20691     this.content = [];
20692     this.cn  = [];
20693      
20694        
20695     
20696 };
20697
20698 Roo.rtf.Group.prototype = {
20699     ignorable : false,
20700     content: false,
20701     cn: false,
20702     addContent : function(node) {
20703         // could set styles...
20704         this.content.push(node);
20705     },
20706     addChild : function(cn)
20707     {
20708         this.cn.push(cn);
20709     },
20710     // only for images really...
20711     toDataURL : function()
20712     {
20713         var mimetype = false;
20714         switch(true) {
20715             case this.content.filter(function(a) { return a.value == 'pngblip' } ).length > 0: 
20716                 mimetype = "image/png";
20717                 break;
20718              case this.content.filter(function(a) { return a.value == 'jpegblip' } ).length > 0:
20719                 mimetype = "image/jpeg";
20720                 break;
20721             default :
20722                 return 'about:blank'; // ?? error?
20723         }
20724         
20725         
20726         var hexstring = this.content[this.content.length-1].value;
20727         
20728         return 'data:' + mimetype + ';base64,' + btoa(hexstring.match(/\w{2}/g).map(function(a) {
20729             return String.fromCharCode(parseInt(a, 16));
20730         }).join(""));
20731     }
20732     
20733 };
20734 // this looks like it's normally the {rtf{ .... }}
20735 Roo.rtf.Document = function()
20736 {
20737     // we dont want to acutally store parent - it will make debug a nightmare..
20738     this.rtlch  = [];
20739     this.content = [];
20740     this.cn = [];
20741     
20742 };
20743 Roo.extend(Roo.rtf.Document, Roo.rtf.Group, { 
20744     addChild : function(cn)
20745     {
20746         this.cn.push(cn);
20747         switch(cn.type) {
20748             case 'rtlch': // most content seems to be inside this??
20749             case 'listtext':
20750             case 'shpinst':
20751                 this.rtlch.push(cn);
20752                 return;
20753             default:
20754                 this[cn.type] = cn;
20755         }
20756         
20757     },
20758     
20759     getElementsByType : function(type)
20760     {
20761         var ret =  [];
20762         this._getElementsByType(type, ret, this.cn, 'rtf');
20763         return ret;
20764     },
20765     _getElementsByType : function (type, ret, search_array, path)
20766     {
20767         search_array.forEach(function(n,i) {
20768             if (n.type == type) {
20769                 n.path = path + '/' + n.type + ':' + i;
20770                 ret.push(n);
20771             }
20772             if (n.cn.length > 0) {
20773                 this._getElementsByType(type, ret, n.cn, path + '/' + n.type+':'+i);
20774             }
20775         },this);
20776     }
20777     
20778 });
20779  
20780 Roo.rtf.Ctrl = function(opts)
20781 {
20782     this.value = opts.value;
20783     this.param = opts.param;
20784 };
20785 /**
20786  *
20787  *
20788  * based on this https://github.com/iarna/rtf-parser
20789  * it's really only designed to extract pict from pasted RTF 
20790  *
20791  * usage:
20792  *
20793  *  var images = new Roo.rtf.Parser().parse(a_string).filter(function(g) { return g.type == 'pict'; });
20794  *  
20795  *
20796  */
20797
20798  
20799
20800
20801
20802 Roo.rtf.Parser = function(text) {
20803     //super({objectMode: true})
20804     this.text = '';
20805     this.parserState = this.parseText;
20806     
20807     // these are for interpeter...
20808     this.doc = {};
20809     ///this.parserState = this.parseTop
20810     this.groupStack = [];
20811     this.hexStore = [];
20812     this.doc = false;
20813     
20814     this.groups = []; // where we put the return.
20815     
20816     for (var ii = 0; ii < text.length; ++ii) {
20817         ++this.cpos;
20818         
20819         if (text[ii] === '\n') {
20820             ++this.row;
20821             this.col = 1;
20822         } else {
20823             ++this.col;
20824         }
20825         this.parserState(text[ii]);
20826     }
20827     
20828     
20829     
20830 };
20831 Roo.rtf.Parser.prototype = {
20832     text : '', // string being parsed..
20833     controlWord : '',
20834     controlWordParam :  '',
20835     hexChar : '',
20836     doc : false,
20837     group: false,
20838     groupStack : false,
20839     hexStore : false,
20840     
20841     
20842     cpos : 0, 
20843     row : 1, // reportin?
20844     col : 1, //
20845
20846      
20847     push : function (el)
20848     {
20849         var m = 'cmd'+ el.type;
20850         if (typeof(this[m]) == 'undefined') {
20851             Roo.log('invalid cmd:' + el.type);
20852             return;
20853         }
20854         this[m](el);
20855         //Roo.log(el);
20856     },
20857     flushHexStore : function()
20858     {
20859         if (this.hexStore.length < 1) {
20860             return;
20861         }
20862         var hexstr = this.hexStore.map(
20863             function(cmd) {
20864                 return cmd.value;
20865         }).join('');
20866         
20867         this.group.addContent( new Roo.rtf.Hex( hexstr ));
20868               
20869             
20870         this.hexStore.splice(0)
20871         
20872     },
20873     
20874     cmdgroupstart : function()
20875     {
20876         this.flushHexStore();
20877         if (this.group) {
20878             this.groupStack.push(this.group);
20879         }
20880          // parent..
20881         if (this.doc === false) {
20882             this.group = this.doc = new Roo.rtf.Document();
20883             return;
20884             
20885         }
20886         this.group = new Roo.rtf.Group(this.group);
20887     },
20888     cmdignorable : function()
20889     {
20890         this.flushHexStore();
20891         this.group.ignorable = true;
20892     },
20893     cmdendparagraph : function()
20894     {
20895         this.flushHexStore();
20896         this.group.addContent(new Roo.rtf.Paragraph());
20897     },
20898     cmdgroupend : function ()
20899     {
20900         this.flushHexStore();
20901         var endingGroup = this.group;
20902         
20903         
20904         this.group = this.groupStack.pop();
20905         if (this.group) {
20906             this.group.addChild(endingGroup);
20907         }
20908         
20909         
20910         
20911         var doc = this.group || this.doc;
20912         //if (endingGroup instanceof FontTable) {
20913         //  doc.fonts = endingGroup.table
20914         //} else if (endingGroup instanceof ColorTable) {
20915         //  doc.colors = endingGroup.table
20916         //} else if (endingGroup !== this.doc && !endingGroup.get('ignorable')) {
20917         if (endingGroup.ignorable === false) {
20918             //code
20919             this.groups.push(endingGroup);
20920            // Roo.log( endingGroup );
20921         }
20922             //Roo.each(endingGroup.content, function(item)) {
20923             //    doc.addContent(item);
20924             //}
20925             //process.emit('debug', 'GROUP END', endingGroup.type, endingGroup.get('ignorable'))
20926         //}
20927     },
20928     cmdtext : function (cmd)
20929     {
20930         this.flushHexStore();
20931         if (!this.group) { // an RTF fragment, missing the {\rtf1 header
20932             //this.group = this.doc
20933             return;  // we really don't care about stray text...
20934         }
20935         this.group.addContent(new Roo.rtf.Span(cmd));
20936     },
20937     cmdcontrolword : function (cmd)
20938     {
20939         this.flushHexStore();
20940         if (!this.group.type) {
20941             this.group.type = cmd.value;
20942             return;
20943         }
20944         this.group.addContent(new Roo.rtf.Ctrl(cmd));
20945         // we actually don't care about ctrl words...
20946         return ;
20947         /*
20948         var method = 'ctrl$' + cmd.value.replace(/-(.)/g, (_, char) => char.toUpperCase())
20949         if (this[method]) {
20950             this[method](cmd.param)
20951         } else {
20952             if (!this.group.get('ignorable')) process.emit('debug', method, cmd.param)
20953         }
20954         */
20955     },
20956     cmdhexchar : function(cmd) {
20957         this.hexStore.push(cmd);
20958     },
20959     cmderror : function(cmd) {
20960         throw cmd.value;
20961     },
20962     
20963     /*
20964       _flush (done) {
20965         if (this.text !== '\u0000') this.emitText()
20966         done()
20967       }
20968       */
20969       
20970       
20971     parseText : function(c)
20972     {
20973         if (c === '\\') {
20974             this.parserState = this.parseEscapes;
20975         } else if (c === '{') {
20976             this.emitStartGroup();
20977         } else if (c === '}') {
20978             this.emitEndGroup();
20979         } else if (c === '\x0A' || c === '\x0D') {
20980             // cr/lf are noise chars
20981         } else {
20982             this.text += c;
20983         }
20984     },
20985     
20986     parseEscapes: function (c)
20987     {
20988         if (c === '\\' || c === '{' || c === '}') {
20989             this.text += c;
20990             this.parserState = this.parseText;
20991         } else {
20992             this.parserState = this.parseControlSymbol;
20993             this.parseControlSymbol(c);
20994         }
20995     },
20996     parseControlSymbol: function(c)
20997     {
20998         if (c === '~') {
20999             this.text += '\u00a0'; // nbsp
21000             this.parserState = this.parseText
21001         } else if (c === '-') {
21002              this.text += '\u00ad'; // soft hyphen
21003         } else if (c === '_') {
21004             this.text += '\u2011'; // non-breaking hyphen
21005         } else if (c === '*') {
21006             this.emitIgnorable();
21007             this.parserState = this.parseText;
21008         } else if (c === "'") {
21009             this.parserState = this.parseHexChar;
21010         } else if (c === '|') { // formula cacter
21011             this.emitFormula();
21012             this.parserState = this.parseText;
21013         } else if (c === ':') { // subentry in an index entry
21014             this.emitIndexSubEntry();
21015             this.parserState = this.parseText;
21016         } else if (c === '\x0a') {
21017             this.emitEndParagraph();
21018             this.parserState = this.parseText;
21019         } else if (c === '\x0d') {
21020             this.emitEndParagraph();
21021             this.parserState = this.parseText;
21022         } else {
21023             this.parserState = this.parseControlWord;
21024             this.parseControlWord(c);
21025         }
21026     },
21027     parseHexChar: function (c)
21028     {
21029         if (/^[A-Fa-f0-9]$/.test(c)) {
21030             this.hexChar += c;
21031             if (this.hexChar.length >= 2) {
21032               this.emitHexChar();
21033               this.parserState = this.parseText;
21034             }
21035             return;
21036         }
21037         this.emitError("Invalid character \"" + c + "\" in hex literal.");
21038         this.parserState = this.parseText;
21039         
21040     },
21041     parseControlWord : function(c)
21042     {
21043         if (c === ' ') {
21044             this.emitControlWord();
21045             this.parserState = this.parseText;
21046         } else if (/^[-\d]$/.test(c)) {
21047             this.parserState = this.parseControlWordParam;
21048             this.controlWordParam += c;
21049         } else if (/^[A-Za-z]$/.test(c)) {
21050           this.controlWord += c;
21051         } else {
21052           this.emitControlWord();
21053           this.parserState = this.parseText;
21054           this.parseText(c);
21055         }
21056     },
21057     parseControlWordParam : function (c) {
21058         if (/^\d$/.test(c)) {
21059           this.controlWordParam += c;
21060         } else if (c === ' ') {
21061           this.emitControlWord();
21062           this.parserState = this.parseText;
21063         } else {
21064           this.emitControlWord();
21065           this.parserState = this.parseText;
21066           this.parseText(c);
21067         }
21068     },
21069     
21070     
21071     
21072     
21073     emitText : function () {
21074         if (this.text === '') {
21075             return;
21076         }
21077         this.push({
21078             type: 'text',
21079             value: this.text,
21080             pos: this.cpos,
21081             row: this.row,
21082             col: this.col
21083         });
21084         this.text = ''
21085     },
21086     emitControlWord : function ()
21087     {
21088         this.emitText();
21089         if (this.controlWord === '') {
21090             // do we want to track this - it seems just to cause problems.
21091             //this.emitError('empty control word');
21092         } else {
21093             this.push({
21094                   type: 'controlword',
21095                   value: this.controlWord,
21096                   param: this.controlWordParam !== '' && Number(this.controlWordParam),
21097                   pos: this.cpos,
21098                   row: this.row,
21099                   col: this.col
21100             });
21101         }
21102         this.controlWord = '';
21103         this.controlWordParam = '';
21104     },
21105     emitStartGroup : function ()
21106     {
21107         this.emitText();
21108         this.push({
21109             type: 'groupstart',
21110             pos: this.cpos,
21111             row: this.row,
21112             col: this.col
21113         });
21114     },
21115     emitEndGroup : function ()
21116     {
21117         this.emitText();
21118         this.push({
21119             type: 'groupend',
21120             pos: this.cpos,
21121             row: this.row,
21122             col: this.col
21123         });
21124     },
21125     emitIgnorable : function ()
21126     {
21127         this.emitText();
21128         this.push({
21129             type: 'ignorable',
21130             pos: this.cpos,
21131             row: this.row,
21132             col: this.col
21133         });
21134     },
21135     emitHexChar : function ()
21136     {
21137         this.emitText();
21138         this.push({
21139             type: 'hexchar',
21140             value: this.hexChar,
21141             pos: this.cpos,
21142             row: this.row,
21143             col: this.col
21144         });
21145         this.hexChar = ''
21146     },
21147     emitError : function (message)
21148     {
21149       this.emitText();
21150       this.push({
21151             type: 'error',
21152             value: message,
21153             row: this.row,
21154             col: this.col,
21155             char: this.cpos //,
21156             //stack: new Error().stack
21157         });
21158     },
21159     emitEndParagraph : function () {
21160         this.emitText();
21161         this.push({
21162             type: 'endparagraph',
21163             pos: this.cpos,
21164             row: this.row,
21165             col: this.col
21166         });
21167     }
21168      
21169 } ;
21170 Roo.htmleditor = {};
21171  
21172 /**
21173  * @class Roo.htmleditor.Filter
21174  * Base Class for filtering htmleditor stuff. - do not use this directly - extend it.
21175  * @cfg {DomElement} node The node to iterate and filter
21176  * @cfg {boolean|String|Array} tag Tags to replace 
21177  * @constructor
21178  * Create a new Filter.
21179  * @param {Object} config Configuration options
21180  */
21181
21182
21183
21184 Roo.htmleditor.Filter = function(cfg) {
21185     Roo.apply(this.cfg);
21186     // this does not actually call walk as it's really just a abstract class
21187 }
21188
21189
21190 Roo.htmleditor.Filter.prototype = {
21191     
21192     node: false,
21193     
21194     tag: false,
21195
21196     // overrride to do replace comments.
21197     replaceComment : false,
21198     
21199     // overrride to do replace or do stuff with tags..
21200     replaceTag : false,
21201     
21202     walk : function(dom)
21203     {
21204         Roo.each( Array.from(dom.childNodes), function( e ) {
21205             switch(true) {
21206                 
21207                 case e.nodeType == 8 &&  this.replaceComment  !== false: // comment
21208                     this.replaceComment(e);
21209                     return;
21210                 
21211                 case e.nodeType != 1: //not a node.
21212                     return;
21213                 
21214                 case this.tag === true: // everything
21215                 case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1:
21216                 case e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":":
21217                 case typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1: // array and it matches.
21218                 case typeof(this.tag) == 'string' && this.tag == e.tagName: // array and it matches.
21219                     if (this.replaceTag && false === this.replaceTag(e)) {
21220                         return;
21221                     }
21222                     if (e.hasChildNodes()) {
21223                         this.walk(e);
21224                     }
21225                     return;
21226                 
21227                 default:    // tags .. that do not match.
21228                     if (e.hasChildNodes()) {
21229                         this.walk(e);
21230                     }
21231             }
21232             
21233         }, this);
21234         
21235     },
21236     
21237     
21238     removeNodeKeepChildren : function( node)
21239     {
21240     
21241         ar = Array.from(node.childNodes);
21242         for (var i = 0; i < ar.length; i++) {
21243          
21244             node.removeChild(ar[i]);
21245             // what if we need to walk these???
21246             node.parentNode.insertBefore(ar[i], node);
21247            
21248         }
21249         node.parentNode.removeChild(node);
21250     }
21251 }; 
21252
21253 /**
21254  * @class Roo.htmleditor.FilterAttributes
21255  * clean attributes and  styles including http:// etc.. in attribute
21256  * @constructor
21257 * Run a new Attribute Filter
21258 * @param {Object} config Configuration options
21259  */
21260 Roo.htmleditor.FilterAttributes = function(cfg)
21261 {
21262     Roo.apply(this, cfg);
21263     this.attrib_black = this.attrib_black || [];
21264     this.attrib_white = this.attrib_white || [];
21265
21266     this.attrib_clean = this.attrib_clean || [];
21267     this.style_white = this.style_white || [];
21268     this.style_black = this.style_black || [];
21269     this.walk(cfg.node);
21270 }
21271
21272 Roo.extend(Roo.htmleditor.FilterAttributes, Roo.htmleditor.Filter,
21273 {
21274     tag: true, // all tags
21275     
21276     attrib_black : false, // array
21277     attrib_clean : false,
21278     attrib_white : false,
21279
21280     style_white : false,
21281     style_black : false,
21282      
21283      
21284     replaceTag : function(node)
21285     {
21286         if (!node.attributes || !node.attributes.length) {
21287             return true;
21288         }
21289         
21290         for (var i = node.attributes.length-1; i > -1 ; i--) {
21291             var a = node.attributes[i];
21292             //console.log(a);
21293             if (this.attrib_white.length && this.attrib_white.indexOf(a.name.toLowerCase()) < 0) {
21294                 node.removeAttribute(a.name);
21295                 continue;
21296             }
21297             
21298             
21299             
21300             if (a.name.toLowerCase().substr(0,2)=='on')  {
21301                 node.removeAttribute(a.name);
21302                 continue;
21303             }
21304             
21305             
21306             if (this.attrib_black.indexOf(a.name.toLowerCase()) > -1) {
21307                 node.removeAttribute(a.name);
21308                 continue;
21309             }
21310             if (this.attrib_clean.indexOf(a.name.toLowerCase()) > -1) {
21311                 this.cleanAttr(node,a.name,a.value); // fixme..
21312                 continue;
21313             }
21314             if (a.name == 'style') {
21315                 this.cleanStyle(node,a.name,a.value);
21316                 continue;
21317             }
21318             /// clean up MS crap..
21319             // tecnically this should be a list of valid class'es..
21320             
21321             
21322             if (a.name == 'class') {
21323                 if (a.value.match(/^Mso/)) {
21324                     node.removeAttribute('class');
21325                 }
21326                 
21327                 if (a.value.match(/^body$/)) {
21328                     node.removeAttribute('class');
21329                 }
21330                 continue;
21331             }
21332             
21333             
21334             // style cleanup!?
21335             // class cleanup?
21336             
21337         }
21338         return true; // clean children
21339     },
21340         
21341     cleanAttr: function(node, n,v)
21342     {
21343         
21344         if (v.match(/^\./) || v.match(/^\//)) {
21345             return;
21346         }
21347         if (v.match(/^(http|https):\/\//)
21348             || v.match(/^mailto:/) 
21349             || v.match(/^ftp:/)
21350             || v.match(/^data:/)
21351             ) {
21352             return;
21353         }
21354         if (v.match(/^#/)) {
21355             return;
21356         }
21357         if (v.match(/^\{/)) { // allow template editing.
21358             return;
21359         }
21360 //            Roo.log("(REMOVE TAG)"+ node.tagName +'.' + n + '=' + v);
21361         node.removeAttribute(n);
21362         
21363     },
21364     cleanStyle : function(node,  n,v)
21365     {
21366         if (v.match(/expression/)) { //XSS?? should we even bother..
21367             node.removeAttribute(n);
21368             return;
21369         }
21370         
21371         var parts = v.split(/;/);
21372         var clean = [];
21373         
21374         Roo.each(parts, function(p) {
21375             p = p.replace(/^\s+/g,'').replace(/\s+$/g,'');
21376             if (!p.length) {
21377                 return true;
21378             }
21379             var l = p.split(':').shift().replace(/\s+/g,'');
21380             l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
21381             
21382             if ( this.style_black.length && (this.style_black.indexOf(l) > -1 || this.style_black.indexOf(l.toLowerCase()) > -1)) {
21383                 return true;
21384             }
21385             //Roo.log()
21386             // only allow 'c whitelisted system attributes'
21387             if ( this.style_white.length &&  style_white.indexOf(l) < 0 && style_white.indexOf(l.toLowerCase()) < 0 ) {
21388                 return true;
21389             }
21390             
21391             
21392             clean.push(p);
21393             return true;
21394         },this);
21395         if (clean.length) { 
21396             node.setAttribute(n, clean.join(';'));
21397         } else {
21398             node.removeAttribute(n);
21399         }
21400         
21401     }
21402         
21403         
21404         
21405     
21406 });/**
21407  * @class Roo.htmleditor.FilterBlack
21408  * remove blacklisted elements.
21409  * @constructor
21410  * Run a new Blacklisted Filter
21411  * @param {Object} config Configuration options
21412  */
21413
21414 Roo.htmleditor.FilterBlack = function(cfg)
21415 {
21416     Roo.apply(this, cfg);
21417     this.walk(cfg.node);
21418 }
21419
21420 Roo.extend(Roo.htmleditor.FilterBlack, Roo.htmleditor.Filter,
21421 {
21422     tag : true, // all elements.
21423    
21424     replaceTag : function(n)
21425     {
21426         n.parentNode.removeChild(n);
21427     }
21428 });
21429 /**
21430  * @class Roo.htmleditor.FilterComment
21431  * remove comments.
21432  * @constructor
21433 * Run a new Comments Filter
21434 * @param {Object} config Configuration options
21435  */
21436 Roo.htmleditor.FilterComment = function(cfg)
21437 {
21438     this.walk(cfg.node);
21439 }
21440
21441 Roo.extend(Roo.htmleditor.FilterComment, Roo.htmleditor.Filter,
21442 {
21443   
21444     replaceComment : function(n)
21445     {
21446         n.parentNode.removeChild(n);
21447     }
21448 });/**
21449  * @class Roo.htmleditor.FilterKeepChildren
21450  * remove tags but keep children
21451  * @constructor
21452  * Run a new Keep Children Filter
21453  * @param {Object} config Configuration options
21454  */
21455
21456 Roo.htmleditor.FilterKeepChildren = function(cfg)
21457 {
21458     Roo.apply(this, cfg);
21459     if (this.tag === false) {
21460         return; // dont walk.. (you can use this to use this just to do a child removal on a single tag )
21461     }
21462     // hacky?
21463     if ((typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)) {
21464         this.cleanNamespace = true;
21465     }
21466         
21467     this.walk(cfg.node);
21468 }
21469
21470 Roo.extend(Roo.htmleditor.FilterKeepChildren, Roo.htmleditor.FilterBlack,
21471 {
21472     cleanNamespace : false, // should really be an option, rather than using ':' inside of this tag.
21473   
21474     replaceTag : function(node)
21475     {
21476         // walk children...
21477         //Roo.log(node.tagName);
21478         var ar = Array.from(node.childNodes);
21479         //remove first..
21480         
21481         for (var i = 0; i < ar.length; i++) {
21482             var e = ar[i];
21483             if (e.nodeType == 1) {
21484                 if (
21485                     (typeof(this.tag) == 'object' && this.tag.indexOf(e.tagName) > -1)
21486                     || // array and it matches
21487                     (typeof(this.tag) == 'string' && this.tag == e.tagName)
21488                     ||
21489                     (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'object' && this.tag.indexOf(":") > -1)
21490                     ||
21491                     (e.tagName.indexOf(":") > -1 && typeof(this.tag) == 'string' && this.tag == ":")
21492                 ) {
21493                     this.replaceTag(ar[i]); // child is blacklisted as well...
21494                     continue;
21495                 }
21496             }
21497         }  
21498         ar = Array.from(node.childNodes);
21499         for (var i = 0; i < ar.length; i++) {
21500          
21501             node.removeChild(ar[i]);
21502             // what if we need to walk these???
21503             node.parentNode.insertBefore(ar[i], node);
21504             if (this.tag !== false) {
21505                 this.walk(ar[i]);
21506                 
21507             }
21508         }
21509         //Roo.log("REMOVE:" + node.tagName);
21510         node.parentNode.removeChild(node);
21511         return false; // don't walk children
21512         
21513         
21514     }
21515 });/**
21516  * @class Roo.htmleditor.FilterParagraph
21517  * paragraphs cause a nightmare for shared content - this filter is designed to be called ? at various points when editing
21518  * like on 'push' to remove the <p> tags and replace them with line breaks.
21519  * @constructor
21520  * Run a new Paragraph Filter
21521  * @param {Object} config Configuration options
21522  */
21523
21524 Roo.htmleditor.FilterParagraph = function(cfg)
21525 {
21526     // no need to apply config.
21527     this.walk(cfg.node);
21528 }
21529
21530 Roo.extend(Roo.htmleditor.FilterParagraph, Roo.htmleditor.Filter,
21531 {
21532     
21533      
21534     tag : 'P',
21535     
21536      
21537     replaceTag : function(node)
21538     {
21539         
21540         if (node.childNodes.length == 1 &&
21541             node.childNodes[0].nodeType == 3 &&
21542             node.childNodes[0].textContent.trim().length < 1
21543             ) {
21544             // remove and replace with '<BR>';
21545             node.parentNode.replaceChild(node.ownerDocument.createElement('BR'),node);
21546             return false; // no need to walk..
21547         }
21548         var ar = Array.from(node.childNodes);
21549         for (var i = 0; i < ar.length; i++) {
21550             node.removeChild(ar[i]);
21551             // what if we need to walk these???
21552             node.parentNode.insertBefore(ar[i], node);
21553         }
21554         // now what about this?
21555         // <p> &nbsp; </p>
21556         
21557         // double BR.
21558         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
21559         node.parentNode.insertBefore(node.ownerDocument.createElement('BR'), node);
21560         node.parentNode.removeChild(node);
21561         
21562         return false;
21563
21564     }
21565     
21566 });/**
21567  * @class Roo.htmleditor.FilterSpan
21568  * filter span's with no attributes out..
21569  * @constructor
21570  * Run a new Span Filter
21571  * @param {Object} config Configuration options
21572  */
21573
21574 Roo.htmleditor.FilterSpan = function(cfg)
21575 {
21576     // no need to apply config.
21577     this.walk(cfg.node);
21578 }
21579
21580 Roo.extend(Roo.htmleditor.FilterSpan, Roo.htmleditor.FilterKeepChildren,
21581 {
21582      
21583     tag : 'SPAN',
21584      
21585  
21586     replaceTag : function(node)
21587     {
21588         if (node.attributes && node.attributes.length > 0) {
21589             return true; // walk if there are any.
21590         }
21591         Roo.htmleditor.FilterKeepChildren.prototype.replaceTag.call(this, node);
21592         return false;
21593      
21594     }
21595     
21596 });/**
21597  * @class Roo.htmleditor.FilterTableWidth
21598   try and remove table width data - as that frequently messes up other stuff.
21599  * 
21600  *      was cleanTableWidths.
21601  *
21602  * Quite often pasting from word etc.. results in tables with column and widths.
21603  * This does not work well on fluid HTML layouts - like emails. - so this code should hunt an destroy them..
21604  *
21605  * @constructor
21606  * Run a new Table Filter
21607  * @param {Object} config Configuration options
21608  */
21609
21610 Roo.htmleditor.FilterTableWidth = function(cfg)
21611 {
21612     // no need to apply config.
21613     this.tag = ['TABLE', 'TD', 'TR', 'TH', 'THEAD', 'TBODY' ];
21614     this.walk(cfg.node);
21615 }
21616
21617 Roo.extend(Roo.htmleditor.FilterTableWidth, Roo.htmleditor.Filter,
21618 {
21619      
21620      
21621     
21622     replaceTag: function(node) {
21623         
21624         
21625       
21626         if (node.hasAttribute('width')) {
21627             node.removeAttribute('width');
21628         }
21629         
21630          
21631         if (node.hasAttribute("style")) {
21632             // pretty basic...
21633             
21634             var styles = node.getAttribute("style").split(";");
21635             var nstyle = [];
21636             Roo.each(styles, function(s) {
21637                 if (!s.match(/:/)) {
21638                     return;
21639                 }
21640                 var kv = s.split(":");
21641                 if (kv[0].match(/^\s*(width|min-width)\s*$/)) {
21642                     return;
21643                 }
21644                 // what ever is left... we allow.
21645                 nstyle.push(s);
21646             });
21647             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
21648             if (!nstyle.length) {
21649                 node.removeAttribute('style');
21650             }
21651         }
21652         
21653         return true; // continue doing children..
21654     }
21655 });/**
21656  * @class Roo.htmleditor.FilterWord
21657  * try and clean up all the mess that Word generates.
21658  * 
21659  * This is the 'nice version' - see 'Heavy' that white lists a very short list of elements, and multi-filters 
21660  
21661  * @constructor
21662  * Run a new Span Filter
21663  * @param {Object} config Configuration options
21664  */
21665
21666 Roo.htmleditor.FilterWord = function(cfg)
21667 {
21668     // no need to apply config.
21669     this.replaceDocBullets(cfg.node);
21670     
21671     this.replaceAname(cfg.node);
21672     // this is disabled as the removal is done by other filters;
21673    // this.walk(cfg.node);
21674     this.replaceImageTable(cfg.node);
21675     
21676 }
21677
21678 Roo.extend(Roo.htmleditor.FilterWord, Roo.htmleditor.Filter,
21679 {
21680     tag: true,
21681      
21682     
21683     /**
21684      * Clean up MS wordisms...
21685      */
21686     replaceTag : function(node)
21687     {
21688          
21689         // no idea what this does - span with text, replaceds with just text.
21690         if(
21691                 node.nodeName == 'SPAN' &&
21692                 !node.hasAttributes() &&
21693                 node.childNodes.length == 1 &&
21694                 node.firstChild.nodeName == "#text"  
21695         ) {
21696             var textNode = node.firstChild;
21697             node.removeChild(textNode);
21698             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
21699                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" "), node);
21700             }
21701             node.parentNode.insertBefore(textNode, node);
21702             if (node.getAttribute('lang') != 'zh-CN') {   // do not space pad on chinese characters..
21703                 node.parentNode.insertBefore(node.ownerDocument.createTextNode(" ") , node);
21704             }
21705             
21706             node.parentNode.removeChild(node);
21707             return false; // dont do chidren - we have remove our node - so no need to do chdhilren?
21708         }
21709         
21710    
21711         
21712         if (node.tagName.toLowerCase().match(/^(style|script|applet|embed|noframes|noscript)$/)) {
21713             node.parentNode.removeChild(node);
21714             return false; // dont do chidlren
21715         }
21716         //Roo.log(node.tagName);
21717         // remove - but keep children..
21718         if (node.tagName.toLowerCase().match(/^(meta|link|\\?xml:|st1:|o:|v:|font)/)) {
21719             //Roo.log('-- removed');
21720             while (node.childNodes.length) {
21721                 var cn = node.childNodes[0];
21722                 node.removeChild(cn);
21723                 node.parentNode.insertBefore(cn, node);
21724                 // move node to parent - and clean it..
21725                 if (cn.nodeType == 1) {
21726                     this.replaceTag(cn);
21727                 }
21728                 
21729             }
21730             node.parentNode.removeChild(node);
21731             /// no need to iterate chidlren = it's got none..
21732             //this.iterateChildren(node, this.cleanWord);
21733             return false; // no need to iterate children.
21734         }
21735         // clean styles
21736         if (node.className.length) {
21737             
21738             var cn = node.className.split(/\W+/);
21739             var cna = [];
21740             Roo.each(cn, function(cls) {
21741                 if (cls.match(/Mso[a-zA-Z]+/)) {
21742                     return;
21743                 }
21744                 cna.push(cls);
21745             });
21746             node.className = cna.length ? cna.join(' ') : '';
21747             if (!cna.length) {
21748                 node.removeAttribute("class");
21749             }
21750         }
21751         
21752         if (node.hasAttribute("lang")) {
21753             node.removeAttribute("lang");
21754         }
21755         
21756         if (node.hasAttribute("style")) {
21757             
21758             var styles = node.getAttribute("style").split(";");
21759             var nstyle = [];
21760             Roo.each(styles, function(s) {
21761                 if (!s.match(/:/)) {
21762                     return;
21763                 }
21764                 var kv = s.split(":");
21765                 if (kv[0].match(/^(mso-|line|font|background|margin|padding|color)/)) {
21766                     return;
21767                 }
21768                 // what ever is left... we allow.
21769                 nstyle.push(s);
21770             });
21771             node.setAttribute("style", nstyle.length ? nstyle.join(';') : '');
21772             if (!nstyle.length) {
21773                 node.removeAttribute('style');
21774             }
21775         }
21776         return true; // do children
21777         
21778         
21779         
21780     },
21781     
21782     styleToObject: function(node)
21783     {
21784         var styles = (node.getAttribute("style") || '').split(";");
21785         var ret = {};
21786         Roo.each(styles, function(s) {
21787             if (!s.match(/:/)) {
21788                 return;
21789             }
21790             var kv = s.split(":");
21791              
21792             // what ever is left... we allow.
21793             ret[kv[0].trim()] = kv[1];
21794         });
21795         return ret;
21796     },
21797     
21798     
21799     replaceAname : function (doc)
21800     {
21801         // replace all the a/name without..
21802         var aa = Array.from(doc.getElementsByTagName('a'));
21803         for (var i = 0; i  < aa.length; i++) {
21804             var a = aa[i];
21805             if (a.hasAttribute("name")) {
21806                 a.removeAttribute("name");
21807             }
21808             if (a.hasAttribute("href")) {
21809                 continue;
21810             }
21811             // reparent children.
21812             this.removeNodeKeepChildren(a);
21813             
21814         }
21815         
21816         
21817         
21818     },
21819
21820     
21821     
21822     replaceDocBullets : function(doc)
21823     {
21824         // this is a bit odd - but it appears some indents use ql-indent-1
21825          //Roo.log(doc.innerHTML);
21826         
21827         var listpara = Array.from(doc.getElementsByClassName('MsoListParagraphCxSpFirst'));
21828         for( var i = 0; i < listpara.length; i ++) {
21829             listpara[i].className = "MsoListParagraph";
21830         }
21831         
21832         listpara =  Array.from(doc.getElementsByClassName('MsoListParagraphCxSpMiddle'));
21833         for( var i = 0; i < listpara.length; i ++) {
21834             listpara[i].className = "MsoListParagraph";
21835         }
21836         listpara =  Array.from(doc.getElementsByClassName('MsoListParagraphCxSpLast'));
21837         for( var i = 0; i < listpara.length; i ++) {
21838             listpara[i].className = "MsoListParagraph";
21839         }
21840         listpara =  Array.from(doc.getElementsByClassName('ql-indent-1'));
21841         for( var i = 0; i < listpara.length; i ++) {
21842             listpara[i].className = "MsoListParagraph";
21843         }
21844         
21845         // this is a bit hacky - we had one word document where h2 had a miso-list attribute.
21846         var htwo =  Array.from(doc.getElementsByTagName('h2'));
21847         for( var i = 0; i < htwo.length; i ++) {
21848             if (htwo[i].hasAttribute('style') && htwo[i].getAttribute('style').match(/mso-list:/)) {
21849                 htwo[i].className = "MsoListParagraph";
21850             }
21851         }
21852         listpara =  Array.from(doc.getElementsByClassName('MsoNormal'));
21853         for( var i = 0; i < listpara.length; i ++) {
21854             if (listpara[i].hasAttribute('style') && listpara[i].getAttribute('style').match(/mso-list:/)) {
21855                 listpara[i].className = "MsoListParagraph";
21856             } else {
21857                 listpara[i].className = "MsoNormalx";
21858             }
21859         }
21860        
21861         listpara = doc.getElementsByClassName('MsoListParagraph');
21862         // Roo.log(doc.innerHTML);
21863         
21864         
21865         
21866         while(listpara.length) {
21867             
21868             this.replaceDocBullet(listpara.item(0));
21869         }
21870       
21871     },
21872     
21873      
21874     
21875     replaceDocBullet : function(p)
21876     {
21877         // gather all the siblings.
21878         var ns = p,
21879             parent = p.parentNode,
21880             doc = parent.ownerDocument,
21881             items = [];
21882          
21883         //Roo.log("Parsing: " + p.innerText)    ;
21884         var listtype = 'ul';   
21885         while (ns) {
21886             if (ns.nodeType != 1) {
21887                 ns = ns.nextSibling;
21888                 continue;
21889             }
21890             if (!ns.className.match(/(MsoListParagraph|ql-indent-1)/i)) {
21891                 //Roo.log("Missing para r q1indent - got:" + ns.className);
21892                 break;
21893             }
21894             var spans = ns.getElementsByTagName('span');
21895             
21896             if (ns.hasAttribute('style') && ns.getAttribute('style').match(/mso-list/)) {
21897                 items.push(ns);
21898                 ns = ns.nextSibling;
21899                 has_list = true;
21900                 if (!spans.length) {
21901                     continue;
21902                 }
21903                 var ff = '';
21904                 var se = spans[0];
21905                 for (var i = 0; i < spans.length;i++) {
21906                     se = spans[i];
21907                     if (se.hasAttribute('style')  && se.hasAttribute('style') && se.style.fontFamily != '') {
21908                         ff = se.style.fontFamily;
21909                         break;
21910                     }
21911                 }
21912                  
21913                     
21914                 //Roo.log("got font family: " + ff);
21915                 if (typeof(ff) != 'undefined' && !ff.match(/(Symbol|Wingdings)/) && "·o".indexOf(se.innerText.trim()) < 0) {
21916                     listtype = 'ol';
21917                 }
21918                 
21919                 continue;
21920             }
21921             //Roo.log("no mso-list?");
21922             
21923             var spans = ns.getElementsByTagName('span');
21924             if (!spans.length) {
21925                 break;
21926             }
21927             var has_list  = false;
21928             for(var i = 0; i < spans.length; i++) {
21929                 if (spans[i].hasAttribute('style') && spans[i].getAttribute('style').match(/mso-list/)) {
21930                     has_list = true;
21931                     break;
21932                 }
21933             }
21934             if (!has_list) {
21935                 break;
21936             }
21937             items.push(ns);
21938             ns = ns.nextSibling;
21939             
21940             
21941         }
21942         if (!items.length) {
21943             ns.className = "";
21944             return;
21945         }
21946         
21947         var ul = parent.ownerDocument.createElement(listtype); // what about number lists...
21948         parent.insertBefore(ul, p);
21949         var lvl = 0;
21950         var stack = [ ul ];
21951         var last_li = false;
21952         
21953         var margin_to_depth = {};
21954         max_margins = -1;
21955         
21956         items.forEach(function(n, ipos) {
21957             //Roo.log("got innertHMLT=" + n.innerHTML);
21958             
21959             var spans = n.getElementsByTagName('span');
21960             if (!spans.length) {
21961                 //Roo.log("No spans found");
21962                  
21963                 parent.removeChild(n);
21964                 
21965                 
21966                 return; // skip it...
21967             }
21968            
21969                 
21970             var num = 1;
21971             var style = {};
21972             for(var i = 0; i < spans.length; i++) {
21973             
21974                 style = this.styleToObject(spans[i]);
21975                 if (typeof(style['mso-list']) == 'undefined') {
21976                     continue;
21977                 }
21978                 if (listtype == 'ol') {
21979                    num = spans[i].innerText.replace(/[^0-9]+]/g,'')  * 1;
21980                 }
21981                 spans[i].parentNode.removeChild(spans[i]); // remove the fake bullet.
21982                 break;
21983             }
21984             //Roo.log("NOW GOT innertHMLT=" + n.innerHTML);
21985             style = this.styleToObject(n); // mo-list is from the parent node.
21986             if (typeof(style['mso-list']) == 'undefined') {
21987                 //Roo.log("parent is missing level");
21988                   
21989                 parent.removeChild(n);
21990                  
21991                 return;
21992             }
21993             
21994             var margin = style['margin-left'];
21995             if (typeof(margin_to_depth[margin]) == 'undefined') {
21996                 max_margins++;
21997                 margin_to_depth[margin] = max_margins;
21998             }
21999             nlvl = margin_to_depth[margin] ;
22000              
22001             if (nlvl > lvl) {
22002                 //new indent
22003                 var nul = doc.createElement(listtype); // what about number lists...
22004                 if (!last_li) {
22005                     last_li = doc.createElement('li');
22006                     stack[lvl].appendChild(last_li);
22007                 }
22008                 last_li.appendChild(nul);
22009                 stack[nlvl] = nul;
22010                 
22011             }
22012             lvl = nlvl;
22013             
22014             // not starting at 1..
22015             if (!stack[nlvl].hasAttribute("start") && listtype == "ol") {
22016                 stack[nlvl].setAttribute("start", num);
22017             }
22018             
22019             var nli = stack[nlvl].appendChild(doc.createElement('li'));
22020             last_li = nli;
22021             nli.innerHTML = n.innerHTML;
22022             //Roo.log("innerHTML = " + n.innerHTML);
22023             parent.removeChild(n);
22024             
22025              
22026              
22027             
22028         },this);
22029         
22030         
22031         
22032         
22033     },
22034     
22035     replaceImageTable : function(doc)
22036     {
22037          /*
22038           <table cellpadding=0 cellspacing=0 align=left>
22039   <tr>
22040    <td width=423 height=0></td>
22041   </tr>
22042   <tr>
22043    <td></td>
22044    <td><img width=601 height=401
22045    src="file:///C:/Users/Alan/AppData/Local/Temp/msohtmlclip1/01/clip_image002.jpg"
22046    v:shapes="Picture_x0020_2"></td>
22047   </tr>
22048  </table>
22049  */
22050         var imgs = Array.from(doc.getElementsByTagName('img'));
22051         Roo.each(imgs, function(img) {
22052             var td = img.parentNode;
22053             if (td.nodeName !=  'TD') {
22054                 return;
22055             }
22056             var tr = td.parentNode;
22057             if (tr.nodeName !=  'TR') {
22058                 return;
22059             }
22060             var tbody = tr.parentNode;
22061             if (tbody.nodeName !=  'TBODY') {
22062                 return;
22063             }
22064             var table = tbody.parentNode;
22065             if (table.nodeName !=  'TABLE') {
22066                 return;
22067             }
22068             // first row..
22069             
22070             if (table.getElementsByTagName('tr').length != 2) {
22071                 return;
22072             }
22073             if (table.getElementsByTagName('td').length != 3) {
22074                 return;
22075             }
22076             if (table.innerText.trim() != '') {
22077                 return;
22078             }
22079             var p = table.parentNode;
22080             img.parentNode.removeChild(img);
22081             p.insertBefore(img, table);
22082             p.removeChild(table);
22083             
22084             
22085             
22086         });
22087         
22088       
22089     }
22090     
22091 });
22092 /**
22093  * @class Roo.htmleditor.FilterStyleToTag
22094  * part of the word stuff... - certain 'styles' should be converted to tags.
22095  * eg.
22096  *   font-weight: bold -> bold
22097  *   ?? super / subscrit etc..
22098  * 
22099  * @constructor
22100 * Run a new style to tag filter.
22101 * @param {Object} config Configuration options
22102  */
22103 Roo.htmleditor.FilterStyleToTag = function(cfg)
22104 {
22105     
22106     this.tags = {
22107         B  : [ 'fontWeight' , 'bold'],
22108         I :  [ 'fontStyle' , 'italic'],
22109         //pre :  [ 'font-style' , 'italic'],
22110         // h1.. h6 ?? font-size?
22111         SUP : [ 'verticalAlign' , 'super' ],
22112         SUB : [ 'verticalAlign' , 'sub' ]
22113         
22114         
22115     };
22116     
22117     Roo.apply(this, cfg);
22118      
22119     
22120     this.walk(cfg.node);
22121     
22122     
22123     
22124 }
22125
22126
22127 Roo.extend(Roo.htmleditor.FilterStyleToTag, Roo.htmleditor.Filter,
22128 {
22129     tag: true, // all tags
22130     
22131     tags : false,
22132     
22133     
22134     replaceTag : function(node)
22135     {
22136         
22137         
22138         if (node.getAttribute("style") === null) {
22139             return true;
22140         }
22141         var inject = [];
22142         for (var k in this.tags) {
22143             if (node.style[this.tags[k][0]] == this.tags[k][1]) {
22144                 inject.push(k);
22145                 node.style.removeProperty(this.tags[k][0]);
22146             }
22147         }
22148         if (!inject.length) {
22149             return true; 
22150         }
22151         var cn = Array.from(node.childNodes);
22152         var nn = node;
22153         Roo.each(inject, function(t) {
22154             var nc = node.ownerDocument.createElement(t);
22155             nn.appendChild(nc);
22156             nn = nc;
22157         });
22158         for(var i = 0;i < cn.length;cn++) {
22159             node.removeChild(cn[i]);
22160             nn.appendChild(cn[i]);
22161         }
22162         return true /// iterate thru
22163     }
22164     
22165 })/**
22166  * @class Roo.htmleditor.FilterLongBr
22167  * BR/BR/BR - keep a maximum of 2...
22168  * @constructor
22169  * Run a new Long BR Filter
22170  * @param {Object} config Configuration options
22171  */
22172
22173 Roo.htmleditor.FilterLongBr = function(cfg)
22174 {
22175     // no need to apply config.
22176     this.walk(cfg.node);
22177 }
22178
22179 Roo.extend(Roo.htmleditor.FilterLongBr, Roo.htmleditor.Filter,
22180 {
22181     
22182      
22183     tag : 'BR',
22184     
22185      
22186     replaceTag : function(node)
22187     {
22188         
22189         var ps = node.nextSibling;
22190         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
22191             ps = ps.nextSibling;
22192         }
22193         
22194         if (!ps &&  [ 'TD', 'TH', 'LI', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(node.parentNode.tagName) > -1) { 
22195             node.parentNode.removeChild(node); // remove last BR inside one fo these tags
22196             return false;
22197         }
22198         
22199         if (!ps || ps.nodeType != 1) {
22200             return false;
22201         }
22202         
22203         if (!ps || ps.tagName != 'BR') {
22204            
22205             return false;
22206         }
22207         
22208         
22209         
22210         
22211         
22212         if (!node.previousSibling) {
22213             return false;
22214         }
22215         var ps = node.previousSibling;
22216         
22217         while (ps && ps.nodeType == 3 && ps.nodeValue.trim().length < 1) {
22218             ps = ps.previousSibling;
22219         }
22220         if (!ps || ps.nodeType != 1) {
22221             return false;
22222         }
22223         // if header or BR before.. then it's a candidate for removal.. - as we only want '2' of these..
22224         if (!ps || [ 'BR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].indexOf(ps.tagName) < 0) {
22225             return false;
22226         }
22227         
22228         node.parentNode.removeChild(node); // remove me...
22229         
22230         return false; // no need to do children
22231
22232     }
22233     
22234 }); 
22235
22236 /**
22237  * @class Roo.htmleditor.FilterBlock
22238  * removes id / data-block and contenteditable that are associated with blocks
22239  * usage should be done on a cloned copy of the dom
22240  * @constructor
22241 * Run a new Attribute Filter { node : xxxx }}
22242 * @param {Object} config Configuration options
22243  */
22244 Roo.htmleditor.FilterBlock = function(cfg)
22245 {
22246     Roo.apply(this, cfg);
22247     var qa = cfg.node.querySelectorAll;
22248     this.removeAttributes('data-block');
22249     this.removeAttributes('contenteditable');
22250     this.removeAttributes('id');
22251     
22252 }
22253
22254 Roo.apply(Roo.htmleditor.FilterBlock.prototype,
22255 {
22256     node: true, // all tags
22257      
22258      
22259     removeAttributes : function(attr)
22260     {
22261         var ar = this.node.querySelectorAll('*[' + attr + ']');
22262         for (var i =0;i<ar.length;i++) {
22263             ar[i].removeAttribute(attr);
22264         }
22265     }
22266         
22267         
22268         
22269     
22270 });
22271 /***
22272  * This is based loosely on tinymce 
22273  * @class Roo.htmleditor.TidySerializer
22274  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
22275  * @constructor
22276  * @method Serializer
22277  * @param {Object} settings Name/value settings object.
22278  */
22279
22280
22281 Roo.htmleditor.TidySerializer = function(settings)
22282 {
22283     Roo.apply(this, settings);
22284     
22285     this.writer = new Roo.htmleditor.TidyWriter(settings);
22286     
22287     
22288
22289 };
22290 Roo.htmleditor.TidySerializer.prototype = {
22291     
22292     /**
22293      * @param {boolean} inner do the inner of the node.
22294      */
22295     inner : false,
22296     
22297     writer : false,
22298     
22299     /**
22300     * Serializes the specified node into a string.
22301     *
22302     * @example
22303     * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('<p>text</p>'));
22304     * @method serialize
22305     * @param {DomElement} node Node instance to serialize.
22306     * @return {String} String with HTML based on DOM tree.
22307     */
22308     serialize : function(node) {
22309         
22310         // = settings.validate;
22311         var writer = this.writer;
22312         var self  = this;
22313         this.handlers = {
22314             // #text
22315             3: function(node) {
22316                 
22317                 writer.text(node.nodeValue, node);
22318             },
22319             // #comment
22320             8: function(node) {
22321                 writer.comment(node.nodeValue);
22322             },
22323             // Processing instruction
22324             7: function(node) {
22325                 writer.pi(node.name, node.nodeValue);
22326             },
22327             // Doctype
22328             10: function(node) {
22329                 writer.doctype(node.nodeValue);
22330             },
22331             // CDATA
22332             4: function(node) {
22333                 writer.cdata(node.nodeValue);
22334             },
22335             // Document fragment
22336             11: function(node) {
22337                 node = node.firstChild;
22338                 if (!node) {
22339                     return;
22340                 }
22341                 while(node) {
22342                     self.walk(node);
22343                     node = node.nextSibling
22344                 }
22345             }
22346         };
22347         writer.reset();
22348         1 != node.nodeType || this.inner ? this.handlers[11](node) : this.walk(node);
22349         return writer.getContent();
22350     },
22351
22352     walk: function(node)
22353     {
22354         var attrName, attrValue, sortedAttrs, i, l, elementRule,
22355             handler = this.handlers[node.nodeType];
22356             
22357         if (handler) {
22358             handler(node);
22359             return;
22360         }
22361     
22362         var name = node.nodeName;
22363         var isEmpty = node.childNodes.length < 1;
22364       
22365         var writer = this.writer;
22366         var attrs = node.attributes;
22367         // Sort attributes
22368         
22369         writer.start(node.nodeName, attrs, isEmpty, node);
22370         if (isEmpty) {
22371             return;
22372         }
22373         node = node.firstChild;
22374         if (!node) {
22375             writer.end(name);
22376             return;
22377         }
22378         while (node) {
22379             this.walk(node);
22380             node = node.nextSibling;
22381         }
22382         writer.end(name);
22383         
22384     
22385     }
22386     // Serialize element and treat all non elements as fragments
22387    
22388 }; 
22389
22390 /***
22391  * This is based loosely on tinymce 
22392  * @class Roo.htmleditor.TidyWriter
22393  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
22394  *
22395  * Known issues?
22396  * - not tested much with 'PRE' formated elements.
22397  * 
22398  *
22399  *
22400  */
22401
22402 Roo.htmleditor.TidyWriter = function(settings)
22403 {
22404     
22405     // indent, indentBefore, indentAfter, encode, htmlOutput, html = [];
22406     Roo.apply(this, settings);
22407     this.html = [];
22408     this.state = [];
22409      
22410     this.encode = Roo.htmleditor.TidyEntities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
22411   
22412 }
22413 Roo.htmleditor.TidyWriter.prototype = {
22414
22415  
22416     state : false,
22417     
22418     indent :  '  ',
22419     
22420     // part of state...
22421     indentstr : '',
22422     in_pre: false,
22423     in_inline : false,
22424     last_inline : false,
22425     encode : false,
22426      
22427     
22428             /**
22429     * Writes the a start element such as <p id="a">.
22430     *
22431     * @method start
22432     * @param {String} name Name of the element.
22433     * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
22434     * @param {Boolean} empty Optional empty state if the tag should end like <br />.
22435     */
22436     start: function(name, attrs, empty, node)
22437     {
22438         var i, l, attr, value;
22439         
22440         // there are some situations where adding line break && indentation will not work. will not work.
22441         // <span / b / i ... formating?
22442         
22443         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
22444         var in_pre    = this.in_pre    || Roo.htmleditor.TidyWriter.whitespace_elements.indexOf(name) > -1;
22445         
22446         var is_short   = empty ? Roo.htmleditor.TidyWriter.shortend_elements.indexOf(name) > -1 : false;
22447         
22448         var add_lb = name == 'BR' ? false : in_inline;
22449         
22450         if (!add_lb && !this.in_pre && this.lastElementEndsWS()) {
22451             i_inline = false;
22452         }
22453
22454         var indentstr =  this.indentstr;
22455         
22456         // e_inline = elements that can be inline, but still allow \n before and after?
22457         // only 'BR' ??? any others?
22458         
22459         // ADD LINE BEFORE tage
22460         if (!this.in_pre) {
22461             if (in_inline) {
22462                 //code
22463                 if (name == 'BR') {
22464                     this.addLine();
22465                 } else if (this.lastElementEndsWS()) {
22466                     this.addLine();
22467                 } else{
22468                     // otherwise - no new line. (and dont indent.)
22469                     indentstr = '';
22470                 }
22471                 
22472             } else {
22473                 this.addLine();
22474             }
22475         } else {
22476             indentstr = '';
22477         }
22478         
22479         this.html.push(indentstr + '<', name.toLowerCase());
22480         
22481         if (attrs) {
22482             for (i = 0, l = attrs.length; i < l; i++) {
22483                 attr = attrs[i];
22484                 this.html.push(' ', attr.name, '="', this.encode(attr.value, true), '"');
22485             }
22486         }
22487      
22488         if (empty) {
22489             if (is_short) {
22490                 this.html[this.html.length] = '/>';
22491             } else {
22492                 this.html[this.html.length] = '></' + name.toLowerCase() + '>';
22493             }
22494             var e_inline = name == 'BR' ? false : this.in_inline;
22495             
22496             if (!e_inline && !this.in_pre) {
22497                 this.addLine();
22498             }
22499             return;
22500         
22501         }
22502         // not empty..
22503         this.html[this.html.length] = '>';
22504         
22505         // there is a special situation, where we need to turn on in_inline - if any of the imediate chidlren are one of these.
22506         /*
22507         if (!in_inline && !in_pre) {
22508             var cn = node.firstChild;
22509             while(cn) {
22510                 if (Roo.htmleditor.TidyWriter.inline_elements.indexOf(cn.nodeName) > -1) {
22511                     in_inline = true
22512                     break;
22513                 }
22514                 cn = cn.nextSibling;
22515             }
22516              
22517         }
22518         */
22519         
22520         
22521         this.pushState({
22522             indentstr : in_pre   ? '' : (this.indentstr + this.indent),
22523             in_pre : in_pre,
22524             in_inline :  in_inline
22525         });
22526         // add a line after if we are not in a
22527         
22528         if (!in_inline && !in_pre) {
22529             this.addLine();
22530         }
22531         
22532             
22533          
22534         
22535     },
22536     
22537     lastElementEndsWS : function()
22538     {
22539         var value = this.html.length > 0 ? this.html[this.html.length-1] : false;
22540         if (value === false) {
22541             return true;
22542         }
22543         return value.match(/\s+$/);
22544         
22545     },
22546     
22547     /**
22548      * Writes the a end element such as </p>.
22549      *
22550      * @method end
22551      * @param {String} name Name of the element.
22552      */
22553     end: function(name) {
22554         var value;
22555         this.popState();
22556         var indentstr = '';
22557         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
22558         
22559         if (!this.in_pre && !in_inline) {
22560             this.addLine();
22561             indentstr  = this.indentstr;
22562         }
22563         this.html.push(indentstr + '</', name.toLowerCase(), '>');
22564         this.last_inline = in_inline;
22565         
22566         // pop the indent state..
22567     },
22568     /**
22569      * Writes a text node.
22570      *
22571      * In pre - we should not mess with the contents.
22572      * 
22573      *
22574      * @method text
22575      * @param {String} text String to write out.
22576      * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
22577      */
22578     text: function(in_text, node)
22579     {
22580         // if not in whitespace critical
22581         if (in_text.length < 1) {
22582             return;
22583         }
22584         var text = new XMLSerializer().serializeToString(document.createTextNode(in_text)); // escape it properly?
22585         
22586         if (this.in_pre) {
22587             this.html[this.html.length] =  text;
22588             return;   
22589         }
22590         
22591         if (this.in_inline) {
22592             text = text.replace(/\s+/g,' '); // all white space inc line breaks to a slingle' '
22593             if (text != ' ') {
22594                 text = text.replace(/\s+/,' ');  // all white space to single white space
22595                 
22596                     
22597                 // if next tag is '<BR>', then we can trim right..
22598                 if (node.nextSibling &&
22599                     node.nextSibling.nodeType == 1 &&
22600                     node.nextSibling.nodeName == 'BR' )
22601                 {
22602                     text = text.replace(/\s+$/g,'');
22603                 }
22604                 // if previous tag was a BR, we can also trim..
22605                 if (node.previousSibling &&
22606                     node.previousSibling.nodeType == 1 &&
22607                     node.previousSibling.nodeName == 'BR' )
22608                 {
22609                     text = this.indentstr +  text.replace(/^\s+/g,'');
22610                 }
22611                 if (text.match(/\n/)) {
22612                     text = text.replace(
22613                         /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
22614                     );
22615                     // remoeve the last whitespace / line break.
22616                     text = text.replace(/\n\s+$/,'');
22617                 }
22618                 // repace long lines
22619                 
22620             }
22621              
22622             this.html[this.html.length] =  text;
22623             return;   
22624         }
22625         // see if previous element was a inline element.
22626         var indentstr = this.indentstr;
22627    
22628         text = text.replace(/\s+/g," "); // all whitespace into single white space.
22629         
22630         // should trim left?
22631         if (node.previousSibling &&
22632             node.previousSibling.nodeType == 1 &&
22633             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.previousSibling.nodeName) > -1)
22634         {
22635             indentstr = '';
22636             
22637         } else {
22638             this.addLine();
22639             text = text.replace(/^\s+/,''); // trim left
22640           
22641         }
22642         // should trim right?
22643         if (node.nextSibling &&
22644             node.nextSibling.nodeType == 1 &&
22645             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.nextSibling.nodeName) > -1)
22646         {
22647           // noop
22648             
22649         }  else {
22650             text = text.replace(/\s+$/,''); // trim right
22651         }
22652          
22653               
22654         
22655         
22656         
22657         if (text.length < 1) {
22658             return;
22659         }
22660         if (!text.match(/\n/)) {
22661             this.html.push(indentstr + text);
22662             return;
22663         }
22664         
22665         text = this.indentstr + text.replace(
22666             /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
22667         );
22668         // remoeve the last whitespace / line break.
22669         text = text.replace(/\s+$/,''); 
22670         
22671         this.html.push(text);
22672         
22673         // split and indent..
22674         
22675         
22676     },
22677     /**
22678      * Writes a cdata node such as <![CDATA[data]]>.
22679      *
22680      * @method cdata
22681      * @param {String} text String to write out inside the cdata.
22682      */
22683     cdata: function(text) {
22684         this.html.push('<![CDATA[', text, ']]>');
22685     },
22686     /**
22687     * Writes a comment node such as <!-- Comment -->.
22688     *
22689     * @method cdata
22690     * @param {String} text String to write out inside the comment.
22691     */
22692    comment: function(text) {
22693        this.html.push('<!--', text, '-->');
22694    },
22695     /**
22696      * Writes a PI node such as <?xml attr="value" ?>.
22697      *
22698      * @method pi
22699      * @param {String} name Name of the pi.
22700      * @param {String} text String to write out inside the pi.
22701      */
22702     pi: function(name, text) {
22703         text ? this.html.push('<?', name, ' ', this.encode(text), '?>') : this.html.push('<?', name, '?>');
22704         this.indent != '' && this.html.push('\n');
22705     },
22706     /**
22707      * Writes a doctype node such as <!DOCTYPE data>.
22708      *
22709      * @method doctype
22710      * @param {String} text String to write out inside the doctype.
22711      */
22712     doctype: function(text) {
22713         this.html.push('<!DOCTYPE', text, '>', this.indent != '' ? '\n' : '');
22714     },
22715     /**
22716      * Resets the internal buffer if one wants to reuse the writer.
22717      *
22718      * @method reset
22719      */
22720     reset: function() {
22721         this.html.length = 0;
22722         this.state = [];
22723         this.pushState({
22724             indentstr : '',
22725             in_pre : false, 
22726             in_inline : false
22727         })
22728     },
22729     /**
22730      * Returns the contents that got serialized.
22731      *
22732      * @method getContent
22733      * @return {String} HTML contents that got written down.
22734      */
22735     getContent: function() {
22736         return this.html.join('').replace(/\n$/, '');
22737     },
22738     
22739     pushState : function(cfg)
22740     {
22741         this.state.push(cfg);
22742         Roo.apply(this, cfg);
22743     },
22744     
22745     popState : function()
22746     {
22747         if (this.state.length < 1) {
22748             return; // nothing to push
22749         }
22750         var cfg = {
22751             in_pre: false,
22752             indentstr : ''
22753         };
22754         this.state.pop();
22755         if (this.state.length > 0) {
22756             cfg = this.state[this.state.length-1]; 
22757         }
22758         Roo.apply(this, cfg);
22759     },
22760     
22761     addLine: function()
22762     {
22763         if (this.html.length < 1) {
22764             return;
22765         }
22766         
22767         
22768         var value = this.html[this.html.length - 1];
22769         if (value.length > 0 && '\n' !== value) {
22770             this.html.push('\n');
22771         }
22772     }
22773     
22774     
22775 //'pre script noscript style textarea video audio iframe object code'
22776 // shortended... 'area base basefont br col frame hr img input isindex link  meta param embed source wbr track');
22777 // inline 
22778 };
22779
22780 Roo.htmleditor.TidyWriter.inline_elements = [
22781         'SPAN','STRONG','B','EM','I','FONT','STRIKE','U','VAR',
22782         'CITE','DFN','CODE','MARK','Q','SUP','SUB','SAMP', 'A'
22783 ];
22784 Roo.htmleditor.TidyWriter.shortend_elements = [
22785     'AREA','BASE','BASEFONT','BR','COL','FRAME','HR','IMG','INPUT',
22786     'ISINDEX','LINK','','META','PARAM','EMBED','SOURCE','WBR','TRACK'
22787 ];
22788
22789 Roo.htmleditor.TidyWriter.whitespace_elements = [
22790     'PRE','SCRIPT','NOSCRIPT','STYLE','TEXTAREA','VIDEO','AUDIO','IFRAME','OBJECT','CODE'
22791 ];/***
22792  * This is based loosely on tinymce 
22793  * @class Roo.htmleditor.TidyEntities
22794  * @static
22795  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
22796  *
22797  * Not 100% sure this is actually used or needed.
22798  */
22799
22800 Roo.htmleditor.TidyEntities = {
22801     
22802     /**
22803      * initialize data..
22804      */
22805     init : function (){
22806      
22807         this.namedEntities = this.buildEntitiesLookup(this.namedEntitiesData, 32);
22808        
22809     },
22810
22811
22812     buildEntitiesLookup: function(items, radix) {
22813         var i, chr, entity, lookup = {};
22814         if (!items) {
22815             return {};
22816         }
22817         items = typeof(items) == 'string' ? items.split(',') : items;
22818         radix = radix || 10;
22819         // Build entities lookup table
22820         for (i = 0; i < items.length; i += 2) {
22821             chr = String.fromCharCode(parseInt(items[i], radix));
22822             // Only add non base entities
22823             if (!this.baseEntities[chr]) {
22824                 entity = '&' + items[i + 1] + ';';
22825                 lookup[chr] = entity;
22826                 lookup[entity] = chr;
22827             }
22828         }
22829         return lookup;
22830         
22831     },
22832     
22833     asciiMap : {
22834             128: '€',
22835             130: '‚',
22836             131: 'ƒ',
22837             132: '„',
22838             133: '…',
22839             134: '†',
22840             135: '‡',
22841             136: 'ˆ',
22842             137: '‰',
22843             138: 'Š',
22844             139: '‹',
22845             140: 'Œ',
22846             142: 'Ž',
22847             145: '‘',
22848             146: '’',
22849             147: '“',
22850             148: '”',
22851             149: '•',
22852             150: '–',
22853             151: '—',
22854             152: '˜',
22855             153: '™',
22856             154: 'š',
22857             155: '›',
22858             156: 'œ',
22859             158: 'ž',
22860             159: 'Ÿ'
22861     },
22862     // Raw entities
22863     baseEntities : {
22864         '"': '&quot;',
22865         // Needs to be escaped since the YUI compressor would otherwise break the code
22866         '\'': '&#39;',
22867         '<': '&lt;',
22868         '>': '&gt;',
22869         '&': '&amp;',
22870         '`': '&#96;'
22871     },
22872     // Reverse lookup table for raw entities
22873     reverseEntities : {
22874         '&lt;': '<',
22875         '&gt;': '>',
22876         '&amp;': '&',
22877         '&quot;': '"',
22878         '&apos;': '\''
22879     },
22880     
22881     attrsCharsRegExp : /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
22882     textCharsRegExp : /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
22883     rawCharsRegExp : /[<>&\"\']/g,
22884     entityRegExp : /&#([a-z0-9]+);?|&([a-z0-9]+);/gi,
22885     namedEntities  : false,
22886     namedEntitiesData : [ 
22887         '50',
22888         'nbsp',
22889         '51',
22890         'iexcl',
22891         '52',
22892         'cent',
22893         '53',
22894         'pound',
22895         '54',
22896         'curren',
22897         '55',
22898         'yen',
22899         '56',
22900         'brvbar',
22901         '57',
22902         'sect',
22903         '58',
22904         'uml',
22905         '59',
22906         'copy',
22907         '5a',
22908         'ordf',
22909         '5b',
22910         'laquo',
22911         '5c',
22912         'not',
22913         '5d',
22914         'shy',
22915         '5e',
22916         'reg',
22917         '5f',
22918         'macr',
22919         '5g',
22920         'deg',
22921         '5h',
22922         'plusmn',
22923         '5i',
22924         'sup2',
22925         '5j',
22926         'sup3',
22927         '5k',
22928         'acute',
22929         '5l',
22930         'micro',
22931         '5m',
22932         'para',
22933         '5n',
22934         'middot',
22935         '5o',
22936         'cedil',
22937         '5p',
22938         'sup1',
22939         '5q',
22940         'ordm',
22941         '5r',
22942         'raquo',
22943         '5s',
22944         'frac14',
22945         '5t',
22946         'frac12',
22947         '5u',
22948         'frac34',
22949         '5v',
22950         'iquest',
22951         '60',
22952         'Agrave',
22953         '61',
22954         'Aacute',
22955         '62',
22956         'Acirc',
22957         '63',
22958         'Atilde',
22959         '64',
22960         'Auml',
22961         '65',
22962         'Aring',
22963         '66',
22964         'AElig',
22965         '67',
22966         'Ccedil',
22967         '68',
22968         'Egrave',
22969         '69',
22970         'Eacute',
22971         '6a',
22972         'Ecirc',
22973         '6b',
22974         'Euml',
22975         '6c',
22976         'Igrave',
22977         '6d',
22978         'Iacute',
22979         '6e',
22980         'Icirc',
22981         '6f',
22982         'Iuml',
22983         '6g',
22984         'ETH',
22985         '6h',
22986         'Ntilde',
22987         '6i',
22988         'Ograve',
22989         '6j',
22990         'Oacute',
22991         '6k',
22992         'Ocirc',
22993         '6l',
22994         'Otilde',
22995         '6m',
22996         'Ouml',
22997         '6n',
22998         'times',
22999         '6o',
23000         'Oslash',
23001         '6p',
23002         'Ugrave',
23003         '6q',
23004         'Uacute',
23005         '6r',
23006         'Ucirc',
23007         '6s',
23008         'Uuml',
23009         '6t',
23010         'Yacute',
23011         '6u',
23012         'THORN',
23013         '6v',
23014         'szlig',
23015         '70',
23016         'agrave',
23017         '71',
23018         'aacute',
23019         '72',
23020         'acirc',
23021         '73',
23022         'atilde',
23023         '74',
23024         'auml',
23025         '75',
23026         'aring',
23027         '76',
23028         'aelig',
23029         '77',
23030         'ccedil',
23031         '78',
23032         'egrave',
23033         '79',
23034         'eacute',
23035         '7a',
23036         'ecirc',
23037         '7b',
23038         'euml',
23039         '7c',
23040         'igrave',
23041         '7d',
23042         'iacute',
23043         '7e',
23044         'icirc',
23045         '7f',
23046         'iuml',
23047         '7g',
23048         'eth',
23049         '7h',
23050         'ntilde',
23051         '7i',
23052         'ograve',
23053         '7j',
23054         'oacute',
23055         '7k',
23056         'ocirc',
23057         '7l',
23058         'otilde',
23059         '7m',
23060         'ouml',
23061         '7n',
23062         'divide',
23063         '7o',
23064         'oslash',
23065         '7p',
23066         'ugrave',
23067         '7q',
23068         'uacute',
23069         '7r',
23070         'ucirc',
23071         '7s',
23072         'uuml',
23073         '7t',
23074         'yacute',
23075         '7u',
23076         'thorn',
23077         '7v',
23078         'yuml',
23079         'ci',
23080         'fnof',
23081         'sh',
23082         'Alpha',
23083         'si',
23084         'Beta',
23085         'sj',
23086         'Gamma',
23087         'sk',
23088         'Delta',
23089         'sl',
23090         'Epsilon',
23091         'sm',
23092         'Zeta',
23093         'sn',
23094         'Eta',
23095         'so',
23096         'Theta',
23097         'sp',
23098         'Iota',
23099         'sq',
23100         'Kappa',
23101         'sr',
23102         'Lambda',
23103         'ss',
23104         'Mu',
23105         'st',
23106         'Nu',
23107         'su',
23108         'Xi',
23109         'sv',
23110         'Omicron',
23111         't0',
23112         'Pi',
23113         't1',
23114         'Rho',
23115         't3',
23116         'Sigma',
23117         't4',
23118         'Tau',
23119         't5',
23120         'Upsilon',
23121         't6',
23122         'Phi',
23123         't7',
23124         'Chi',
23125         't8',
23126         'Psi',
23127         't9',
23128         'Omega',
23129         'th',
23130         'alpha',
23131         'ti',
23132         'beta',
23133         'tj',
23134         'gamma',
23135         'tk',
23136         'delta',
23137         'tl',
23138         'epsilon',
23139         'tm',
23140         'zeta',
23141         'tn',
23142         'eta',
23143         'to',
23144         'theta',
23145         'tp',
23146         'iota',
23147         'tq',
23148         'kappa',
23149         'tr',
23150         'lambda',
23151         'ts',
23152         'mu',
23153         'tt',
23154         'nu',
23155         'tu',
23156         'xi',
23157         'tv',
23158         'omicron',
23159         'u0',
23160         'pi',
23161         'u1',
23162         'rho',
23163         'u2',
23164         'sigmaf',
23165         'u3',
23166         'sigma',
23167         'u4',
23168         'tau',
23169         'u5',
23170         'upsilon',
23171         'u6',
23172         'phi',
23173         'u7',
23174         'chi',
23175         'u8',
23176         'psi',
23177         'u9',
23178         'omega',
23179         'uh',
23180         'thetasym',
23181         'ui',
23182         'upsih',
23183         'um',
23184         'piv',
23185         '812',
23186         'bull',
23187         '816',
23188         'hellip',
23189         '81i',
23190         'prime',
23191         '81j',
23192         'Prime',
23193         '81u',
23194         'oline',
23195         '824',
23196         'frasl',
23197         '88o',
23198         'weierp',
23199         '88h',
23200         'image',
23201         '88s',
23202         'real',
23203         '892',
23204         'trade',
23205         '89l',
23206         'alefsym',
23207         '8cg',
23208         'larr',
23209         '8ch',
23210         'uarr',
23211         '8ci',
23212         'rarr',
23213         '8cj',
23214         'darr',
23215         '8ck',
23216         'harr',
23217         '8dl',
23218         'crarr',
23219         '8eg',
23220         'lArr',
23221         '8eh',
23222         'uArr',
23223         '8ei',
23224         'rArr',
23225         '8ej',
23226         'dArr',
23227         '8ek',
23228         'hArr',
23229         '8g0',
23230         'forall',
23231         '8g2',
23232         'part',
23233         '8g3',
23234         'exist',
23235         '8g5',
23236         'empty',
23237         '8g7',
23238         'nabla',
23239         '8g8',
23240         'isin',
23241         '8g9',
23242         'notin',
23243         '8gb',
23244         'ni',
23245         '8gf',
23246         'prod',
23247         '8gh',
23248         'sum',
23249         '8gi',
23250         'minus',
23251         '8gn',
23252         'lowast',
23253         '8gq',
23254         'radic',
23255         '8gt',
23256         'prop',
23257         '8gu',
23258         'infin',
23259         '8h0',
23260         'ang',
23261         '8h7',
23262         'and',
23263         '8h8',
23264         'or',
23265         '8h9',
23266         'cap',
23267         '8ha',
23268         'cup',
23269         '8hb',
23270         'int',
23271         '8hk',
23272         'there4',
23273         '8hs',
23274         'sim',
23275         '8i5',
23276         'cong',
23277         '8i8',
23278         'asymp',
23279         '8j0',
23280         'ne',
23281         '8j1',
23282         'equiv',
23283         '8j4',
23284         'le',
23285         '8j5',
23286         'ge',
23287         '8k2',
23288         'sub',
23289         '8k3',
23290         'sup',
23291         '8k4',
23292         'nsub',
23293         '8k6',
23294         'sube',
23295         '8k7',
23296         'supe',
23297         '8kl',
23298         'oplus',
23299         '8kn',
23300         'otimes',
23301         '8l5',
23302         'perp',
23303         '8m5',
23304         'sdot',
23305         '8o8',
23306         'lceil',
23307         '8o9',
23308         'rceil',
23309         '8oa',
23310         'lfloor',
23311         '8ob',
23312         'rfloor',
23313         '8p9',
23314         'lang',
23315         '8pa',
23316         'rang',
23317         '9ea',
23318         'loz',
23319         '9j0',
23320         'spades',
23321         '9j3',
23322         'clubs',
23323         '9j5',
23324         'hearts',
23325         '9j6',
23326         'diams',
23327         'ai',
23328         'OElig',
23329         'aj',
23330         'oelig',
23331         'b0',
23332         'Scaron',
23333         'b1',
23334         'scaron',
23335         'bo',
23336         'Yuml',
23337         'm6',
23338         'circ',
23339         'ms',
23340         'tilde',
23341         '802',
23342         'ensp',
23343         '803',
23344         'emsp',
23345         '809',
23346         'thinsp',
23347         '80c',
23348         'zwnj',
23349         '80d',
23350         'zwj',
23351         '80e',
23352         'lrm',
23353         '80f',
23354         'rlm',
23355         '80j',
23356         'ndash',
23357         '80k',
23358         'mdash',
23359         '80o',
23360         'lsquo',
23361         '80p',
23362         'rsquo',
23363         '80q',
23364         'sbquo',
23365         '80s',
23366         'ldquo',
23367         '80t',
23368         'rdquo',
23369         '80u',
23370         'bdquo',
23371         '810',
23372         'dagger',
23373         '811',
23374         'Dagger',
23375         '81g',
23376         'permil',
23377         '81p',
23378         'lsaquo',
23379         '81q',
23380         'rsaquo',
23381         '85c',
23382         'euro'
23383     ],
23384
23385          
23386     /**
23387      * Encodes the specified string using raw entities. This means only the required XML base entities will be encoded.
23388      *
23389      * @method encodeRaw
23390      * @param {String} text Text to encode.
23391      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
23392      * @return {String} Entity encoded text.
23393      */
23394     encodeRaw: function(text, attr)
23395     {
23396         var t = this;
23397         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
23398             return t.baseEntities[chr] || chr;
23399         });
23400     },
23401     /**
23402      * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents
23403      * since it doesn't know if the context is within a attribute or text node. This was added for compatibility
23404      * and is exposed as the DOMUtils.encode function.
23405      *
23406      * @method encodeAllRaw
23407      * @param {String} text Text to encode.
23408      * @return {String} Entity encoded text.
23409      */
23410     encodeAllRaw: function(text) {
23411         var t = this;
23412         return ('' + text).replace(this.rawCharsRegExp, function(chr) {
23413             return t.baseEntities[chr] || chr;
23414         });
23415     },
23416     /**
23417      * Encodes the specified string using numeric entities. The core entities will be
23418      * encoded as named ones but all non lower ascii characters will be encoded into numeric entities.
23419      *
23420      * @method encodeNumeric
23421      * @param {String} text Text to encode.
23422      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
23423      * @return {String} Entity encoded text.
23424      */
23425     encodeNumeric: function(text, attr) {
23426         var t = this;
23427         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
23428             // Multi byte sequence convert it to a single entity
23429             if (chr.length > 1) {
23430                 return '&#' + (1024 * (chr.charCodeAt(0) - 55296) + (chr.charCodeAt(1) - 56320) + 65536) + ';';
23431             }
23432             return t.baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
23433         });
23434     },
23435     /**
23436      * Encodes the specified string using named entities. The core entities will be encoded
23437      * as named ones but all non lower ascii characters will be encoded into named entities.
23438      *
23439      * @method encodeNamed
23440      * @param {String} text Text to encode.
23441      * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
23442      * @param {Object} entities Optional parameter with entities to use.
23443      * @return {String} Entity encoded text.
23444      */
23445     encodeNamed: function(text, attr, entities) {
23446         var t = this;
23447         entities = entities || this.namedEntities;
23448         return text.replace(attr ? this.attrsCharsRegExp : this.textCharsRegExp, function(chr) {
23449             return t.baseEntities[chr] || entities[chr] || chr;
23450         });
23451     },
23452     /**
23453      * Returns an encode function based on the name(s) and it's optional entities.
23454      *
23455      * @method getEncodeFunc
23456      * @param {String} name Comma separated list of encoders for example named,numeric.
23457      * @param {String} entities Optional parameter with entities to use instead of the built in set.
23458      * @return {function} Encode function to be used.
23459      */
23460     getEncodeFunc: function(name, entities) {
23461         entities = this.buildEntitiesLookup(entities) || this.namedEntities;
23462         var t = this;
23463         function encodeNamedAndNumeric(text, attr) {
23464             return text.replace(attr ? t.attrsCharsRegExp : t.textCharsRegExp, function(chr) {
23465                 return t.baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
23466             });
23467         }
23468
23469         function encodeCustomNamed(text, attr) {
23470             return t.encodeNamed(text, attr, entities);
23471         }
23472         // Replace + with , to be compatible with previous TinyMCE versions
23473         name = this.makeMap(name.replace(/\+/g, ','));
23474         // Named and numeric encoder
23475         if (name.named && name.numeric) {
23476             return this.encodeNamedAndNumeric;
23477         }
23478         // Named encoder
23479         if (name.named) {
23480             // Custom names
23481             if (entities) {
23482                 return encodeCustomNamed;
23483             }
23484             return this.encodeNamed;
23485         }
23486         // Numeric
23487         if (name.numeric) {
23488             return this.encodeNumeric;
23489         }
23490         // Raw encoder
23491         return this.encodeRaw;
23492     },
23493     /**
23494      * Decodes the specified string, this will replace entities with raw UTF characters.
23495      *
23496      * @method decode
23497      * @param {String} text Text to entity decode.
23498      * @return {String} Entity decoded string.
23499      */
23500     decode: function(text)
23501     {
23502         var  t = this;
23503         return text.replace(this.entityRegExp, function(all, numeric) {
23504             if (numeric) {
23505                 numeric = 'x' === numeric.charAt(0).toLowerCase() ? parseInt(numeric.substr(1), 16) : parseInt(numeric, 10);
23506                 // Support upper UTF
23507                 if (numeric > 65535) {
23508                     numeric -= 65536;
23509                     return String.fromCharCode(55296 + (numeric >> 10), 56320 + (1023 & numeric));
23510                 }
23511                 return t.asciiMap[numeric] || String.fromCharCode(numeric);
23512             }
23513             return t.reverseEntities[all] || t.namedEntities[all] || t.nativeDecode(all);
23514         });
23515     },
23516     nativeDecode : function (text) {
23517         return text;
23518     },
23519     makeMap : function (items, delim, map) {
23520                 var i;
23521                 items = items || [];
23522                 delim = delim || ',';
23523                 if (typeof items == "string") {
23524                         items = items.split(delim);
23525                 }
23526                 map = map || {};
23527                 i = items.length;
23528                 while (i--) {
23529                         map[items[i]] = {};
23530                 }
23531                 return map;
23532         }
23533 };
23534     
23535     
23536     
23537 Roo.htmleditor.TidyEntities.init();
23538 /**
23539  * @class Roo.htmleditor.KeyEnter
23540  * Handle Enter press..
23541  * @cfg {Roo.HtmlEditorCore} core the editor.
23542  * @constructor
23543  * Create a new Filter.
23544  * @param {Object} config Configuration options
23545  */
23546
23547
23548
23549
23550
23551 Roo.htmleditor.KeyEnter = function(cfg) {
23552     Roo.apply(this, cfg);
23553     // this does not actually call walk as it's really just a abstract class
23554  
23555     Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
23556 }
23557
23558 //Roo.htmleditor.KeyEnter.i = 0;
23559
23560
23561 Roo.htmleditor.KeyEnter.prototype = {
23562     
23563     core : false,
23564     
23565     keypress : function(e)
23566     {
23567         if (e.charCode != 13 && e.charCode != 10) {
23568             Roo.log([e.charCode,e]);
23569             return true;
23570         }
23571         e.preventDefault();
23572         // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
23573         var doc = this.core.doc;
23574           //add a new line
23575        
23576     
23577         var sel = this.core.getSelection();
23578         var range = sel.getRangeAt(0);
23579         var n = range.commonAncestorContainer;
23580         var pc = range.closest([ 'ol', 'ul']);
23581         var pli = range.closest('li');
23582         if (!pc || e.ctrlKey) {
23583             // on it list, or ctrl pressed.
23584             if (!e.ctrlKey) {
23585                 sel.insertNode('br', 'after'); 
23586             } else {
23587                 // only do this if we have ctrl key..
23588                 var br = doc.createElement('br');
23589                 br.className = 'clear';
23590                 br.setAttribute('style', 'clear: both');
23591                 sel.insertNode(br, 'after'); 
23592             }
23593             
23594          
23595             this.core.undoManager.addEvent();
23596             this.core.fireEditorEvent(e);
23597             return false;
23598         }
23599         
23600         // deal with <li> insetion
23601         if (pli.innerText.trim() == '' &&
23602             pli.previousSibling &&
23603             pli.previousSibling.nodeName == 'LI' &&
23604             pli.previousSibling.innerText.trim() ==  '') {
23605             pli.parentNode.removeChild(pli.previousSibling);
23606             sel.cursorAfter(pc);
23607             this.core.undoManager.addEvent();
23608             this.core.fireEditorEvent(e);
23609             return false;
23610         }
23611     
23612         var li = doc.createElement('LI');
23613         li.innerHTML = '&nbsp;';
23614         if (!pli || !pli.firstSibling) {
23615             pc.appendChild(li);
23616         } else {
23617             pli.parentNode.insertBefore(li, pli.firstSibling);
23618         }
23619         sel.cursorText (li.firstChild);
23620       
23621         this.core.undoManager.addEvent();
23622         this.core.fireEditorEvent(e);
23623
23624         return false;
23625         
23626     
23627         
23628         
23629          
23630     }
23631 };
23632      
23633 /**
23634  * @class Roo.htmleditor.Block
23635  * Base class for html editor blocks - do not use it directly .. extend it..
23636  * @cfg {DomElement} node The node to apply stuff to.
23637  * @cfg {String} friendly_name the name that appears in the context bar about this block
23638  * @cfg {Object} Context menu - see Roo.form.HtmlEditor.ToolbarContext
23639  
23640  * @constructor
23641  * Create a new Filter.
23642  * @param {Object} config Configuration options
23643  */
23644
23645 Roo.htmleditor.Block  = function(cfg)
23646 {
23647     // do nothing .. should not be called really.
23648 }
23649 /**
23650  * factory method to get the block from an element (using cache if necessary)
23651  * @static
23652  * @param {HtmlElement} the dom element
23653  */
23654 Roo.htmleditor.Block.factory = function(node)
23655 {
23656     var cc = Roo.htmleditor.Block.cache;
23657     var id = Roo.get(node).id;
23658     if (typeof(cc[id]) != 'undefined' && (!cc[id].node || cc[id].node.closest('body'))) {
23659         Roo.htmleditor.Block.cache[id].readElement(node);
23660         return Roo.htmleditor.Block.cache[id];
23661     }
23662     var db  = node.getAttribute('data-block');
23663     if (!db) {
23664         db = node.nodeName.toLowerCase().toUpperCaseFirst();
23665     }
23666     var cls = Roo.htmleditor['Block' + db];
23667     if (typeof(cls) == 'undefined') {
23668         //Roo.log(node.getAttribute('data-block'));
23669         Roo.log("OOps missing block : " + 'Block' + db);
23670         return false;
23671     }
23672     Roo.htmleditor.Block.cache[id] = new cls({ node: node });
23673     return Roo.htmleditor.Block.cache[id];  /// should trigger update element
23674 };
23675
23676 /**
23677  * initalize all Elements from content that are 'blockable'
23678  * @static
23679  * @param the body element
23680  */
23681 Roo.htmleditor.Block.initAll = function(body, type)
23682 {
23683     if (typeof(type) == 'undefined') {
23684         var ia = Roo.htmleditor.Block.initAll;
23685         ia(body,'table');
23686         ia(body,'td');
23687         ia(body,'figure');
23688         return;
23689     }
23690     Roo.each(Roo.get(body).query(type), function(e) {
23691         Roo.htmleditor.Block.factory(e);    
23692     },this);
23693 };
23694 // question goes here... do we need to clear out this cache sometimes?
23695 // or show we make it relivant to the htmleditor.
23696 Roo.htmleditor.Block.cache = {};
23697
23698 Roo.htmleditor.Block.prototype = {
23699     
23700     node : false,
23701     
23702      // used by context menu
23703     friendly_name : 'Based Block',
23704     
23705     // text for button to delete this element
23706     deleteTitle : false,
23707     
23708     context : false,
23709     /**
23710      * Update a node with values from this object
23711      * @param {DomElement} node
23712      */
23713     updateElement : function(node)
23714     {
23715         Roo.DomHelper.update(node === undefined ? this.node : node, this.toObject());
23716     },
23717      /**
23718      * convert to plain HTML for calling insertAtCursor..
23719      */
23720     toHTML : function()
23721     {
23722         return Roo.DomHelper.markup(this.toObject());
23723     },
23724     /**
23725      * used by readEleemnt to extract data from a node
23726      * may need improving as it's pretty basic
23727      
23728      * @param {DomElement} node
23729      * @param {String} tag - tag to find, eg. IMG ?? might be better to use DomQuery ?
23730      * @param {String} attribute (use html - for contents, style for using next param as style, or false to return the node)
23731      * @param {String} style the style property - eg. text-align
23732      */
23733     getVal : function(node, tag, attr, style)
23734     {
23735         var n = node;
23736         if (tag !== true && n.tagName != tag.toUpperCase()) {
23737             // in theory we could do figure[3] << 3rd figure? or some more complex search..?
23738             // but kiss for now.
23739             n = node.getElementsByTagName(tag).item(0);
23740         }
23741         if (!n) {
23742             return '';
23743         }
23744         if (attr === false) {
23745             return n;
23746         }
23747         if (attr == 'html') {
23748             return n.innerHTML;
23749         }
23750         if (attr == 'style') {
23751             return n.style[style]; 
23752         }
23753         
23754         return n.hasAttribute(attr) ? n.getAttribute(attr) : '';
23755             
23756     },
23757     /**
23758      * create a DomHelper friendly object - for use with 
23759      * Roo.DomHelper.markup / overwrite / etc..
23760      * (override this)
23761      */
23762     toObject : function()
23763     {
23764         return {};
23765     },
23766       /**
23767      * Read a node that has a 'data-block' property - and extract the values from it.
23768      * @param {DomElement} node - the node
23769      */
23770     readElement : function(node)
23771     {
23772         
23773     } 
23774     
23775     
23776 };
23777
23778  
23779
23780 /**
23781  * @class Roo.htmleditor.BlockFigure
23782  * Block that has an image and a figcaption
23783  * @cfg {String} image_src the url for the image
23784  * @cfg {String} align (left|right) alignment for the block default left
23785  * @cfg {String} caption the text to appear below  (and in the alt tag)
23786  * @cfg {String} caption_display (block|none) display or not the caption
23787  * @cfg {String|number} image_width the width of the image number or %?
23788  * @cfg {String|number} image_height the height of the image number or %?
23789  * 
23790  * @constructor
23791  * Create a new Filter.
23792  * @param {Object} config Configuration options
23793  */
23794
23795 Roo.htmleditor.BlockFigure = function(cfg)
23796 {
23797     if (cfg.node) {
23798         this.readElement(cfg.node);
23799         this.updateElement(cfg.node);
23800     }
23801     Roo.apply(this, cfg);
23802 }
23803 Roo.extend(Roo.htmleditor.BlockFigure, Roo.htmleditor.Block, {
23804  
23805     
23806     // setable values.
23807     image_src: '',
23808     align: 'center',
23809     caption : '',
23810     caption_display : 'block',
23811     width : '100%',
23812     cls : '',
23813     href: '',
23814     video_url : '',
23815     
23816     // margin: '2%', not used
23817     
23818     text_align: 'left', //   (left|right) alignment for the text caption default left. - not used at present
23819
23820     
23821     // used by context menu
23822     friendly_name : 'Image with caption',
23823     deleteTitle : "Delete Image and Caption",
23824     
23825     contextMenu : function(toolbar)
23826     {
23827         
23828         var block = function() {
23829             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
23830         };
23831         
23832         
23833         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
23834         
23835         var syncValue = toolbar.editorcore.syncValue;
23836         
23837         var fields = {};
23838         
23839         return [
23840              {
23841                 xtype : 'TextItem',
23842                 text : "Source: ",
23843                 xns : rooui.Toolbar  //Boostrap?
23844             },
23845             {
23846                 xtype : 'Button',
23847                 text: 'Change Image URL',
23848                  
23849                 listeners : {
23850                     click: function (btn, state)
23851                     {
23852                         var b = block();
23853                         
23854                         Roo.MessageBox.show({
23855                             title : "Image Source URL",
23856                             msg : "Enter the url for the image",
23857                             buttons: Roo.MessageBox.OKCANCEL,
23858                             fn: function(btn, val){
23859                                 if (btn != 'ok') {
23860                                     return;
23861                                 }
23862                                 b.image_src = val;
23863                                 b.updateElement();
23864                                 syncValue();
23865                                 toolbar.editorcore.onEditorEvent();
23866                             },
23867                             minWidth:250,
23868                             prompt:true,
23869                             //multiline: multiline,
23870                             modal : true,
23871                             value : b.image_src
23872                         });
23873                     }
23874                 },
23875                 xns : rooui.Toolbar
23876             },
23877          
23878             {
23879                 xtype : 'Button',
23880                 text: 'Change Link URL',
23881                  
23882                 listeners : {
23883                     click: function (btn, state)
23884                     {
23885                         var b = block();
23886                         
23887                         Roo.MessageBox.show({
23888                             title : "Link URL",
23889                             msg : "Enter the url for the link - leave blank to have no link",
23890                             buttons: Roo.MessageBox.OKCANCEL,
23891                             fn: function(btn, val){
23892                                 if (btn != 'ok') {
23893                                     return;
23894                                 }
23895                                 b.href = val;
23896                                 b.updateElement();
23897                                 syncValue();
23898                                 toolbar.editorcore.onEditorEvent();
23899                             },
23900                             minWidth:250,
23901                             prompt:true,
23902                             //multiline: multiline,
23903                             modal : true,
23904                             value : b.href
23905                         });
23906                     }
23907                 },
23908                 xns : rooui.Toolbar
23909             },
23910             {
23911                 xtype : 'Button',
23912                 text: 'Show Video URL',
23913                  
23914                 listeners : {
23915                     click: function (btn, state)
23916                     {
23917                         Roo.MessageBox.alert("Video URL",
23918                             block().video_url == '' ? 'This image is not linked ot a video' :
23919                                 'The image is linked to: <a target="_new" href="' + block().video_url + '">' + block().video_url + '</a>');
23920                     }
23921                 },
23922                 xns : rooui.Toolbar
23923             },
23924             
23925             
23926             {
23927                 xtype : 'TextItem',
23928                 text : "Width: ",
23929                 xns : rooui.Toolbar  //Boostrap?
23930             },
23931             {
23932                 xtype : 'ComboBox',
23933                 allowBlank : false,
23934                 displayField : 'val',
23935                 editable : true,
23936                 listWidth : 100,
23937                 triggerAction : 'all',
23938                 typeAhead : true,
23939                 valueField : 'val',
23940                 width : 70,
23941                 name : 'width',
23942                 listeners : {
23943                     select : function (combo, r, index)
23944                     {
23945                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
23946                         var b = block();
23947                         b.width = r.get('val');
23948                         b.updateElement();
23949                         syncValue();
23950                         toolbar.editorcore.onEditorEvent();
23951                     }
23952                 },
23953                 xns : rooui.form,
23954                 store : {
23955                     xtype : 'SimpleStore',
23956                     data : [
23957                         ['100%'],
23958                         ['80%'],
23959                         ['50%'],
23960                         ['20%'],
23961                         ['10%']
23962                     ],
23963                     fields : [ 'val'],
23964                     xns : Roo.data
23965                 }
23966             },
23967             {
23968                 xtype : 'TextItem',
23969                 text : "Align: ",
23970                 xns : rooui.Toolbar  //Boostrap?
23971             },
23972             {
23973                 xtype : 'ComboBox',
23974                 allowBlank : false,
23975                 displayField : 'val',
23976                 editable : true,
23977                 listWidth : 100,
23978                 triggerAction : 'all',
23979                 typeAhead : true,
23980                 valueField : 'val',
23981                 width : 70,
23982                 name : 'align',
23983                 listeners : {
23984                     select : function (combo, r, index)
23985                     {
23986                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
23987                         var b = block();
23988                         b.align = r.get('val');
23989                         b.updateElement();
23990                         syncValue();
23991                         toolbar.editorcore.onEditorEvent();
23992                     }
23993                 },
23994                 xns : rooui.form,
23995                 store : {
23996                     xtype : 'SimpleStore',
23997                     data : [
23998                         ['left'],
23999                         ['right'],
24000                         ['center']
24001                     ],
24002                     fields : [ 'val'],
24003                     xns : Roo.data
24004                 }
24005             },
24006             
24007               
24008             {
24009                 xtype : 'Button',
24010                 text: 'Hide Caption',
24011                 name : 'caption_display',
24012                 pressed : false,
24013                 enableToggle : true,
24014                 setValue : function(v) {
24015                     // this trigger toggle.
24016                      
24017                     this.setText(v ? "Hide Caption" : "Show Caption");
24018                     this.setPressed(v != 'block');
24019                 },
24020                 listeners : {
24021                     toggle: function (btn, state)
24022                     {
24023                         var b  = block();
24024                         b.caption_display = b.caption_display == 'block' ? 'none' : 'block';
24025                         this.setText(b.caption_display == 'block' ? "Hide Caption" : "Show Caption");
24026                         b.updateElement();
24027                         syncValue();
24028                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24029                         toolbar.editorcore.onEditorEvent();
24030                     }
24031                 },
24032                 xns : rooui.Toolbar
24033             }
24034         ];
24035         
24036     },
24037     /**
24038      * create a DomHelper friendly object - for use with
24039      * Roo.DomHelper.markup / overwrite / etc..
24040      */
24041     toObject : function()
24042     {
24043         var d = document.createElement('div');
24044         d.innerHTML = this.caption;
24045         
24046         var m = this.width != '100%' && this.align == 'center' ? '0 auto' : 0; 
24047         
24048         var iw = this.align == 'center' ? this.width : '100%';
24049         var img =   {
24050             tag : 'img',
24051             contenteditable : 'false',
24052             src : this.image_src,
24053             alt : d.innerText.replace(/\n/g, " ").replace(/\s+/g, ' ').trim(), // removeHTML and reduce spaces..
24054             style: {
24055                 width : iw,
24056                 maxWidth : iw + ' !important', // this is not getting rendered?
24057                 margin : m  
24058                 
24059             }
24060         };
24061         /*
24062         '<div class="{0}" width="420" height="315" src="{1}" frameborder="0" allowfullscreen>' +
24063                     '<a href="{2}">' + 
24064                         '<img class="{0}-thumbnail" src="{3}/Images/{4}/{5}#image-{4}" />' + 
24065                     '</a>' + 
24066                 '</div>',
24067         */
24068                 
24069         if (this.href.length > 0) {
24070             img = {
24071                 tag : 'a',
24072                 href: this.href,
24073                 contenteditable : 'true',
24074                 cn : [
24075                     img
24076                 ]
24077             };
24078         }
24079         
24080         
24081         if (this.video_url.length > 0) {
24082             img = {
24083                 tag : 'div',
24084                 cls : this.cls,
24085                 frameborder : 0,
24086                 allowfullscreen : true,
24087                 width : 420,  // these are for video tricks - that we replace the outer
24088                 height : 315,
24089                 src : this.video_url,
24090                 cn : [
24091                     img
24092                 ]
24093             };
24094         }
24095
24096
24097   
24098         var ret =   {
24099             tag: 'figure',
24100             'data-block' : 'Figure',
24101             'data-width' : this.width,
24102             'data-caption' : this.caption, 
24103             'data-caption-display' : this.caption_display,
24104             contenteditable : 'false',
24105             
24106             style : {
24107                 display: 'block',
24108                 float :  this.align ,
24109                 maxWidth :  this.align == 'center' ? '100% !important' : (this.width + ' !important'),
24110                 width : this.align == 'center' ? '100%' : this.width,
24111                 margin:  '0px',
24112                 padding: this.align == 'center' ? '0' : '0 10px' ,
24113                 textAlign : this.align   // seems to work for email..
24114                 
24115             },
24116             
24117             align : this.align,
24118             cn : [
24119                 img
24120             ]
24121         };
24122
24123         // show figcaption only if caption_display is 'block'
24124         if(this.caption_display == 'block') {
24125             ret['cn'].push({
24126                 tag: 'figcaption',
24127                 style : {
24128                     textAlign : 'left',
24129                     fontSize : '16px',
24130                     lineHeight : '24px',
24131                     display : this.caption_display,
24132                     maxWidth : (this.align == 'center' ?  this.width : '100%' ) + ' !important',
24133                     margin: m,
24134                     width: this.align == 'center' ?  this.width : '100%' 
24135                 
24136                      
24137                 },
24138                 cls : this.cls.length > 0 ? (this.cls  + '-thumbnail' ) : '',
24139                 cn : [
24140                     {
24141                         tag: 'div',
24142                         style  : {
24143                             marginTop : '16px',
24144                             textAlign : 'start'
24145                         },
24146                         align: 'left',
24147                         cn : [
24148                             {
24149                                 // we can not rely on yahoo syndication to use CSS elements - so have to use  '<i>' to encase stuff.
24150                                 tag : 'i',
24151                                 contenteditable : Roo.htmleditor.BlockFigure.caption_edit,
24152                                 html : this.caption.length ? this.caption : "Caption" // fake caption
24153                             }
24154                             
24155                         ]
24156                     }
24157                     
24158                 ]
24159                 
24160             });
24161         }
24162         return ret;
24163          
24164     },
24165     
24166     readElement : function(node)
24167     {
24168         // this should not really come from the link...
24169         this.video_url = this.getVal(node, 'div', 'src');
24170         this.cls = this.getVal(node, 'div', 'class');
24171         this.href = this.getVal(node, 'a', 'href');
24172         
24173         
24174         this.image_src = this.getVal(node, 'img', 'src');
24175          
24176         this.align = this.getVal(node, 'figure', 'align');
24177
24178         // caption display is stored in figure
24179         this.caption_display = this.getVal(node, true, 'data-caption-display');
24180
24181         // backward compatible
24182         // it was stored in figcaption
24183         if(this.caption_display == '') {
24184             this.caption_display = this.getVal(node, 'figcaption', 'data-display');
24185         }
24186
24187         // read caption from figcaption
24188         var figcaption = this.getVal(node, 'figcaption', false);
24189
24190         if (figcaption !== '') {
24191             this.caption = this.getVal(figcaption, 'i', 'html');
24192         }
24193                 
24194
24195         // read caption from data-caption in figure if no caption from figcaption
24196         var dc = this.getVal(node, true, 'data-caption');
24197
24198         if(this.caption_display == 'none' && dc && dc.length){
24199             this.caption = dc;
24200         }
24201
24202         //this.text_align = this.getVal(node, 'figcaption', 'style','text-align');
24203         this.width = this.getVal(node, true, 'data-width');
24204         //this.margin = this.getVal(node, 'figure', 'style', 'margin');
24205         
24206     },
24207     removeNode : function()
24208     {
24209         return this.node;
24210     }
24211     
24212   
24213    
24214      
24215     
24216     
24217     
24218     
24219 });
24220
24221 Roo.apply(Roo.htmleditor.BlockFigure, {
24222     caption_edit : true
24223 });
24224
24225  
24226
24227 /**
24228  * @class Roo.htmleditor.BlockTable
24229  * Block that manages a table
24230  * 
24231  * @constructor
24232  * Create a new Filter.
24233  * @param {Object} config Configuration options
24234  */
24235
24236 Roo.htmleditor.BlockTable = function(cfg)
24237 {
24238     if (cfg.node) {
24239         this.readElement(cfg.node);
24240         this.updateElement(cfg.node);
24241     }
24242     Roo.apply(this, cfg);
24243     if (!cfg.node) {
24244         this.rows = [];
24245         for(var r = 0; r < this.no_row; r++) {
24246             this.rows[r] = [];
24247             for(var c = 0; c < this.no_col; c++) {
24248                 this.rows[r][c] = this.emptyCell();
24249             }
24250         }
24251     }
24252     
24253     
24254 }
24255 Roo.extend(Roo.htmleditor.BlockTable, Roo.htmleditor.Block, {
24256  
24257     rows : false,
24258     no_col : 1,
24259     no_row : 1,
24260     
24261     
24262     width: '100%',
24263     
24264     // used by context menu
24265     friendly_name : 'Table',
24266     deleteTitle : 'Delete Table',
24267     // context menu is drawn once..
24268     
24269     contextMenu : function(toolbar)
24270     {
24271         
24272         var block = function() {
24273             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
24274         };
24275         
24276         
24277         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
24278         
24279         var syncValue = toolbar.editorcore.syncValue;
24280         
24281         var fields = {};
24282         
24283         return [
24284             {
24285                 xtype : 'TextItem',
24286                 text : "Width: ",
24287                 xns : rooui.Toolbar  //Boostrap?
24288             },
24289             {
24290                 xtype : 'ComboBox',
24291                 allowBlank : false,
24292                 displayField : 'val',
24293                 editable : true,
24294                 listWidth : 100,
24295                 triggerAction : 'all',
24296                 typeAhead : true,
24297                 valueField : 'val',
24298                 width : 100,
24299                 name : 'width',
24300                 listeners : {
24301                     select : function (combo, r, index)
24302                     {
24303                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24304                         var b = block();
24305                         b.width = r.get('val');
24306                         b.updateElement();
24307                         syncValue();
24308                         toolbar.editorcore.onEditorEvent();
24309                     }
24310                 },
24311                 xns : rooui.form,
24312                 store : {
24313                     xtype : 'SimpleStore',
24314                     data : [
24315                         ['100%'],
24316                         ['auto']
24317                     ],
24318                     fields : [ 'val'],
24319                     xns : Roo.data
24320                 }
24321             },
24322             // -------- Cols
24323             
24324             {
24325                 xtype : 'TextItem',
24326                 text : "Columns: ",
24327                 xns : rooui.Toolbar  //Boostrap?
24328             },
24329          
24330             {
24331                 xtype : 'Button',
24332                 text: '-',
24333                 listeners : {
24334                     click : function (_self, e)
24335                     {
24336                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24337                         block().removeColumn();
24338                         syncValue();
24339                         toolbar.editorcore.onEditorEvent();
24340                     }
24341                 },
24342                 xns : rooui.Toolbar
24343             },
24344             {
24345                 xtype : 'Button',
24346                 text: '+',
24347                 listeners : {
24348                     click : function (_self, e)
24349                     {
24350                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24351                         block().addColumn();
24352                         syncValue();
24353                         toolbar.editorcore.onEditorEvent();
24354                     }
24355                 },
24356                 xns : rooui.Toolbar
24357             },
24358             // -------- ROWS
24359             {
24360                 xtype : 'TextItem',
24361                 text : "Rows: ",
24362                 xns : rooui.Toolbar  //Boostrap?
24363             },
24364          
24365             {
24366                 xtype : 'Button',
24367                 text: '-',
24368                 listeners : {
24369                     click : function (_self, e)
24370                     {
24371                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24372                         block().removeRow();
24373                         syncValue();
24374                         toolbar.editorcore.onEditorEvent();
24375                     }
24376                 },
24377                 xns : rooui.Toolbar
24378             },
24379             {
24380                 xtype : 'Button',
24381                 text: '+',
24382                 listeners : {
24383                     click : function (_self, e)
24384                     {
24385                         block().addRow();
24386                         syncValue();
24387                         toolbar.editorcore.onEditorEvent();
24388                     }
24389                 },
24390                 xns : rooui.Toolbar
24391             },
24392             // -------- ROWS
24393             {
24394                 xtype : 'Button',
24395                 text: 'Reset Column Widths',
24396                 listeners : {
24397                     
24398                     click : function (_self, e)
24399                     {
24400                         block().resetWidths();
24401                         syncValue();
24402                         toolbar.editorcore.onEditorEvent();
24403                     }
24404                 },
24405                 xns : rooui.Toolbar
24406             } 
24407             
24408             
24409             
24410         ];
24411         
24412     },
24413     
24414     
24415   /**
24416      * create a DomHelper friendly object - for use with
24417      * Roo.DomHelper.markup / overwrite / etc..
24418      * ?? should it be called with option to hide all editing features?
24419      */
24420     toObject : function()
24421     {
24422         
24423         var ret = {
24424             tag : 'table',
24425             contenteditable : 'false', // this stops cell selection from picking the table.
24426             'data-block' : 'Table',
24427             style : {
24428                 width:  this.width,
24429                 border : 'solid 1px #000', // ??? hard coded?
24430                 'border-collapse' : 'collapse' 
24431             },
24432             cn : [
24433                 { tag : 'tbody' , cn : [] }
24434             ]
24435         };
24436         
24437         // do we have a head = not really 
24438         var ncols = 0;
24439         Roo.each(this.rows, function( row ) {
24440             var tr = {
24441                 tag: 'tr',
24442                 style : {
24443                     margin: '6px',
24444                     border : 'solid 1px #000',
24445                     textAlign : 'left' 
24446                 },
24447                 cn : [ ]
24448             };
24449             
24450             ret.cn[0].cn.push(tr);
24451             // does the row have any properties? ?? height?
24452             var nc = 0;
24453             Roo.each(row, function( cell ) {
24454                 
24455                 var td = {
24456                     tag : 'td',
24457                     contenteditable :  'true',
24458                     'data-block' : 'Td',
24459                     html : cell.html,
24460                     style : cell.style
24461                 };
24462                 if (cell.colspan > 1) {
24463                     td.colspan = cell.colspan ;
24464                     nc += cell.colspan;
24465                 } else {
24466                     nc++;
24467                 }
24468                 if (cell.rowspan > 1) {
24469                     td.rowspan = cell.rowspan ;
24470                 }
24471                 
24472                 
24473                 // widths ?
24474                 tr.cn.push(td);
24475                     
24476                 
24477             }, this);
24478             ncols = Math.max(nc, ncols);
24479             
24480             
24481         }, this);
24482         // add the header row..
24483         
24484         ncols++;
24485          
24486         
24487         return ret;
24488          
24489     },
24490     
24491     readElement : function(node)
24492     {
24493         node  = node ? node : this.node ;
24494         this.width = this.getVal(node, true, 'style', 'width') || '100%';
24495         
24496         this.rows = [];
24497         this.no_row = 0;
24498         var trs = Array.from(node.rows);
24499         trs.forEach(function(tr) {
24500             var row =  [];
24501             this.rows.push(row);
24502             
24503             this.no_row++;
24504             var no_column = 0;
24505             Array.from(tr.cells).forEach(function(td) {
24506                 
24507                 var add = {
24508                     colspan : td.hasAttribute('colspan') ? td.getAttribute('colspan')*1 : 1,
24509                     rowspan : td.hasAttribute('rowspan') ? td.getAttribute('rowspan')*1 : 1,
24510                     style : td.hasAttribute('style') ? td.getAttribute('style') : '',
24511                     html : td.innerHTML
24512                 };
24513                 no_column += add.colspan;
24514                      
24515                 
24516                 row.push(add);
24517                 
24518                 
24519             },this);
24520             this.no_col = Math.max(this.no_col, no_column);
24521             
24522             
24523         },this);
24524         
24525         
24526     },
24527     normalizeRows: function()
24528     {
24529         var ret= [];
24530         var rid = -1;
24531         this.rows.forEach(function(row) {
24532             rid++;
24533             ret[rid] = [];
24534             row = this.normalizeRow(row);
24535             var cid = 0;
24536             row.forEach(function(c) {
24537                 while (typeof(ret[rid][cid]) != 'undefined') {
24538                     cid++;
24539                 }
24540                 if (typeof(ret[rid]) == 'undefined') {
24541                     ret[rid] = [];
24542                 }
24543                 ret[rid][cid] = c;
24544                 c.row = rid;
24545                 c.col = cid;
24546                 if (c.rowspan < 2) {
24547                     return;
24548                 }
24549                 
24550                 for(var i = 1 ;i < c.rowspan; i++) {
24551                     if (typeof(ret[rid+i]) == 'undefined') {
24552                         ret[rid+i] = [];
24553                     }
24554                     ret[rid+i][cid] = c;
24555                 }
24556             });
24557         }, this);
24558         return ret;
24559     
24560     },
24561     
24562     normalizeRow: function(row)
24563     {
24564         var ret= [];
24565         row.forEach(function(c) {
24566             if (c.colspan < 2) {
24567                 ret.push(c);
24568                 return;
24569             }
24570             for(var i =0 ;i < c.colspan; i++) {
24571                 ret.push(c);
24572             }
24573         });
24574         return ret;
24575     
24576     },
24577     
24578     deleteColumn : function(sel)
24579     {
24580         if (!sel || sel.type != 'col') {
24581             return;
24582         }
24583         if (this.no_col < 2) {
24584             return;
24585         }
24586         
24587         this.rows.forEach(function(row) {
24588             var cols = this.normalizeRow(row);
24589             var col = cols[sel.col];
24590             if (col.colspan > 1) {
24591                 col.colspan --;
24592             } else {
24593                 row.remove(col);
24594             }
24595             
24596         }, this);
24597         this.no_col--;
24598         
24599     },
24600     removeColumn : function()
24601     {
24602         this.deleteColumn({
24603             type: 'col',
24604             col : this.no_col-1
24605         });
24606         this.updateElement();
24607     },
24608     
24609      
24610     addColumn : function()
24611     {
24612         
24613         this.rows.forEach(function(row) {
24614             row.push(this.emptyCell());
24615            
24616         }, this);
24617         this.updateElement();
24618     },
24619     
24620     deleteRow : function(sel)
24621     {
24622         if (!sel || sel.type != 'row') {
24623             return;
24624         }
24625         
24626         if (this.no_row < 2) {
24627             return;
24628         }
24629         
24630         var rows = this.normalizeRows();
24631         
24632         
24633         rows[sel.row].forEach(function(col) {
24634             if (col.rowspan > 1) {
24635                 col.rowspan--;
24636             } else {
24637                 col.remove = 1; // flage it as removed.
24638             }
24639             
24640         }, this);
24641         var newrows = [];
24642         this.rows.forEach(function(row) {
24643             newrow = [];
24644             row.forEach(function(c) {
24645                 if (typeof(c.remove) == 'undefined') {
24646                     newrow.push(c);
24647                 }
24648                 
24649             });
24650             if (newrow.length > 0) {
24651                 newrows.push(row);
24652             }
24653         });
24654         this.rows =  newrows;
24655         
24656         
24657         
24658         this.no_row--;
24659         this.updateElement();
24660         
24661     },
24662     removeRow : function()
24663     {
24664         this.deleteRow({
24665             type: 'row',
24666             row : this.no_row-1
24667         });
24668         
24669     },
24670     
24671      
24672     addRow : function()
24673     {
24674         
24675         var row = [];
24676         for (var i = 0; i < this.no_col; i++ ) {
24677             
24678             row.push(this.emptyCell());
24679            
24680         }
24681         this.rows.push(row);
24682         this.updateElement();
24683         
24684     },
24685      
24686     // the default cell object... at present...
24687     emptyCell : function() {
24688         return (new Roo.htmleditor.BlockTd({})).toObject();
24689         
24690      
24691     },
24692     
24693     removeNode : function()
24694     {
24695         return this.node;
24696     },
24697     
24698     
24699     
24700     resetWidths : function()
24701     {
24702         Array.from(this.node.getElementsByTagName('td')).forEach(function(n) {
24703             var nn = Roo.htmleditor.Block.factory(n);
24704             nn.width = '';
24705             nn.updateElement(n);
24706         });
24707     }
24708     
24709     
24710     
24711     
24712 })
24713
24714 /**
24715  *
24716  * editing a TD?
24717  *
24718  * since selections really work on the table cell, then editing really should work from there
24719  *
24720  * The original plan was to support merging etc... - but that may not be needed yet..
24721  *
24722  * So this simple version will support:
24723  *   add/remove cols
24724  *   adjust the width +/-
24725  *   reset the width...
24726  *   
24727  *
24728  */
24729
24730
24731  
24732
24733 /**
24734  * @class Roo.htmleditor.BlockTable
24735  * Block that manages a table
24736  * 
24737  * @constructor
24738  * Create a new Filter.
24739  * @param {Object} config Configuration options
24740  */
24741
24742 Roo.htmleditor.BlockTd = function(cfg)
24743 {
24744     if (cfg.node) {
24745         this.readElement(cfg.node);
24746         this.updateElement(cfg.node);
24747     }
24748     Roo.apply(this, cfg);
24749      
24750     
24751     
24752 }
24753 Roo.extend(Roo.htmleditor.BlockTd, Roo.htmleditor.Block, {
24754  
24755     node : false,
24756     
24757     width: '',
24758     textAlign : 'left',
24759     valign : 'top',
24760     
24761     colspan : 1,
24762     rowspan : 1,
24763     
24764     
24765     // used by context menu
24766     friendly_name : 'Table Cell',
24767     deleteTitle : false, // use our customer delete
24768     
24769     // context menu is drawn once..
24770     
24771     contextMenu : function(toolbar)
24772     {
24773         
24774         var cell = function() {
24775             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode);
24776         };
24777         
24778         var table = function() {
24779             return Roo.htmleditor.Block.factory(toolbar.tb.selectedNode.closest('table'));
24780         };
24781         
24782         var lr = false;
24783         var saveSel = function()
24784         {
24785             lr = toolbar.editorcore.getSelection().getRangeAt(0);
24786         }
24787         var restoreSel = function()
24788         {
24789             if (lr) {
24790                 (function() {
24791                     toolbar.editorcore.focus();
24792                     var cr = toolbar.editorcore.getSelection();
24793                     cr.removeAllRanges();
24794                     cr.addRange(lr);
24795                     toolbar.editorcore.onEditorEvent();
24796                 }).defer(10, this);
24797                 
24798                 
24799             }
24800         }
24801         
24802         var rooui =  typeof(Roo.bootstrap) == 'undefined' ? Roo : Roo.bootstrap;
24803         
24804         var syncValue = toolbar.editorcore.syncValue;
24805         
24806         var fields = {};
24807         
24808         return [
24809             {
24810                 xtype : 'Button',
24811                 text : 'Edit Table',
24812                 listeners : {
24813                     click : function() {
24814                         var t = toolbar.tb.selectedNode.closest('table');
24815                         toolbar.editorcore.selectNode(t);
24816                         toolbar.editorcore.onEditorEvent();                        
24817                     }
24818                 }
24819                 
24820             },
24821               
24822            
24823              
24824             {
24825                 xtype : 'TextItem',
24826                 text : "Column Width: ",
24827                  xns : rooui.Toolbar 
24828                
24829             },
24830             {
24831                 xtype : 'Button',
24832                 text: '-',
24833                 listeners : {
24834                     click : function (_self, e)
24835                     {
24836                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24837                         cell().shrinkColumn();
24838                         syncValue();
24839                          toolbar.editorcore.onEditorEvent();
24840                     }
24841                 },
24842                 xns : rooui.Toolbar
24843             },
24844             {
24845                 xtype : 'Button',
24846                 text: '+',
24847                 listeners : {
24848                     click : function (_self, e)
24849                     {
24850                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24851                         cell().growColumn();
24852                         syncValue();
24853                         toolbar.editorcore.onEditorEvent();
24854                     }
24855                 },
24856                 xns : rooui.Toolbar
24857             },
24858             
24859             {
24860                 xtype : 'TextItem',
24861                 text : "Vertical Align: ",
24862                 xns : rooui.Toolbar  //Boostrap?
24863             },
24864             {
24865                 xtype : 'ComboBox',
24866                 allowBlank : false,
24867                 displayField : 'val',
24868                 editable : true,
24869                 listWidth : 100,
24870                 triggerAction : 'all',
24871                 typeAhead : true,
24872                 valueField : 'val',
24873                 width : 100,
24874                 name : 'valign',
24875                 listeners : {
24876                     select : function (combo, r, index)
24877                     {
24878                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24879                         var b = cell();
24880                         b.valign = r.get('val');
24881                         b.updateElement();
24882                         syncValue();
24883                         toolbar.editorcore.onEditorEvent();
24884                     }
24885                 },
24886                 xns : rooui.form,
24887                 store : {
24888                     xtype : 'SimpleStore',
24889                     data : [
24890                         ['top'],
24891                         ['middle'],
24892                         ['bottom'] // there are afew more... 
24893                     ],
24894                     fields : [ 'val'],
24895                     xns : Roo.data
24896                 }
24897             },
24898             
24899             {
24900                 xtype : 'TextItem',
24901                 text : "Merge Cells: ",
24902                  xns : rooui.Toolbar 
24903                
24904             },
24905             
24906             
24907             {
24908                 xtype : 'Button',
24909                 text: 'Right',
24910                 listeners : {
24911                     click : function (_self, e)
24912                     {
24913                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24914                         cell().mergeRight();
24915                         //block().growColumn();
24916                         syncValue();
24917                         toolbar.editorcore.onEditorEvent();
24918                     }
24919                 },
24920                 xns : rooui.Toolbar
24921             },
24922              
24923             {
24924                 xtype : 'Button',
24925                 text: 'Below',
24926                 listeners : {
24927                     click : function (_self, e)
24928                     {
24929                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24930                         cell().mergeBelow();
24931                         //block().growColumn();
24932                         syncValue();
24933                         toolbar.editorcore.onEditorEvent();
24934                     }
24935                 },
24936                 xns : rooui.Toolbar
24937             },
24938             {
24939                 xtype : 'TextItem',
24940                 text : "| ",
24941                  xns : rooui.Toolbar 
24942                
24943             },
24944             
24945             {
24946                 xtype : 'Button',
24947                 text: 'Split',
24948                 listeners : {
24949                     click : function (_self, e)
24950                     {
24951                         //toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24952                         cell().split();
24953                         syncValue();
24954                         toolbar.editorcore.selectNode(toolbar.tb.selectedNode);
24955                         toolbar.editorcore.onEditorEvent();
24956                                              
24957                     }
24958                 },
24959                 xns : rooui.Toolbar
24960             },
24961             {
24962                 xtype : 'Fill',
24963                 xns : rooui.Toolbar 
24964                
24965             },
24966         
24967           
24968             {
24969                 xtype : 'Button',
24970                 text: 'Delete',
24971                  
24972                 xns : rooui.Toolbar,
24973                 menu : {
24974                     xtype : 'Menu',
24975                     xns : rooui.menu,
24976                     items : [
24977                         {
24978                             xtype : 'Item',
24979                             html: 'Column',
24980                             listeners : {
24981                                 click : function (_self, e)
24982                                 {
24983                                     var t = table();
24984                                     
24985                                     cell().deleteColumn();
24986                                     syncValue();
24987                                     toolbar.editorcore.selectNode(t.node);
24988                                     toolbar.editorcore.onEditorEvent();   
24989                                 }
24990                             },
24991                             xns : rooui.menu
24992                         },
24993                         {
24994                             xtype : 'Item',
24995                             html: 'Row',
24996                             listeners : {
24997                                 click : function (_self, e)
24998                                 {
24999                                     var t = table();
25000                                     cell().deleteRow();
25001                                     syncValue();
25002                                     
25003                                     toolbar.editorcore.selectNode(t.node);
25004                                     toolbar.editorcore.onEditorEvent();   
25005                                                          
25006                                 }
25007                             },
25008                             xns : rooui.menu
25009                         },
25010                        {
25011                             xtype : 'Separator',
25012                             xns : rooui.menu
25013                         },
25014                         {
25015                             xtype : 'Item',
25016                             html: 'Table',
25017                             listeners : {
25018                                 click : function (_self, e)
25019                                 {
25020                                     var t = table();
25021                                     var nn = t.node.nextSibling || t.node.previousSibling;
25022                                     t.node.parentNode.removeChild(t.node);
25023                                     if (nn) { 
25024                                         toolbar.editorcore.selectNode(nn, true);
25025                                     }
25026                                     toolbar.editorcore.onEditorEvent();   
25027                                                          
25028                                 }
25029                             },
25030                             xns : rooui.menu
25031                         }
25032                     ]
25033                 }
25034             }
25035             
25036             // align... << fixme
25037             
25038         ];
25039         
25040     },
25041     
25042     
25043   /**
25044      * create a DomHelper friendly object - for use with
25045      * Roo.DomHelper.markup / overwrite / etc..
25046      * ?? should it be called with option to hide all editing features?
25047      */
25048  /**
25049      * create a DomHelper friendly object - for use with
25050      * Roo.DomHelper.markup / overwrite / etc..
25051      * ?? should it be called with option to hide all editing features?
25052      */
25053     toObject : function()
25054     {
25055         var ret = {
25056             tag : 'td',
25057             contenteditable : 'true', // this stops cell selection from picking the table.
25058             'data-block' : 'Td',
25059             valign : this.valign,
25060             style : {  
25061                 'text-align' :  this.textAlign,
25062                 border : 'solid 1px rgb(0, 0, 0)', // ??? hard coded?
25063                 'border-collapse' : 'collapse',
25064                 padding : '6px', // 8 for desktop / 4 for mobile
25065                 'vertical-align': this.valign
25066             },
25067             html : this.html
25068         };
25069         if (this.width != '') {
25070             ret.width = this.width;
25071             ret.style.width = this.width;
25072         }
25073         
25074         
25075         if (this.colspan > 1) {
25076             ret.colspan = this.colspan ;
25077         } 
25078         if (this.rowspan > 1) {
25079             ret.rowspan = this.rowspan ;
25080         }
25081         
25082            
25083         
25084         return ret;
25085          
25086     },
25087     
25088     readElement : function(node)
25089     {
25090         node  = node ? node : this.node ;
25091         this.width = node.style.width;
25092         this.colspan = Math.max(1,1*node.getAttribute('colspan'));
25093         this.rowspan = Math.max(1,1*node.getAttribute('rowspan'));
25094         this.html = node.innerHTML;
25095         if (node.style.textAlign != '') {
25096             this.textAlign = node.style.textAlign;
25097         }
25098         
25099         
25100     },
25101      
25102     // the default cell object... at present...
25103     emptyCell : function() {
25104         return {
25105             colspan :  1,
25106             rowspan :  1,
25107             textAlign : 'left',
25108             html : "&nbsp;" // is this going to be editable now?
25109         };
25110      
25111     },
25112     
25113     removeNode : function()
25114     {
25115         return this.node.closest('table');
25116          
25117     },
25118     
25119     cellData : false,
25120     
25121     colWidths : false,
25122     
25123     toTableArray  : function()
25124     {
25125         var ret = [];
25126         var tab = this.node.closest('tr').closest('table');
25127         Array.from(tab.rows).forEach(function(r, ri){
25128             ret[ri] = [];
25129         });
25130         var rn = 0;
25131         this.colWidths = [];
25132         var all_auto = true;
25133         Array.from(tab.rows).forEach(function(r, ri){
25134             
25135             var cn = 0;
25136             Array.from(r.cells).forEach(function(ce, ci){
25137                 var c =  {
25138                     cell : ce,
25139                     row : rn,
25140                     col: cn,
25141                     colspan : ce.colSpan,
25142                     rowspan : ce.rowSpan
25143                 };
25144                 if (ce.isEqualNode(this.node)) {
25145                     this.cellData = c;
25146                 }
25147                 // if we have been filled up by a row?
25148                 if (typeof(ret[rn][cn]) != 'undefined') {
25149                     while(typeof(ret[rn][cn]) != 'undefined') {
25150                         cn++;
25151                     }
25152                     c.col = cn;
25153                 }
25154                 
25155                 if (typeof(this.colWidths[cn]) == 'undefined' && c.colspan < 2) {
25156                     this.colWidths[cn] =   ce.style.width;
25157                     if (this.colWidths[cn] != '') {
25158                         all_auto = false;
25159                     }
25160                 }
25161                 
25162                 
25163                 if (c.colspan < 2 && c.rowspan < 2 ) {
25164                     ret[rn][cn] = c;
25165                     cn++;
25166                     return;
25167                 }
25168                 for(var j = 0; j < c.rowspan; j++) {
25169                     if (typeof(ret[rn+j]) == 'undefined') {
25170                         continue; // we have a problem..
25171                     }
25172                     ret[rn+j][cn] = c;
25173                     for(var i = 0; i < c.colspan; i++) {
25174                         ret[rn+j][cn+i] = c;
25175                     }
25176                 }
25177                 
25178                 cn += c.colspan;
25179             }, this);
25180             rn++;
25181         }, this);
25182         
25183         // initalize widths.?
25184         // either all widths or no widths..
25185         if (all_auto) {
25186             this.colWidths[0] = false; // no widths flag.
25187         }
25188         
25189         
25190         return ret;
25191         
25192     },
25193     
25194     
25195     
25196     
25197     mergeRight: function()
25198     {
25199          
25200         // get the contents of the next cell along..
25201         var tr = this.node.closest('tr');
25202         var i = Array.prototype.indexOf.call(tr.childNodes, this.node);
25203         if (i >= tr.childNodes.length - 1) {
25204             return; // no cells on right to merge with.
25205         }
25206         var table = this.toTableArray();
25207         
25208         if (typeof(table[this.cellData.row][this.cellData.col+this.cellData.colspan]) == 'undefined') {
25209             return; // nothing right?
25210         }
25211         var rc = table[this.cellData.row][this.cellData.col+this.cellData.colspan];
25212         // right cell - must be same rowspan and on the same row.
25213         if (rc.rowspan != this.cellData.rowspan || rc.row != this.cellData.row) {
25214             return; // right hand side is not same rowspan.
25215         }
25216         
25217         
25218         
25219         this.node.innerHTML += ' ' + rc.cell.innerHTML;
25220         tr.removeChild(rc.cell);
25221         this.colspan += rc.colspan;
25222         this.node.setAttribute('colspan', this.colspan);
25223
25224         var table = this.toTableArray();
25225         this.normalizeWidths(table);
25226         this.updateWidths(table);
25227     },
25228     
25229     
25230     mergeBelow : function()
25231     {
25232         var table = this.toTableArray();
25233         if (typeof(table[this.cellData.row+this.cellData.rowspan]) == 'undefined') {
25234             return; // no row below
25235         }
25236         if (typeof(table[this.cellData.row+this.cellData.rowspan][this.cellData.col]) == 'undefined') {
25237             return; // nothing right?
25238         }
25239         var rc = table[this.cellData.row+this.cellData.rowspan][this.cellData.col];
25240         
25241         if (rc.colspan != this.cellData.colspan || rc.col != this.cellData.col) {
25242             return; // right hand side is not same rowspan.
25243         }
25244         this.node.innerHTML =  this.node.innerHTML + rc.cell.innerHTML ;
25245         rc.cell.parentNode.removeChild(rc.cell);
25246         this.rowspan += rc.rowspan;
25247         this.node.setAttribute('rowspan', this.rowspan);
25248     },
25249     
25250     split: function()
25251     {
25252         if (this.node.rowSpan < 2 && this.node.colSpan < 2) {
25253             return;
25254         }
25255         var table = this.toTableArray();
25256         var cd = this.cellData;
25257         this.rowspan = 1;
25258         this.colspan = 1;
25259         
25260         for(var r = cd.row; r < cd.row + cd.rowspan; r++) {
25261              
25262             
25263             for(var c = cd.col; c < cd.col + cd.colspan; c++) {
25264                 if (r == cd.row && c == cd.col) {
25265                     this.node.removeAttribute('rowspan');
25266                     this.node.removeAttribute('colspan');
25267                 }
25268                  
25269                 var ntd = this.node.cloneNode(); // which col/row should be 0..
25270                 ntd.removeAttribute('id'); 
25271                 ntd.style.width  = this.colWidths[c];
25272                 ntd.innerHTML = '';
25273                 table[r][c] = { cell : ntd, col : c, row: r , colspan : 1 , rowspan : 1   };
25274             }
25275             
25276         }
25277         this.redrawAllCells(table);
25278         
25279     },
25280     
25281     
25282     
25283     redrawAllCells: function(table)
25284     {
25285         
25286          
25287         var tab = this.node.closest('tr').closest('table');
25288         var ctr = tab.rows[0].parentNode;
25289         Array.from(tab.rows).forEach(function(r, ri){
25290             
25291             Array.from(r.cells).forEach(function(ce, ci){
25292                 ce.parentNode.removeChild(ce);
25293             });
25294             r.parentNode.removeChild(r);
25295         });
25296         for(var r = 0 ; r < table.length; r++) {
25297             var re = tab.rows[r];
25298             
25299             var re = tab.ownerDocument.createElement('tr');
25300             ctr.appendChild(re);
25301             for(var c = 0 ; c < table[r].length; c++) {
25302                 if (table[r][c].cell === false) {
25303                     continue;
25304                 }
25305                 
25306                 re.appendChild(table[r][c].cell);
25307                  
25308                 table[r][c].cell = false;
25309             }
25310         }
25311         
25312     },
25313     updateWidths : function(table)
25314     {
25315         for(var r = 0 ; r < table.length; r++) {
25316            
25317             for(var c = 0 ; c < table[r].length; c++) {
25318                 if (table[r][c].cell === false) {
25319                     continue;
25320                 }
25321                 
25322                 if (this.colWidths[0] != false && table[r][c].colspan < 2) {
25323                     var el = Roo.htmleditor.Block.factory(table[r][c].cell);
25324                     el.width = Math.floor(this.colWidths[c])  +'%';
25325                     el.updateElement(el.node);
25326                 }
25327                 if (this.colWidths[0] != false && table[r][c].colspan > 1) {
25328                     var el = Roo.htmleditor.Block.factory(table[r][c].cell);
25329                     var width = 0;
25330                     for(var i = 0; i < table[r][c].colspan; i ++) {
25331                         width += Math.floor(this.colWidths[c + i]);
25332                     }
25333                     el.width = width  +'%';
25334                     el.updateElement(el.node);
25335                 }
25336                 table[r][c].cell = false; // done
25337             }
25338         }
25339     },
25340     normalizeWidths : function(table)
25341     {
25342         if (this.colWidths[0] === false) {
25343             var nw = 100.0 / this.colWidths.length;
25344             this.colWidths.forEach(function(w,i) {
25345                 this.colWidths[i] = nw;
25346             },this);
25347             return;
25348         }
25349     
25350         var t = 0, missing = [];
25351         
25352         this.colWidths.forEach(function(w,i) {
25353             //if you mix % and
25354             this.colWidths[i] = this.colWidths[i] == '' ? 0 : (this.colWidths[i]+'').replace(/[^0-9]+/g,'')*1;
25355             var add =  this.colWidths[i];
25356             if (add > 0) {
25357                 t+=add;
25358                 return;
25359             }
25360             missing.push(i);
25361             
25362             
25363         },this);
25364         var nc = this.colWidths.length;
25365         if (missing.length) {
25366             var mult = (nc - missing.length) / (1.0 * nc);
25367             var t = mult * t;
25368             var ew = (100 -t) / (1.0 * missing.length);
25369             this.colWidths.forEach(function(w,i) {
25370                 if (w > 0) {
25371                     this.colWidths[i] = w * mult;
25372                     return;
25373                 }
25374                 
25375                 this.colWidths[i] = ew;
25376             }, this);
25377             // have to make up numbers..
25378              
25379         }
25380         // now we should have all the widths..
25381         
25382     
25383     },
25384     
25385     shrinkColumn : function()
25386     {
25387         var table = this.toTableArray();
25388         this.normalizeWidths(table);
25389         var col = this.cellData.col;
25390         var nw = this.colWidths[col] * 0.8;
25391         if (nw < 5) {
25392             return;
25393         }
25394         var otherAdd = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
25395         this.colWidths.forEach(function(w,i) {
25396             if (i == col) {
25397                  this.colWidths[i] = nw;
25398                 return;
25399             }
25400             this.colWidths[i] += otherAdd
25401         }, this);
25402         this.updateWidths(table);
25403          
25404     },
25405     growColumn : function()
25406     {
25407         var table = this.toTableArray();
25408         this.normalizeWidths(table);
25409         var col = this.cellData.col;
25410         var nw = this.colWidths[col] * 1.2;
25411         if (nw > 90) {
25412             return;
25413         }
25414         var otherSub = (this.colWidths[col]  * 0.2) / (this.colWidths.length -1);
25415         this.colWidths.forEach(function(w,i) {
25416             if (i == col) {
25417                 this.colWidths[i] = nw;
25418                 return;
25419             }
25420             this.colWidths[i] -= otherSub
25421         }, this);
25422         this.updateWidths(table);
25423          
25424     },
25425     deleteRow : function()
25426     {
25427         // delete this rows 'tr'
25428         // if any of the cells in this row have a rowspan > 1 && row!= this row..
25429         // then reduce the rowspan.
25430         var table = this.toTableArray();
25431         // this.cellData.row;
25432         for (var i =0;i< table[this.cellData.row].length ; i++) {
25433             var c = table[this.cellData.row][i];
25434             if (c.row != this.cellData.row) {
25435                 
25436                 c.rowspan--;
25437                 c.cell.setAttribute('rowspan', c.rowspan);
25438                 continue;
25439             }
25440             if (c.rowspan > 1) {
25441                 c.rowspan--;
25442                 c.cell.setAttribute('rowspan', c.rowspan);
25443             }
25444         }
25445         table.splice(this.cellData.row,1);
25446         this.redrawAllCells(table);
25447         
25448     },
25449     deleteColumn : function()
25450     {
25451         var table = this.toTableArray();
25452         
25453         for (var i =0;i< table.length ; i++) {
25454             var c = table[i][this.cellData.col];
25455             if (c.col != this.cellData.col) {
25456                 table[i][this.cellData.col].colspan--;
25457             } else if (c.colspan > 1) {
25458                 c.colspan--;
25459                 c.cell.setAttribute('colspan', c.colspan);
25460             }
25461             table[i].splice(this.cellData.col,1);
25462         }
25463         
25464         this.redrawAllCells(table);
25465     }
25466     
25467     
25468     
25469     
25470 })
25471
25472 //<script type="text/javascript">
25473
25474 /*
25475  * Based  Ext JS Library 1.1.1
25476  * Copyright(c) 2006-2007, Ext JS, LLC.
25477  * LGPL
25478  *
25479  */
25480  
25481 /**
25482  * @class Roo.HtmlEditorCore
25483  * @extends Roo.Component
25484  * Provides a the editing component for the HTML editors in Roo. (bootstrap and Roo.form)
25485  *
25486  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
25487  */
25488
25489 Roo.HtmlEditorCore = function(config){
25490     
25491     
25492     Roo.HtmlEditorCore.superclass.constructor.call(this, config);
25493     
25494     
25495     this.addEvents({
25496         /**
25497          * @event initialize
25498          * Fires when the editor is fully initialized (including the iframe)
25499          * @param {Roo.HtmlEditorCore} this
25500          */
25501         initialize: true,
25502         /**
25503          * @event activate
25504          * Fires when the editor is first receives the focus. Any insertion must wait
25505          * until after this event.
25506          * @param {Roo.HtmlEditorCore} this
25507          */
25508         activate: true,
25509          /**
25510          * @event beforesync
25511          * Fires before the textarea is updated with content from the editor iframe. Return false
25512          * to cancel the sync.
25513          * @param {Roo.HtmlEditorCore} this
25514          * @param {String} html
25515          */
25516         beforesync: true,
25517          /**
25518          * @event beforepush
25519          * Fires before the iframe editor is updated with content from the textarea. Return false
25520          * to cancel the push.
25521          * @param {Roo.HtmlEditorCore} this
25522          * @param {String} html
25523          */
25524         beforepush: true,
25525          /**
25526          * @event sync
25527          * Fires when the textarea is updated with content from the editor iframe.
25528          * @param {Roo.HtmlEditorCore} this
25529          * @param {String} html
25530          */
25531         sync: true,
25532          /**
25533          * @event push
25534          * Fires when the iframe editor is updated with content from the textarea.
25535          * @param {Roo.HtmlEditorCore} this
25536          * @param {String} html
25537          */
25538         push: true,
25539         
25540         /**
25541          * @event editorevent
25542          * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
25543          * @param {Roo.HtmlEditorCore} this
25544          */
25545         editorevent: true 
25546         
25547         
25548     });
25549     
25550     // at this point this.owner is set, so we can start working out the whitelisted / blacklisted elements
25551     
25552     // defaults : white / black...
25553     this.applyBlacklists();
25554     
25555     
25556     
25557 };
25558
25559
25560 Roo.extend(Roo.HtmlEditorCore, Roo.Component,  {
25561
25562
25563      /**
25564      * @cfg {Roo.form.HtmlEditor|Roo.bootstrap.HtmlEditor} the owner field 
25565      */
25566     
25567     owner : false,
25568     
25569      /**
25570      * @cfg {String} css styling for resizing. (used on bootstrap only)
25571      */
25572     resize : false,
25573      /**
25574      * @cfg {Number} height (in pixels)
25575      */   
25576     height: 300,
25577    /**
25578      * @cfg {Number} width (in pixels)
25579      */   
25580     width: 500,
25581      /**
25582      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
25583      *         if you are doing an email editor, this probably needs disabling, it's designed
25584      */
25585     autoClean: true,
25586     
25587     /**
25588      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
25589      */
25590     enableBlocks : true,
25591     /**
25592      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets.
25593      * 
25594      */
25595     stylesheets: false,
25596      /**
25597      * @cfg {String} language default en - language of text (usefull for rtl languages)
25598      * 
25599      */
25600     language: 'en',
25601     
25602     /**
25603      * @cfg {boolean} allowComments - default false - allow comments in HTML source
25604      *          - by default they are stripped - if you are editing email you may need this.
25605      */
25606     allowComments: false,
25607     // id of frame..
25608     frameId: false,
25609     
25610     // private properties
25611     validationEvent : false,
25612     deferHeight: true,
25613     initialized : false,
25614     activated : false,
25615     sourceEditMode : false,
25616     onFocus : Roo.emptyFn,
25617     iframePad:3,
25618     hideMode:'offsets',
25619     
25620     clearUp: true,
25621     
25622     // blacklist + whitelisted elements..
25623     black: false,
25624     white: false,
25625      
25626     bodyCls : '',
25627
25628     
25629     undoManager : false,
25630     /**
25631      * Protected method that will not generally be called directly. It
25632      * is called when the editor initializes the iframe with HTML contents. Override this method if you
25633      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
25634      */
25635     getDocMarkup : function(){
25636         // body styles..
25637         var st = '';
25638         
25639         // inherit styels from page...?? 
25640         if (this.stylesheets === false) {
25641             
25642             Roo.get(document.head).select('style').each(function(node) {
25643                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
25644             });
25645             
25646             Roo.get(document.head).select('link').each(function(node) { 
25647                 st += node.dom.outerHTML || new XMLSerializer().serializeToString(node.dom);
25648             });
25649             
25650         } else if (!this.stylesheets.length) {
25651                 // simple..
25652                 st = '<style type="text/css">' +
25653                     'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
25654                    '</style>';
25655         } else {
25656             for (var i in this.stylesheets) {
25657                 if (typeof(this.stylesheets[i]) != 'string') {
25658                     continue;
25659                 }
25660                 st += '<link rel="stylesheet" href="' + this.stylesheets[i] +'" type="text/css">';
25661             }
25662             
25663         }
25664         
25665         st +=  '<style type="text/css">' +
25666             'IMG { cursor: pointer } ' +
25667         '</style>';
25668         
25669         st += '<meta name="google" content="notranslate">';
25670         
25671         var cls = 'notranslate roo-htmleditor-body';
25672         
25673         if(this.bodyCls.length){
25674             cls += ' ' + this.bodyCls;
25675         }
25676         
25677         return '<html  class="notranslate" translate="no"><head>' + st  +
25678             //<style type="text/css">' +
25679             //'body{border:0;margin:0;padding:3px;height:98%;cursor:text;}' +
25680             //'</style>' +
25681             ' </head><body contenteditable="true" data-enable-grammerly="true" class="' +  cls + '"></body></html>';
25682     },
25683
25684     // private
25685     onRender : function(ct, position)
25686     {
25687         var _t = this;
25688         //Roo.HtmlEditorCore.superclass.onRender.call(this, ct, position);
25689         this.el = this.owner.inputEl ? this.owner.inputEl() : this.owner.el;
25690         
25691         
25692         this.el.dom.style.border = '0 none';
25693         this.el.dom.setAttribute('tabIndex', -1);
25694         this.el.addClass('x-hidden hide');
25695         
25696         
25697         
25698         if(Roo.isIE){ // fix IE 1px bogus margin
25699             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
25700         }
25701        
25702         
25703         this.frameId = Roo.id();
25704         
25705         var ifcfg = {
25706             tag: 'iframe',
25707             cls: 'form-control', // bootstrap..
25708             id: this.frameId,
25709             name: this.frameId,
25710             frameBorder : 'no',
25711             'src' : Roo.SSL_SECURE_URL ? Roo.SSL_SECURE_URL  :  "javascript:false"
25712         };
25713         if (this.resize) {
25714             ifcfg.style = { resize : this.resize };
25715         }
25716         
25717         var iframe = this.owner.wrap.createChild(ifcfg, this.el); 
25718         
25719         
25720         this.iframe = iframe.dom;
25721
25722         this.assignDocWin();
25723         
25724         this.doc.designMode = 'on';
25725        
25726         this.doc.open();
25727         this.doc.write(this.getDocMarkup());
25728         this.doc.close();
25729
25730         
25731         var task = { // must defer to wait for browser to be ready
25732             run : function(){
25733                 //console.log("run task?" + this.doc.readyState);
25734                 this.assignDocWin();
25735                 if(this.doc.body || this.doc.readyState == 'complete'){
25736                     try {
25737                         this.doc.designMode="on";
25738                         
25739                     } catch (e) {
25740                         return;
25741                     }
25742                     Roo.TaskMgr.stop(task);
25743                     this.initEditor.defer(10, this);
25744                 }
25745             },
25746             interval : 10,
25747             duration: 10000,
25748             scope: this
25749         };
25750         Roo.TaskMgr.start(task);
25751
25752     },
25753
25754     // private
25755     onResize : function(w, h)
25756     {
25757          Roo.log('resize: ' +w + ',' + h );
25758         //Roo.HtmlEditorCore.superclass.onResize.apply(this, arguments);
25759         if(!this.iframe){
25760             return;
25761         }
25762         if(typeof w == 'number'){
25763             
25764             this.iframe.style.width = w + 'px';
25765         }
25766         if(typeof h == 'number'){
25767             
25768             this.iframe.style.height = h + 'px';
25769             if(this.doc){
25770                 (this.doc.body || this.doc.documentElement).style.height = (h - (this.iframePad*2)) + 'px';
25771             }
25772         }
25773         
25774     },
25775
25776     /**
25777      * Toggles the editor between standard and source edit mode.
25778      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
25779      */
25780     toggleSourceEdit : function(sourceEditMode){
25781         
25782         this.sourceEditMode = sourceEditMode === true;
25783         
25784         if(this.sourceEditMode){
25785  
25786             Roo.get(this.iframe).addClass(['x-hidden','hide', 'd-none']);     //FIXME - what's the BS styles for these
25787             
25788         }else{
25789             Roo.get(this.iframe).removeClass(['x-hidden','hide', 'd-none']);
25790             //this.iframe.className = '';
25791             this.deferFocus();
25792         }
25793         //this.setSize(this.owner.wrap.getSize());
25794         //this.fireEvent('editmodechange', this, this.sourceEditMode);
25795     },
25796
25797     
25798   
25799
25800     /**
25801      * Protected method that will not generally be called directly. If you need/want
25802      * custom HTML cleanup, this is the method you should override.
25803      * @param {String} html The HTML to be cleaned
25804      * return {String} The cleaned HTML
25805      */
25806     cleanHtml : function(html)
25807     {
25808         html = String(html);
25809         if(html.length > 5){
25810             if(Roo.isSafari){ // strip safari nonsense
25811                 html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
25812             }
25813         }
25814         if(html == '&nbsp;'){
25815             html = '';
25816         }
25817         return html;
25818     },
25819
25820     /**
25821      * HTML Editor -> Textarea
25822      * Protected method that will not generally be called directly. Syncs the contents
25823      * of the editor iframe with the textarea.
25824      */
25825     syncValue : function()
25826     {
25827         //Roo.log("HtmlEditorCore:syncValue (EDITOR->TEXT)");
25828         if(this.initialized){
25829             
25830             if (this.undoManager) {
25831                 this.undoManager.addEvent();
25832             }
25833
25834             
25835             var bd = (this.doc.body || this.doc.documentElement);
25836            
25837             
25838             var sel = this.win.getSelection();
25839             
25840             var div = document.createElement('div');
25841             div.innerHTML = bd.innerHTML;
25842             var gtx = div.getElementsByClassName('gtx-trans-icon'); // google translate - really annoying and difficult to get rid of.
25843             if (gtx.length > 0) {
25844                 var rm = gtx.item(0).parentNode;
25845                 rm.parentNode.removeChild(rm);
25846             }
25847             
25848            
25849             if (this.enableBlocks) {
25850                 new Roo.htmleditor.FilterBlock({ node : div });
25851             }
25852             
25853             var html = div.innerHTML;
25854             
25855             //?? tidy?
25856             if (this.autoClean) {
25857                 
25858                 new Roo.htmleditor.FilterAttributes({
25859                     node : div,
25860                     attrib_white : [
25861                             'href',
25862                             'src',
25863                             'name',
25864                             'align',
25865                             'colspan',
25866                             'rowspan',
25867                             'data-display',
25868                             'data-caption-display',
25869                             'data-width',
25870                             'data-caption',
25871                             'start' ,
25872                             'style',
25873                             // youtube embed.
25874                             'class',
25875                             'allowfullscreen',
25876                             'frameborder',
25877                             'width',
25878                             'height',
25879                             'alt'
25880                             ],
25881                     attrib_clean : ['href', 'src' ] 
25882                 });
25883                 
25884                 var tidy = new Roo.htmleditor.TidySerializer({
25885                     inner:  true
25886                 });
25887                 html  = tidy.serialize(div);
25888                 
25889             }
25890             
25891             
25892             if(Roo.isSafari){
25893                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
25894                 var m = bs ? bs.match(/text-align:(.*?);/i) : false;
25895                 if(m && m[1]){
25896                     html = '<div style="'+m[0]+'">' + html + '</div>';
25897                 }
25898             }
25899             html = this.cleanHtml(html);
25900             // fix up the special chars.. normaly like back quotes in word...
25901             // however we do not want to do this with chinese..
25902             html = html.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u0080-\uFFFF]/g, function(match) {
25903                 
25904                 var cc = match.charCodeAt();
25905
25906                 // Get the character value, handling surrogate pairs
25907                 if (match.length == 2) {
25908                     // It's a surrogate pair, calculate the Unicode code point
25909                     var high = match.charCodeAt(0) - 0xD800;
25910                     var low  = match.charCodeAt(1) - 0xDC00;
25911                     cc = (high * 0x400) + low + 0x10000;
25912                 }  else if (
25913                     (cc >= 0x4E00 && cc < 0xA000 ) ||
25914                     (cc >= 0x3400 && cc < 0x4E00 ) ||
25915                     (cc >= 0xf900 && cc < 0xfb00 )
25916                 ) {
25917                         return match;
25918                 }  
25919          
25920                 // No, use a numeric entity. Here we brazenly (and possibly mistakenly)
25921                 return "&#" + cc + ";";
25922                 
25923                 
25924             });
25925             
25926             
25927              
25928             if(this.owner.fireEvent('beforesync', this, html) !== false){
25929                 this.el.dom.value = html;
25930                 this.owner.fireEvent('sync', this, html);
25931             }
25932         }
25933     },
25934
25935     /**
25936      * TEXTAREA -> EDITABLE
25937      * Protected method that will not generally be called directly. Pushes the value of the textarea
25938      * into the iframe editor.
25939      */
25940     pushValue : function()
25941     {
25942         //Roo.log("HtmlEditorCore:pushValue (TEXT->EDITOR)");
25943         if(this.initialized){
25944             var v = this.el.dom.value.trim();
25945             
25946             
25947             if(this.owner.fireEvent('beforepush', this, v) !== false){
25948                 var d = (this.doc.body || this.doc.documentElement);
25949                 d.innerHTML = v;
25950                  
25951                 this.el.dom.value = d.innerHTML;
25952                 this.owner.fireEvent('push', this, v);
25953             }
25954             if (this.autoClean) {
25955                 new Roo.htmleditor.FilterParagraph({node : this.doc.body}); // paragraphs
25956                 new Roo.htmleditor.FilterSpan({node : this.doc.body}); // empty spans
25957             }
25958             if (this.enableBlocks) {
25959                 Roo.htmleditor.Block.initAll(this.doc.body);
25960             }
25961             
25962             this.updateLanguage();
25963             
25964             var lc = this.doc.body.lastChild;
25965             if (lc && lc.nodeType == 1 && lc.getAttribute("contenteditable") == "false") {
25966                 // add an extra line at the end.
25967                 this.doc.body.appendChild(this.doc.createElement('br'));
25968             }
25969             
25970             
25971         }
25972     },
25973
25974     // private
25975     deferFocus : function(){
25976         this.focus.defer(10, this);
25977     },
25978
25979     // doc'ed in Field
25980     focus : function(){
25981         if(this.win && !this.sourceEditMode){
25982             this.win.focus();
25983         }else{
25984             this.el.focus();
25985         }
25986     },
25987     
25988     assignDocWin: function()
25989     {
25990         var iframe = this.iframe;
25991         
25992          if(Roo.isIE){
25993             this.doc = iframe.contentWindow.document;
25994             this.win = iframe.contentWindow;
25995         } else {
25996 //            if (!Roo.get(this.frameId)) {
25997 //                return;
25998 //            }
25999 //            this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
26000 //            this.win = Roo.get(this.frameId).dom.contentWindow;
26001             
26002             if (!Roo.get(this.frameId) && !iframe.contentDocument) {
26003                 return;
26004             }
26005             
26006             this.doc = (iframe.contentDocument || Roo.get(this.frameId).dom.document);
26007             this.win = (iframe.contentWindow || Roo.get(this.frameId).dom.contentWindow);
26008         }
26009     },
26010     
26011     // private
26012     initEditor : function(){
26013         //console.log("INIT EDITOR");
26014         this.assignDocWin();
26015         
26016         
26017         
26018         this.doc.designMode="on";
26019         this.doc.open();
26020         this.doc.write(this.getDocMarkup());
26021         this.doc.close();
26022         
26023         var dbody = (this.doc.body || this.doc.documentElement);
26024         //var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
26025         // this copies styles from the containing element into thsi one..
26026         // not sure why we need all of this..
26027         //var ss = this.el.getStyles('font-size', 'background-image', 'background-repeat');
26028         
26029         //var ss = this.el.getStyles( 'background-image', 'background-repeat');
26030         //ss['background-attachment'] = 'fixed'; // w3c
26031         dbody.bgProperties = 'fixed'; // ie
26032         dbody.setAttribute("translate", "no");
26033         
26034         //Roo.DomHelper.applyStyles(dbody, ss);
26035         Roo.EventManager.on(this.doc, {
26036              
26037             'mouseup': this.onEditorEvent,
26038             'dblclick': this.onEditorEvent,
26039             'click': this.onEditorEvent,
26040             'keyup': this.onEditorEvent,
26041             
26042             buffer:100,
26043             scope: this
26044         });
26045         Roo.EventManager.on(this.doc, {
26046             'paste': this.onPasteEvent,
26047             scope : this
26048         });
26049         if(Roo.isGecko){
26050             Roo.EventManager.on(this.doc, 'keypress', this.mozKeyPress, this);
26051         }
26052         //??? needed???
26053         if(Roo.isIE || Roo.isSafari || Roo.isOpera){
26054             Roo.EventManager.on(this.doc, 'keydown', this.fixKeys, this);
26055         }
26056         this.initialized = true;
26057
26058         
26059         // initialize special key events - enter
26060         new Roo.htmleditor.KeyEnter({core : this});
26061         
26062          
26063         
26064         this.owner.fireEvent('initialize', this);
26065         this.pushValue();
26066     },
26067     // this is to prevent a href clicks resulting in a redirect?
26068    
26069     onPasteEvent : function(e,v)
26070     {
26071         // I think we better assume paste is going to be a dirty load of rubish from word..
26072         
26073         // even pasting into a 'email version' of this widget will have to clean up that mess.
26074         var cd = (e.browserEvent.clipboardData || window.clipboardData);
26075         
26076         // check what type of paste - if it's an image, then handle it differently.
26077         if (cd.files && cd.files.length > 0 && cd.types.indexOf('text/html') < 0) {
26078             // pasting images? 
26079             var urlAPI = (window.createObjectURL && window) || 
26080                 (window.URL && URL.revokeObjectURL && URL) || 
26081                 (window.webkitURL && webkitURL);
26082             
26083             var r = new FileReader();
26084             var t = this;
26085             r.addEventListener('load',function()
26086             {
26087                 
26088                 var d = (new DOMParser().parseFromString('<img src="' + r.result+ '">', 'text/html')).body;
26089                 // is insert asycn?
26090                 if (t.enableBlocks) {
26091                     
26092                     Array.from(d.getElementsByTagName('img')).forEach(function(img) {
26093                         if (img.closest('figure')) { // assume!! that it's aready
26094                             return;
26095                         }
26096                         var fig  = new Roo.htmleditor.BlockFigure({
26097                             image_src  : img.src
26098                         });
26099                         fig.updateElement(img); // replace it..
26100                         
26101                     });
26102                 }
26103                 t.insertAtCursor(d.innerHTML.replace(/&nbsp;/g,' '));
26104                 t.owner.fireEvent('paste', this);
26105             });
26106             r.readAsDataURL(cd.files[0]);
26107             
26108             e.preventDefault();
26109             
26110             return false;
26111         }
26112         if (cd.types.indexOf('text/html') < 0 ) {
26113             return false;
26114         }
26115         var images = [];
26116         var html = cd.getData('text/html'); // clipboard event
26117         if (cd.types.indexOf('text/rtf') > -1) {
26118             var parser = new Roo.rtf.Parser(cd.getData('text/rtf'));
26119             images = parser.doc ? parser.doc.getElementsByType('pict') : [];
26120         }
26121         // Roo.log(images);
26122         // Roo.log(imgs);
26123         // fixme..
26124         images = images.filter(function(g) { return !g.path.match(/^rtf\/(head|pgdsctbl|listtable|footerf)/); }) // ignore headers/footers etc.
26125                        .map(function(g) { return g.toDataURL(); })
26126                        .filter(function(g) { return g != 'about:blank'; });
26127         
26128         //Roo.log(html);
26129         html = this.cleanWordChars(html);
26130         
26131         var d = (new DOMParser().parseFromString(html, 'text/html')).body;
26132         
26133         
26134         var sn = this.getParentElement();
26135         // check if d contains a table, and prevent nesting??
26136         //Roo.log(d.getElementsByTagName('table'));
26137         //Roo.log(sn);
26138         //Roo.log(sn.closest('table'));
26139         if (d.getElementsByTagName('table').length && sn && sn.closest('table')) {
26140             e.preventDefault();
26141             this.insertAtCursor("You can not nest tables");
26142             //Roo.log("prevent?"); // fixme - 
26143             return false;
26144         }
26145         
26146         
26147         
26148         if (images.length > 0) {
26149             // replace all v:imagedata - with img.
26150             var ar = Array.from(d.getElementsByTagName('v:imagedata'));
26151             Roo.each(ar, function(node) {
26152                 node.parentNode.insertBefore(d.ownerDocument.createElement('img'), node );
26153                 node.parentNode.removeChild(node);
26154             });
26155             
26156             
26157             Roo.each(d.getElementsByTagName('img'), function(img, i) {
26158                 img.setAttribute('src', images[i]);
26159             });
26160         }
26161         if (this.autoClean) {
26162             new Roo.htmleditor.FilterWord({ node : d });
26163             
26164             new Roo.htmleditor.FilterStyleToTag({ node : d });
26165             new Roo.htmleditor.FilterAttributes({
26166                 node : d,
26167                 attrib_white : [
26168                     'href',
26169                     'src',
26170                     'name',
26171                     'align',
26172                     'colspan',
26173                     'rowspan' 
26174                 /*  THESE ARE NOT ALLWOED FOR PASTE
26175                  *    'data-display',
26176                     'data-caption-display',
26177                     'data-width',
26178                     'data-caption',
26179                     'start' ,
26180                     'style',
26181                     // youtube embed.
26182                     'class',
26183                     'allowfullscreen',
26184                     'frameborder',
26185                     'width',
26186                     'height',
26187                     'alt'
26188                     */
26189                     ],
26190                 attrib_clean : ['href', 'src' ] 
26191             });
26192             new Roo.htmleditor.FilterBlack({ node : d, tag : this.black});
26193             // should be fonts..
26194             new Roo.htmleditor.FilterKeepChildren({node : d, tag : [ 'FONT', ':' ]} );
26195             new Roo.htmleditor.FilterParagraph({ node : d });
26196             new Roo.htmleditor.FilterSpan({ node : d });
26197             new Roo.htmleditor.FilterLongBr({ node : d });
26198             new Roo.htmleditor.FilterComment({ node : d });
26199             
26200             
26201         }
26202         if (this.enableBlocks) {
26203                 
26204             Array.from(d.getElementsByTagName('img')).forEach(function(img) {
26205                 if (img.closest('figure')) { // assume!! that it's aready
26206                     return;
26207                 }
26208                 var fig  = new Roo.htmleditor.BlockFigure({
26209                     image_src  : img.src
26210                 });
26211                 fig.updateElement(img); // replace it..
26212                 
26213             });
26214         }
26215         
26216         
26217         this.insertAtCursor(d.innerHTML.replace(/&nbsp;/g,' '));
26218         if (this.enableBlocks) {
26219             Roo.htmleditor.Block.initAll(this.doc.body);
26220         }
26221          
26222         
26223         e.preventDefault();
26224         this.owner.fireEvent('paste', this);
26225         return false;
26226         // default behaveiour should be our local cleanup paste? (optional?)
26227         // for simple editor - we want to hammer the paste and get rid of everything... - so over-rideable..
26228         //this.owner.fireEvent('paste', e, v);
26229     },
26230     // private
26231     onDestroy : function(){
26232         
26233         
26234         
26235         if(this.rendered){
26236             
26237             //for (var i =0; i < this.toolbars.length;i++) {
26238             //    // fixme - ask toolbars for heights?
26239             //    this.toolbars[i].onDestroy();
26240            // }
26241             
26242             //this.wrap.dom.innerHTML = '';
26243             //this.wrap.remove();
26244         }
26245     },
26246
26247     // private
26248     onFirstFocus : function(){
26249         
26250         this.assignDocWin();
26251         this.undoManager = new Roo.lib.UndoManager(100,(this.doc.body || this.doc.documentElement));
26252         
26253         this.activated = true;
26254          
26255     
26256         if(Roo.isGecko){ // prevent silly gecko errors
26257             this.win.focus();
26258             var s = this.win.getSelection();
26259             if(!s.focusNode || s.focusNode.nodeType != 3){
26260                 var r = s.getRangeAt(0);
26261                 r.selectNodeContents((this.doc.body || this.doc.documentElement));
26262                 r.collapse(true);
26263                 this.deferFocus();
26264             }
26265             try{
26266                 this.execCmd('useCSS', true);
26267                 this.execCmd('styleWithCSS', false);
26268             }catch(e){}
26269         }
26270         this.owner.fireEvent('activate', this);
26271     },
26272
26273     // private
26274     adjustFont: function(btn){
26275         var adjust = btn.cmd == 'increasefontsize' ? 1 : -1;
26276         //if(Roo.isSafari){ // safari
26277         //    adjust *= 2;
26278        // }
26279         var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10);
26280         if(Roo.isSafari){ // safari
26281             var sm = { 10 : 1, 13: 2, 16:3, 18:4, 24: 5, 32:6, 48: 7 };
26282             v =  (v < 10) ? 10 : v;
26283             v =  (v > 48) ? 48 : v;
26284             v = typeof(sm[v]) == 'undefined' ? 1 : sm[v];
26285             
26286         }
26287         
26288         
26289         v = Math.max(1, v+adjust);
26290         
26291         this.execCmd('FontSize', v  );
26292     },
26293
26294     onEditorEvent : function(e)
26295     {
26296          
26297         
26298         if (e && (e.ctrlKey || e.metaKey) && e.keyCode === 90) {
26299             return; // we do not handle this.. (undo manager does..)
26300         }
26301         // clicking a 'block'?
26302         
26303         // in theory this detects if the last element is not a br, then we try and do that.
26304         // its so clicking in space at bottom triggers adding a br and moving the cursor.
26305         if (e &&
26306             e.target.nodeName == 'BODY' &&
26307             e.type == "mouseup" &&
26308             this.doc.body.lastChild
26309            ) {
26310             var lc = this.doc.body.lastChild;
26311             // gtx-trans is google translate plugin adding crap.
26312             while ((lc.nodeType == 3 && lc.nodeValue == '') || lc.id == 'gtx-trans') {
26313                 lc = lc.previousSibling;
26314             }
26315             if (lc.nodeType == 1 && lc.nodeName != 'BR') {
26316             // if last element is <BR> - then dont do anything.
26317             
26318                 var ns = this.doc.createElement('br');
26319                 this.doc.body.appendChild(ns);
26320                 range = this.doc.createRange();
26321                 range.setStartAfter(ns);
26322                 range.collapse(true);
26323                 var sel = this.win.getSelection();
26324                 sel.removeAllRanges();
26325                 sel.addRange(range);
26326             }
26327         }
26328         
26329         
26330         
26331         this.fireEditorEvent(e);
26332       //  this.updateToolbar();
26333         this.syncValue(); //we can not sync so often.. sync cleans, so this breaks stuff
26334     },
26335     
26336     fireEditorEvent: function(e)
26337     {
26338         this.owner.fireEvent('editorevent', this, e);
26339     },
26340
26341     insertTag : function(tg)
26342     {
26343         // could be a bit smarter... -> wrap the current selected tRoo..
26344         if (tg.toLowerCase() == 'span' ||
26345             tg.toLowerCase() == 'code' ||
26346             tg.toLowerCase() == 'sup' ||
26347             tg.toLowerCase() == 'sub' 
26348             ) {
26349             
26350             range = this.createRange(this.getSelection());
26351             var wrappingNode = this.doc.createElement(tg.toLowerCase());
26352             wrappingNode.appendChild(range.extractContents());
26353             range.insertNode(wrappingNode);
26354
26355             return;
26356             
26357             
26358             
26359         }
26360         this.execCmd("formatblock",   tg);
26361         this.undoManager.addEvent(); 
26362     },
26363     
26364     insertText : function(txt)
26365     {
26366         
26367         
26368         var range = this.createRange();
26369         range.deleteContents();
26370                //alert(Sender.getAttribute('label'));
26371                
26372         range.insertNode(this.doc.createTextNode(txt));
26373         this.undoManager.addEvent();
26374     } ,
26375     
26376      
26377
26378     /**
26379      * Executes a Midas editor command on the editor document and performs necessary focus and
26380      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
26381      * @param {String} cmd The Midas command
26382      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
26383      */
26384     relayCmd : function(cmd, value)
26385     {
26386         
26387         switch (cmd) {
26388             case 'justifyleft':
26389             case 'justifyright':
26390             case 'justifycenter':
26391                 // if we are in a cell, then we will adjust the
26392                 var n = this.getParentElement();
26393                 var td = n.closest('td');
26394                 if (td) {
26395                     var bl = Roo.htmleditor.Block.factory(td);
26396                     bl.textAlign = cmd.replace('justify','');
26397                     bl.updateElement();
26398                     this.owner.fireEvent('editorevent', this);
26399                     return;
26400                 }
26401                 this.execCmd('styleWithCSS', true); // 
26402                 break;
26403             case 'bold':
26404             case 'italic':
26405             case 'underline':                
26406                 // if there is no selection, then we insert, and set the curson inside it..
26407                 this.execCmd('styleWithCSS', false); 
26408                 break;
26409                 
26410         
26411             default:
26412                 break;
26413         }
26414         
26415         
26416         this.win.focus();
26417         this.execCmd(cmd, value);
26418         this.owner.fireEvent('editorevent', this);
26419         //this.updateToolbar();
26420         this.owner.deferFocus();
26421     },
26422
26423     /**
26424      * Executes a Midas editor command directly on the editor document.
26425      * For visual commands, you should use {@link #relayCmd} instead.
26426      * <b>This should only be called after the editor is initialized.</b>
26427      * @param {String} cmd The Midas command
26428      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
26429      */
26430     execCmd : function(cmd, value){
26431         this.doc.execCommand(cmd, false, value === undefined ? null : value);
26432         this.syncValue();
26433     },
26434  
26435  
26436    
26437     /**
26438      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
26439      * to insert tRoo.
26440      * @param {String} text | dom node.. 
26441      */
26442     insertAtCursor : function(text)
26443     {
26444         
26445         if(!this.activated){
26446             return;
26447         }
26448          
26449         if(Roo.isGecko || Roo.isOpera || Roo.isSafari){
26450             this.win.focus();
26451             
26452             
26453             // from jquery ui (MIT licenced)
26454             var range, node;
26455             var win = this.win;
26456             
26457             if (win.getSelection && win.getSelection().getRangeAt) {
26458                 
26459                 // delete the existing?
26460                 
26461                 this.createRange(this.getSelection()).deleteContents();
26462                 range = win.getSelection().getRangeAt(0);
26463                 node = typeof(text) == 'string' ? range.createContextualFragment(text) : text;
26464                 range.insertNode(node);
26465                 range = range.cloneRange();
26466                 range.collapse(false);
26467                  
26468                 win.getSelection().removeAllRanges();
26469                 win.getSelection().addRange(range);
26470                 
26471                 
26472                 
26473             } else if (win.document.selection && win.document.selection.createRange) {
26474                 // no firefox support
26475                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
26476                 win.document.selection.createRange().pasteHTML(txt);
26477             
26478             } else {
26479                 // no firefox support
26480                 var txt = typeof(text) == 'string' ? text : text.outerHTML;
26481                 this.execCmd('InsertHTML', txt);
26482             } 
26483             this.syncValue();
26484             
26485             this.deferFocus();
26486         }
26487     },
26488  // private
26489     mozKeyPress : function(e){
26490         if(e.ctrlKey){
26491             var c = e.getCharCode(), cmd;
26492           
26493             if(c > 0){
26494                 c = String.fromCharCode(c).toLowerCase();
26495                 switch(c){
26496                     case 'b':
26497                         cmd = 'bold';
26498                         break;
26499                     case 'i':
26500                         cmd = 'italic';
26501                         break;
26502                     
26503                     case 'u':
26504                         cmd = 'underline';
26505                         break;
26506                     
26507                     //case 'v':
26508                       //  this.cleanUpPaste.defer(100, this);
26509                       //  return;
26510                         
26511                 }
26512                 if(cmd){
26513                     
26514                     this.relayCmd(cmd);
26515                     //this.win.focus();
26516                     //this.execCmd(cmd);
26517                     //this.deferFocus();
26518                     e.preventDefault();
26519                 }
26520                 
26521             }
26522         }
26523     },
26524
26525     // private
26526     fixKeys : function(){ // load time branching for fastest keydown performance
26527         
26528         
26529         if(Roo.isIE){
26530             return function(e){
26531                 var k = e.getKey(), r;
26532                 if(k == e.TAB){
26533                     e.stopEvent();
26534                     r = this.doc.selection.createRange();
26535                     if(r){
26536                         r.collapse(true);
26537                         r.pasteHTML('&#160;&#160;&#160;&#160;');
26538                         this.deferFocus();
26539                     }
26540                     return;
26541                 }
26542                 /// this is handled by Roo.htmleditor.KeyEnter
26543                  /*
26544                 if(k == e.ENTER){
26545                     r = this.doc.selection.createRange();
26546                     if(r){
26547                         var target = r.parentElement();
26548                         if(!target || target.tagName.toLowerCase() != 'li'){
26549                             e.stopEvent();
26550                             r.pasteHTML('<br/>');
26551                             r.collapse(false);
26552                             r.select();
26553                         }
26554                     }
26555                 }
26556                 */
26557                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
26558                 //    this.cleanUpPaste.defer(100, this);
26559                 //    return;
26560                 //}
26561                 
26562                 
26563             };
26564         }else if(Roo.isOpera){
26565             return function(e){
26566                 var k = e.getKey();
26567                 if(k == e.TAB){
26568                     e.stopEvent();
26569                     this.win.focus();
26570                     this.execCmd('InsertHTML','&#160;&#160;&#160;&#160;');
26571                     this.deferFocus();
26572                 }
26573                
26574                 //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
26575                 //    this.cleanUpPaste.defer(100, this);
26576                  //   return;
26577                 //}
26578                 
26579             };
26580         }else if(Roo.isSafari){
26581             return function(e){
26582                 var k = e.getKey();
26583                 
26584                 if(k == e.TAB){
26585                     e.stopEvent();
26586                     this.execCmd('InsertText','\t');
26587                     this.deferFocus();
26588                     return;
26589                 }
26590                  this.mozKeyPress(e);
26591                 
26592                //if (String.fromCharCode(k).toLowerCase() == 'v') { // paste
26593                  //   this.cleanUpPaste.defer(100, this);
26594                  //   return;
26595                // }
26596                 
26597              };
26598         }
26599     }(),
26600     
26601     getAllAncestors: function()
26602     {
26603         var p = this.getSelectedNode();
26604         var a = [];
26605         if (!p) {
26606             a.push(p); // push blank onto stack..
26607             p = this.getParentElement();
26608         }
26609         
26610         
26611         while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
26612             a.push(p);
26613             p = p.parentNode;
26614         }
26615         a.push(this.doc.body);
26616         return a;
26617     },
26618     lastSel : false,
26619     lastSelNode : false,
26620     
26621     
26622     getSelection : function() 
26623     {
26624         this.assignDocWin();
26625         return Roo.lib.Selection.wrap(Roo.isIE ? this.doc.selection : this.win.getSelection(), this.doc);
26626     },
26627     /**
26628      * Select a dom node
26629      * @param {DomElement} node the node to select
26630      */
26631     selectNode : function(node, collapse)
26632     {
26633         var nodeRange = node.ownerDocument.createRange();
26634         try {
26635             nodeRange.selectNode(node);
26636         } catch (e) {
26637             nodeRange.selectNodeContents(node);
26638         }
26639         if (collapse === true) {
26640             nodeRange.collapse(true);
26641         }
26642         //
26643         var s = this.win.getSelection();
26644         s.removeAllRanges();
26645         s.addRange(nodeRange);
26646     },
26647     
26648     getSelectedNode: function() 
26649     {
26650         // this may only work on Gecko!!!
26651         
26652         // should we cache this!!!!
26653         
26654          
26655          
26656         var range = this.createRange(this.getSelection()).cloneRange();
26657         
26658         if (Roo.isIE) {
26659             var parent = range.parentElement();
26660             while (true) {
26661                 var testRange = range.duplicate();
26662                 testRange.moveToElementText(parent);
26663                 if (testRange.inRange(range)) {
26664                     break;
26665                 }
26666                 if ((parent.nodeType != 1) || (parent.tagName.toLowerCase() == 'body')) {
26667                     break;
26668                 }
26669                 parent = parent.parentElement;
26670             }
26671             return parent;
26672         }
26673         
26674         // is ancestor a text element.
26675         var ac =  range.commonAncestorContainer;
26676         if (ac.nodeType == 3) {
26677             ac = ac.parentNode;
26678         }
26679         
26680         var ar = ac.childNodes;
26681          
26682         var nodes = [];
26683         var other_nodes = [];
26684         var has_other_nodes = false;
26685         for (var i=0;i<ar.length;i++) {
26686             if ((ar[i].nodeType == 3) && (!ar[i].data.length)) { // empty text ? 
26687                 continue;
26688             }
26689             // fullly contained node.
26690             
26691             if (this.rangeIntersectsNode(range,ar[i]) && this.rangeCompareNode(range,ar[i]) == 3) {
26692                 nodes.push(ar[i]);
26693                 continue;
26694             }
26695             
26696             // probably selected..
26697             if ((ar[i].nodeType == 1) && this.rangeIntersectsNode(range,ar[i]) && (this.rangeCompareNode(range,ar[i]) > 0)) {
26698                 other_nodes.push(ar[i]);
26699                 continue;
26700             }
26701             // outer..
26702             if (!this.rangeIntersectsNode(range,ar[i])|| (this.rangeCompareNode(range,ar[i]) == 0))  {
26703                 continue;
26704             }
26705             
26706             
26707             has_other_nodes = true;
26708         }
26709         if (!nodes.length && other_nodes.length) {
26710             nodes= other_nodes;
26711         }
26712         if (has_other_nodes || !nodes.length || (nodes.length > 1)) {
26713             return false;
26714         }
26715         
26716         return nodes[0];
26717     },
26718     
26719     
26720     createRange: function(sel)
26721     {
26722         // this has strange effects when using with 
26723         // top toolbar - not sure if it's a great idea.
26724         //this.editor.contentWindow.focus();
26725         if (typeof sel != "undefined") {
26726             try {
26727                 return sel.getRangeAt ? sel.getRangeAt(0) : sel.createRange();
26728             } catch(e) {
26729                 return this.doc.createRange();
26730             }
26731         } else {
26732             return this.doc.createRange();
26733         }
26734     },
26735     getParentElement: function()
26736     {
26737         
26738         this.assignDocWin();
26739         var sel = Roo.isIE ? this.doc.selection : this.win.getSelection();
26740         
26741         var range = this.createRange(sel);
26742          
26743         try {
26744             var p = range.commonAncestorContainer;
26745             while (p.nodeType == 3) { // text node
26746                 p = p.parentNode;
26747             }
26748             return p;
26749         } catch (e) {
26750             return null;
26751         }
26752     
26753     },
26754     /***
26755      *
26756      * Range intersection.. the hard stuff...
26757      *  '-1' = before
26758      *  '0' = hits..
26759      *  '1' = after.
26760      *         [ -- selected range --- ]
26761      *   [fail]                        [fail]
26762      *
26763      *    basically..
26764      *      if end is before start or  hits it. fail.
26765      *      if start is after end or hits it fail.
26766      *
26767      *   if either hits (but other is outside. - then it's not 
26768      *   
26769      *    
26770      **/
26771     
26772     
26773     // @see http://www.thismuchiknow.co.uk/?p=64.
26774     rangeIntersectsNode : function(range, node)
26775     {
26776         var nodeRange = node.ownerDocument.createRange();
26777         try {
26778             nodeRange.selectNode(node);
26779         } catch (e) {
26780             nodeRange.selectNodeContents(node);
26781         }
26782     
26783         var rangeStartRange = range.cloneRange();
26784         rangeStartRange.collapse(true);
26785     
26786         var rangeEndRange = range.cloneRange();
26787         rangeEndRange.collapse(false);
26788     
26789         var nodeStartRange = nodeRange.cloneRange();
26790         nodeStartRange.collapse(true);
26791     
26792         var nodeEndRange = nodeRange.cloneRange();
26793         nodeEndRange.collapse(false);
26794     
26795         return rangeStartRange.compareBoundaryPoints(
26796                  Range.START_TO_START, nodeEndRange) == -1 &&
26797                rangeEndRange.compareBoundaryPoints(
26798                  Range.START_TO_START, nodeStartRange) == 1;
26799         
26800          
26801     },
26802     rangeCompareNode : function(range, node)
26803     {
26804         var nodeRange = node.ownerDocument.createRange();
26805         try {
26806             nodeRange.selectNode(node);
26807         } catch (e) {
26808             nodeRange.selectNodeContents(node);
26809         }
26810         
26811         
26812         range.collapse(true);
26813     
26814         nodeRange.collapse(true);
26815      
26816         var ss = range.compareBoundaryPoints( Range.START_TO_START, nodeRange);
26817         var ee = range.compareBoundaryPoints(  Range.END_TO_END, nodeRange);
26818          
26819         //Roo.log(node.tagName + ': ss='+ss +', ee='+ee)
26820         
26821         var nodeIsBefore   =  ss == 1;
26822         var nodeIsAfter    = ee == -1;
26823         
26824         if (nodeIsBefore && nodeIsAfter) {
26825             return 0; // outer
26826         }
26827         if (!nodeIsBefore && nodeIsAfter) {
26828             return 1; //right trailed.
26829         }
26830         
26831         if (nodeIsBefore && !nodeIsAfter) {
26832             return 2;  // left trailed.
26833         }
26834         // fully contined.
26835         return 3;
26836     },
26837  
26838     cleanWordChars : function(input) {// change the chars to hex code
26839         
26840        var swapCodes  = [ 
26841             [    8211, "&#8211;" ], 
26842             [    8212, "&#8212;" ], 
26843             [    8216,  "'" ],  
26844             [    8217, "'" ],  
26845             [    8220, '"' ],  
26846             [    8221, '"' ],  
26847             [    8226, "*" ],  
26848             [    8230, "..." ]
26849         ]; 
26850         var output = input;
26851         Roo.each(swapCodes, function(sw) { 
26852             var swapper = new RegExp("\\u" + sw[0].toString(16), "g"); // hex codes
26853             
26854             output = output.replace(swapper, sw[1]);
26855         });
26856         
26857         return output;
26858     },
26859     
26860      
26861     
26862         
26863     
26864     cleanUpChild : function (node)
26865     {
26866         
26867         new Roo.htmleditor.FilterComment({node : node});
26868         new Roo.htmleditor.FilterAttributes({
26869                 node : node,
26870                 attrib_black : this.ablack,
26871                 attrib_clean : this.aclean,
26872                 style_white : this.cwhite,
26873                 style_black : this.cblack
26874         });
26875         new Roo.htmleditor.FilterBlack({ node : node, tag : this.black});
26876         new Roo.htmleditor.FilterKeepChildren({node : node, tag : this.tag_remove} );
26877          
26878         
26879     },
26880     
26881     /**
26882      * Clean up MS wordisms...
26883      * @deprecated - use filter directly
26884      */
26885     cleanWord : function(node)
26886     {
26887         new Roo.htmleditor.FilterWord({ node : node ? node : this.doc.body });
26888         new Roo.htmleditor.FilterKeepChildren({node : node ? node : this.doc.body, tag : [ 'FONT', ':' ]} );
26889         
26890     },
26891    
26892     
26893     /**
26894
26895      * @deprecated - use filters
26896      */
26897     cleanTableWidths : function(node)
26898     {
26899         new Roo.htmleditor.FilterTableWidth({ node : node ? node : this.doc.body});
26900         
26901  
26902     },
26903     
26904      
26905         
26906     applyBlacklists : function()
26907     {
26908         var w = typeof(this.owner.white) != 'undefined' && this.owner.white ? this.owner.white  : [];
26909         var b = typeof(this.owner.black) != 'undefined' && this.owner.black ? this.owner.black :  [];
26910         
26911         this.aclean = typeof(this.owner.aclean) != 'undefined' && this.owner.aclean ? this.owner.aclean :  Roo.HtmlEditorCore.aclean;
26912         this.ablack = typeof(this.owner.ablack) != 'undefined' && this.owner.ablack ? this.owner.ablack :  Roo.HtmlEditorCore.ablack;
26913         this.tag_remove = typeof(this.owner.tag_remove) != 'undefined' && this.owner.tag_remove ? this.owner.tag_remove :  Roo.HtmlEditorCore.tag_remove;
26914         
26915         this.white = [];
26916         this.black = [];
26917         Roo.each(Roo.HtmlEditorCore.white, function(tag) {
26918             if (b.indexOf(tag) > -1) {
26919                 return;
26920             }
26921             this.white.push(tag);
26922             
26923         }, this);
26924         
26925         Roo.each(w, function(tag) {
26926             if (b.indexOf(tag) > -1) {
26927                 return;
26928             }
26929             if (this.white.indexOf(tag) > -1) {
26930                 return;
26931             }
26932             this.white.push(tag);
26933             
26934         }, this);
26935         
26936         
26937         Roo.each(Roo.HtmlEditorCore.black, function(tag) {
26938             if (w.indexOf(tag) > -1) {
26939                 return;
26940             }
26941             this.black.push(tag);
26942             
26943         }, this);
26944         
26945         Roo.each(b, function(tag) {
26946             if (w.indexOf(tag) > -1) {
26947                 return;
26948             }
26949             if (this.black.indexOf(tag) > -1) {
26950                 return;
26951             }
26952             this.black.push(tag);
26953             
26954         }, this);
26955         
26956         
26957         w = typeof(this.owner.cwhite) != 'undefined' && this.owner.cwhite ? this.owner.cwhite  : [];
26958         b = typeof(this.owner.cblack) != 'undefined' && this.owner.cblack ? this.owner.cblack :  [];
26959         
26960         this.cwhite = [];
26961         this.cblack = [];
26962         Roo.each(Roo.HtmlEditorCore.cwhite, function(tag) {
26963             if (b.indexOf(tag) > -1) {
26964                 return;
26965             }
26966             this.cwhite.push(tag);
26967             
26968         }, this);
26969         
26970         Roo.each(w, function(tag) {
26971             if (b.indexOf(tag) > -1) {
26972                 return;
26973             }
26974             if (this.cwhite.indexOf(tag) > -1) {
26975                 return;
26976             }
26977             this.cwhite.push(tag);
26978             
26979         }, this);
26980         
26981         
26982         Roo.each(Roo.HtmlEditorCore.cblack, function(tag) {
26983             if (w.indexOf(tag) > -1) {
26984                 return;
26985             }
26986             this.cblack.push(tag);
26987             
26988         }, this);
26989         
26990         Roo.each(b, function(tag) {
26991             if (w.indexOf(tag) > -1) {
26992                 return;
26993             }
26994             if (this.cblack.indexOf(tag) > -1) {
26995                 return;
26996             }
26997             this.cblack.push(tag);
26998             
26999         }, this);
27000     },
27001     
27002     setStylesheets : function(stylesheets)
27003     {
27004         if(typeof(stylesheets) == 'string'){
27005             Roo.get(this.iframe.contentDocument.head).createChild({
27006                 tag : 'link',
27007                 rel : 'stylesheet',
27008                 type : 'text/css',
27009                 href : stylesheets
27010             });
27011             
27012             return;
27013         }
27014         var _this = this;
27015      
27016         Roo.each(stylesheets, function(s) {
27017             if(!s.length){
27018                 return;
27019             }
27020             
27021             Roo.get(_this.iframe.contentDocument.head).createChild({
27022                 tag : 'link',
27023                 rel : 'stylesheet',
27024                 type : 'text/css',
27025                 href : s
27026             });
27027         });
27028
27029         
27030     },
27031     
27032     
27033     updateLanguage : function()
27034     {
27035         if (!this.iframe || !this.iframe.contentDocument) {
27036             return;
27037         }
27038         Roo.get(this.iframe.contentDocument.body).attr("lang", this.language);
27039     },
27040     
27041     
27042     removeStylesheets : function()
27043     {
27044         var _this = this;
27045         
27046         Roo.each(Roo.get(_this.iframe.contentDocument.head).select('link[rel=stylesheet]', true).elements, function(s){
27047             s.remove();
27048         });
27049     },
27050     
27051     setStyle : function(style)
27052     {
27053         Roo.get(this.iframe.contentDocument.head).createChild({
27054             tag : 'style',
27055             type : 'text/css',
27056             html : style
27057         });
27058
27059         return;
27060     }
27061     
27062     // hide stuff that is not compatible
27063     /**
27064      * @event blur
27065      * @hide
27066      */
27067     /**
27068      * @event change
27069      * @hide
27070      */
27071     /**
27072      * @event focus
27073      * @hide
27074      */
27075     /**
27076      * @event specialkey
27077      * @hide
27078      */
27079     /**
27080      * @cfg {String} fieldClass @hide
27081      */
27082     /**
27083      * @cfg {String} focusClass @hide
27084      */
27085     /**
27086      * @cfg {String} autoCreate @hide
27087      */
27088     /**
27089      * @cfg {String} inputType @hide
27090      */
27091     /**
27092      * @cfg {String} invalidClass @hide
27093      */
27094     /**
27095      * @cfg {String} invalidText @hide
27096      */
27097     /**
27098      * @cfg {String} msgFx @hide
27099      */
27100     /**
27101      * @cfg {String} validateOnBlur @hide
27102      */
27103 });
27104
27105 Roo.HtmlEditorCore.white = [
27106         'AREA', 'BR', 'IMG', 'INPUT', 'HR', 'WBR',
27107         
27108        'ADDRESS', 'BLOCKQUOTE', 'CENTER', 'DD',      'DIR',       'DIV', 
27109        'DL',      'DT',         'H1',     'H2',      'H3',        'H4', 
27110        'H5',      'H6',         'HR',     'ISINDEX', 'LISTING',   'MARQUEE', 
27111        'MENU',    'MULTICOL',   'OL',     'P',       'PLAINTEXT', 'PRE', 
27112        'TABLE',   'UL',         'XMP', 
27113        
27114        'CAPTION', 'COL', 'COLGROUP', 'TBODY', 'TD', 'TFOOT', 'TH', 
27115       'THEAD',   'TR', 
27116      
27117       'DIR', 'MENU', 'OL', 'UL', 'DL',
27118        
27119       'EMBED',  'OBJECT'
27120 ];
27121
27122
27123 Roo.HtmlEditorCore.black = [
27124     //    'embed',  'object', // enable - backend responsiblity to clean thiese
27125         'APPLET', // 
27126         'BASE',   'BASEFONT', 'BGSOUND', 'BLINK',  'BODY', 
27127         'FRAME',  'FRAMESET', 'HEAD',    'HTML',   'ILAYER', 
27128         'IFRAME', 'LAYER',  'LINK',     'META',    'OBJECT',   
27129         'SCRIPT', 'STYLE' ,'TITLE',  'XML',
27130         //'FONT' // CLEAN LATER..
27131         'COLGROUP', 'COL'   // messy tables.
27132         
27133         
27134 ];
27135 Roo.HtmlEditorCore.clean = [ // ?? needed???
27136      'SCRIPT', 'STYLE', 'TITLE', 'XML'
27137 ];
27138 Roo.HtmlEditorCore.tag_remove = [
27139     'FONT', 'TBODY'  
27140 ];
27141 // attributes..
27142
27143 Roo.HtmlEditorCore.ablack = [
27144     'on'
27145 ];
27146     
27147 Roo.HtmlEditorCore.aclean = [ 
27148     'action', 'background', 'codebase', 'dynsrc', 'href', 'lowsrc' 
27149 ];
27150
27151 // protocols..
27152 Roo.HtmlEditorCore.pwhite= [
27153         'http',  'https',  'mailto'
27154 ];
27155
27156 // white listed style attributes.
27157 Roo.HtmlEditorCore.cwhite= [
27158       //  'text-align', /// default is to allow most things..
27159       
27160          
27161 //        'font-size'//??
27162 ];
27163
27164 // black listed style attributes.
27165 Roo.HtmlEditorCore.cblack= [
27166       //  'font-size' -- this can be set by the project 
27167 ];
27168
27169
27170
27171
27172     //<script type="text/javascript">
27173
27174 /*
27175  * Ext JS Library 1.1.1
27176  * Copyright(c) 2006-2007, Ext JS, LLC.
27177  * Licence LGPL
27178  * 
27179  */
27180  
27181  
27182 Roo.form.HtmlEditor = function(config){
27183     
27184     
27185     
27186     Roo.form.HtmlEditor.superclass.constructor.call(this, config);
27187     
27188     if (!this.toolbars) {
27189         this.toolbars = [];
27190     }
27191     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
27192     
27193     
27194 };
27195
27196 /**
27197  * @class Roo.form.HtmlEditor
27198  * @extends Roo.form.Field
27199  * Provides a lightweight HTML Editor component.
27200  *
27201  * This has been tested on Fireforx / Chrome.. IE may not be so great..
27202  * 
27203  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
27204  * supported by this editor.</b><br/><br/>
27205  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
27206  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
27207  */
27208 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
27209     /**
27210      * @cfg {Boolean} clearUp
27211      */
27212     clearUp : true,
27213       /**
27214      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
27215      */
27216     toolbars : false,
27217    
27218      /**
27219      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
27220      *                        Roo.resizable.
27221      */
27222     resizable : false,
27223      /**
27224      * @cfg {Number} height (in pixels)
27225      */   
27226     height: 300,
27227    /**
27228      * @cfg {Number} width (in pixels)
27229      */   
27230     width: 500,
27231     
27232     /**
27233      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea  rootURL + '/roojs1/css/undoreset.css',   .
27234      * 
27235      */
27236     stylesheets: false,
27237     
27238     
27239      /**
27240      * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
27241      * 
27242      */
27243     cblack: false,
27244     /**
27245      * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
27246      * 
27247      */
27248     cwhite: false,
27249     
27250      /**
27251      * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
27252      * 
27253      */
27254     black: false,
27255     /**
27256      * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
27257      * 
27258      */
27259     white: false,
27260     /**
27261      * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
27262      */
27263     allowComments: false,
27264     /**
27265      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
27266      */
27267     enableBlocks : true,
27268     
27269     /**
27270      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
27271      *         if you are doing an email editor, this probably needs disabling, it's designed
27272      */
27273     autoClean: true,
27274     /**
27275      * @cfg {string} bodyCls default '' default classes to add to body of editable area - usually undoreset is a good start..
27276      */
27277     bodyCls : '',
27278     /**
27279      * @cfg {String} language default en - language of text (usefull for rtl languages)
27280      * 
27281      */
27282     language: 'en',
27283     
27284      
27285     // id of frame..
27286     frameId: false,
27287     
27288     // private properties
27289     validationEvent : false,
27290     deferHeight: true,
27291     initialized : false,
27292     activated : false,
27293     
27294     onFocus : Roo.emptyFn,
27295     iframePad:3,
27296     hideMode:'offsets',
27297     
27298     actionMode : 'container', // defaults to hiding it...
27299     
27300     defaultAutoCreate : { // modified by initCompnoent..
27301         tag: "textarea",
27302         style:"width:500px;height:300px;",
27303         autocomplete: "new-password"
27304     },
27305
27306     // private
27307     initComponent : function(){
27308         this.addEvents({
27309             /**
27310              * @event initialize
27311              * Fires when the editor is fully initialized (including the iframe)
27312              * @param {HtmlEditor} this
27313              */
27314             initialize: true,
27315             /**
27316              * @event activate
27317              * Fires when the editor is first receives the focus. Any insertion must wait
27318              * until after this event.
27319              * @param {HtmlEditor} this
27320              */
27321             activate: true,
27322              /**
27323              * @event beforesync
27324              * Fires before the textarea is updated with content from the editor iframe. Return false
27325              * to cancel the sync.
27326              * @param {HtmlEditor} this
27327              * @param {String} html
27328              */
27329             beforesync: true,
27330              /**
27331              * @event beforepush
27332              * Fires before the iframe editor is updated with content from the textarea. Return false
27333              * to cancel the push.
27334              * @param {HtmlEditor} this
27335              * @param {String} html
27336              */
27337             beforepush: true,
27338              /**
27339              * @event sync
27340              * Fires when the textarea is updated with content from the editor iframe.
27341              * @param {HtmlEditor} this
27342              * @param {String} html
27343              */
27344             sync: true,
27345              /**
27346              * @event push
27347              * Fires when the iframe editor is updated with content from the textarea.
27348              * @param {HtmlEditor} this
27349              * @param {String} html
27350              */
27351             push: true,
27352              /**
27353              * @event editmodechange
27354              * Fires when the editor switches edit modes
27355              * @param {HtmlEditor} this
27356              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
27357              */
27358             editmodechange: true,
27359             /**
27360              * @event editorevent
27361              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
27362              * @param {HtmlEditor} this
27363              */
27364             editorevent: true,
27365             /**
27366              * @event firstfocus
27367              * Fires when on first focus - needed by toolbars..
27368              * @param {HtmlEditor} this
27369              */
27370             firstfocus: true,
27371             /**
27372              * @event autosave
27373              * Auto save the htmlEditor value as a file into Events
27374              * @param {HtmlEditor} this
27375              */
27376             autosave: true,
27377             /**
27378              * @event savedpreview
27379              * preview the saved version of htmlEditor
27380              * @param {HtmlEditor} this
27381              */
27382             savedpreview: true,
27383             
27384             /**
27385             * @event stylesheetsclick
27386             * Fires when press the Sytlesheets button
27387             * @param {Roo.HtmlEditorCore} this
27388             */
27389             stylesheetsclick: true,
27390             /**
27391             * @event paste
27392             * Fires when press user pastes into the editor
27393             * @param {Roo.HtmlEditorCore} this
27394             */
27395             paste: true 
27396             
27397         });
27398         this.defaultAutoCreate =  {
27399             tag: "textarea",
27400             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
27401             autocomplete: "new-password"
27402         };
27403     },
27404
27405     /**
27406      * Protected method that will not generally be called directly. It
27407      * is called when the editor creates its toolbar. Override this method if you need to
27408      * add custom toolbar buttons.
27409      * @param {HtmlEditor} editor
27410      */
27411     createToolbar : function(editor){
27412         Roo.log("create toolbars");
27413         if (!editor.toolbars || !editor.toolbars.length) {
27414             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
27415         }
27416         
27417         for (var i =0 ; i < editor.toolbars.length;i++) {
27418             editor.toolbars[i] = Roo.factory(
27419                     typeof(editor.toolbars[i]) == 'string' ?
27420                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
27421                 Roo.form.HtmlEditor);
27422             editor.toolbars[i].init(editor);
27423         }
27424          
27425         
27426     },
27427     /**
27428      * get the Context selected node
27429      * @returns {DomElement|boolean} selected node if active or false if none
27430      * 
27431      */
27432     getSelectedNode : function()
27433     {
27434         if (this.toolbars.length < 2 || !this.toolbars[1].tb) {
27435             return false;
27436         }
27437         return this.toolbars[1].tb.selectedNode;
27438     
27439     },
27440     // private
27441     onRender : function(ct, position)
27442     {
27443         var _t = this;
27444         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
27445         
27446         this.wrap = this.el.wrap({
27447             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
27448         });
27449         
27450         this.editorcore.onRender(ct, position);
27451          
27452         if (this.resizable) {
27453             this.resizeEl = new Roo.Resizable(this.wrap, {
27454                 pinned : true,
27455                 wrap: true,
27456                 dynamic : true,
27457                 minHeight : this.height,
27458                 height: this.height,
27459                 handles : this.resizable,
27460                 width: this.width,
27461                 listeners : {
27462                     resize : function(r, w, h) {
27463                         _t.onResize(w,h); // -something
27464                     }
27465                 }
27466             });
27467             
27468         }
27469         this.createToolbar(this);
27470        
27471         
27472         if(!this.width){
27473             this.setSize(this.wrap.getSize());
27474         }
27475         if (this.resizeEl) {
27476             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
27477             // should trigger onReize..
27478         }
27479         
27480         this.keyNav = new Roo.KeyNav(this.el, {
27481             
27482             "tab" : function(e){
27483                 e.preventDefault();
27484                 
27485                 var value = this.getValue();
27486                 
27487                 var start = this.el.dom.selectionStart;
27488                 var end = this.el.dom.selectionEnd;
27489                 
27490                 if(!e.shiftKey){
27491                     
27492                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
27493                     this.el.dom.setSelectionRange(end + 1, end + 1);
27494                     return;
27495                 }
27496                 
27497                 var f = value.substring(0, start).split("\t");
27498                 
27499                 if(f.pop().length != 0){
27500                     return;
27501                 }
27502                 
27503                 this.setValue(f.join("\t") + value.substring(end));
27504                 this.el.dom.setSelectionRange(start - 1, start - 1);
27505                 
27506             },
27507             
27508             "home" : function(e){
27509                 e.preventDefault();
27510                 
27511                 var curr = this.el.dom.selectionStart;
27512                 var lines = this.getValue().split("\n");
27513                 
27514                 if(!lines.length){
27515                     return;
27516                 }
27517                 
27518                 if(e.ctrlKey){
27519                     this.el.dom.setSelectionRange(0, 0);
27520                     return;
27521                 }
27522                 
27523                 var pos = 0;
27524                 
27525                 for (var i = 0; i < lines.length;i++) {
27526                     pos += lines[i].length;
27527                     
27528                     if(i != 0){
27529                         pos += 1;
27530                     }
27531                     
27532                     if(pos < curr){
27533                         continue;
27534                     }
27535                     
27536                     pos -= lines[i].length;
27537                     
27538                     break;
27539                 }
27540                 
27541                 if(!e.shiftKey){
27542                     this.el.dom.setSelectionRange(pos, pos);
27543                     return;
27544                 }
27545                 
27546                 this.el.dom.selectionStart = pos;
27547                 this.el.dom.selectionEnd = curr;
27548             },
27549             
27550             "end" : function(e){
27551                 e.preventDefault();
27552                 
27553                 var curr = this.el.dom.selectionStart;
27554                 var lines = this.getValue().split("\n");
27555                 
27556                 if(!lines.length){
27557                     return;
27558                 }
27559                 
27560                 if(e.ctrlKey){
27561                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
27562                     return;
27563                 }
27564                 
27565                 var pos = 0;
27566                 
27567                 for (var i = 0; i < lines.length;i++) {
27568                     
27569                     pos += lines[i].length;
27570                     
27571                     if(i != 0){
27572                         pos += 1;
27573                     }
27574                     
27575                     if(pos < curr){
27576                         continue;
27577                     }
27578                     
27579                     break;
27580                 }
27581                 
27582                 if(!e.shiftKey){
27583                     this.el.dom.setSelectionRange(pos, pos);
27584                     return;
27585                 }
27586                 
27587                 this.el.dom.selectionStart = curr;
27588                 this.el.dom.selectionEnd = pos;
27589             },
27590
27591             scope : this,
27592
27593             doRelay : function(foo, bar, hname){
27594                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
27595             },
27596
27597             forceKeyDown: true
27598         });
27599         
27600 //        if(this.autosave && this.w){
27601 //            this.autoSaveFn = setInterval(this.autosave, 1000);
27602 //        }
27603     },
27604
27605     // private
27606     onResize : function(w, h)
27607     {
27608         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
27609         var ew = false;
27610         var eh = false;
27611         
27612         if(this.el ){
27613             if(typeof w == 'number'){
27614                 var aw = w - this.wrap.getFrameWidth('lr');
27615                 this.el.setWidth(this.adjustWidth('textarea', aw));
27616                 ew = aw;
27617             }
27618             if(typeof h == 'number'){
27619                 var tbh = 0;
27620                 for (var i =0; i < this.toolbars.length;i++) {
27621                     // fixme - ask toolbars for heights?
27622                     tbh += this.toolbars[i].tb.el.getHeight();
27623                     if (this.toolbars[i].footer) {
27624                         tbh += this.toolbars[i].footer.el.getHeight();
27625                     }
27626                 }
27627                 
27628                 
27629                 
27630                 
27631                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
27632                 ah -= 5; // knock a few pixes off for look..
27633 //                Roo.log(ah);
27634                 this.el.setHeight(this.adjustWidth('textarea', ah));
27635                 var eh = ah;
27636             }
27637         }
27638         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
27639         this.editorcore.onResize(ew,eh);
27640         
27641     },
27642
27643     /**
27644      * Toggles the editor between standard and source edit mode.
27645      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
27646      */
27647     toggleSourceEdit : function(sourceEditMode)
27648     {
27649         this.editorcore.toggleSourceEdit(sourceEditMode);
27650         
27651         if(this.editorcore.sourceEditMode){
27652             Roo.log('editor - showing textarea');
27653             
27654 //            Roo.log('in');
27655 //            Roo.log(this.syncValue());
27656             this.editorcore.syncValue();
27657             this.el.removeClass('x-hidden');
27658             this.el.dom.removeAttribute('tabIndex');
27659             this.el.focus();
27660             this.el.dom.scrollTop = 0;
27661             
27662             
27663             for (var i = 0; i < this.toolbars.length; i++) {
27664                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
27665                     this.toolbars[i].tb.hide();
27666                     this.toolbars[i].footer.hide();
27667                 }
27668             }
27669             
27670         }else{
27671             Roo.log('editor - hiding textarea');
27672 //            Roo.log('out')
27673 //            Roo.log(this.pushValue()); 
27674             this.editorcore.pushValue();
27675             
27676             this.el.addClass('x-hidden');
27677             this.el.dom.setAttribute('tabIndex', -1);
27678             
27679             for (var i = 0; i < this.toolbars.length; i++) {
27680                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
27681                     this.toolbars[i].tb.show();
27682                     this.toolbars[i].footer.show();
27683                 }
27684             }
27685             
27686             //this.deferFocus();
27687         }
27688         
27689         this.setSize(this.wrap.getSize());
27690         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
27691         
27692         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
27693     },
27694  
27695     // private (for BoxComponent)
27696     adjustSize : Roo.BoxComponent.prototype.adjustSize,
27697
27698     // private (for BoxComponent)
27699     getResizeEl : function(){
27700         return this.wrap;
27701     },
27702
27703     // private (for BoxComponent)
27704     getPositionEl : function(){
27705         return this.wrap;
27706     },
27707
27708     // private
27709     initEvents : function(){
27710         this.originalValue = this.getValue();
27711     },
27712
27713     /**
27714      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
27715      * @method
27716      */
27717     markInvalid : Roo.emptyFn,
27718     /**
27719      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
27720      * @method
27721      */
27722     clearInvalid : Roo.emptyFn,
27723
27724     setValue : function(v){
27725         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
27726         this.editorcore.pushValue();
27727     },
27728
27729     /**
27730      * update the language in the body - really done by core
27731      * @param {String} language - eg. en / ar / zh-CN etc..
27732      */
27733     updateLanguage : function(lang)
27734     {
27735         this.language = lang;
27736         this.editorcore.language = lang;
27737         this.editorcore.updateLanguage();
27738      
27739     },
27740     // private
27741     deferFocus : function(){
27742         this.focus.defer(10, this);
27743     },
27744
27745     // doc'ed in Field
27746     focus : function(){
27747         this.editorcore.focus();
27748         
27749     },
27750       
27751
27752     // private
27753     onDestroy : function(){
27754         
27755         
27756         
27757         if(this.rendered){
27758             
27759             for (var i =0; i < this.toolbars.length;i++) {
27760                 // fixme - ask toolbars for heights?
27761                 this.toolbars[i].onDestroy();
27762             }
27763             
27764             this.wrap.dom.innerHTML = '';
27765             this.wrap.remove();
27766         }
27767     },
27768
27769     // private
27770     onFirstFocus : function(){
27771         //Roo.log("onFirstFocus");
27772         this.editorcore.onFirstFocus();
27773          for (var i =0; i < this.toolbars.length;i++) {
27774             this.toolbars[i].onFirstFocus();
27775         }
27776         
27777     },
27778     
27779     // private
27780     syncValue : function()
27781     {
27782         this.editorcore.syncValue();
27783     },
27784     
27785     pushValue : function()
27786     {
27787         this.editorcore.pushValue();
27788     },
27789     
27790     setStylesheets : function(stylesheets)
27791     {
27792         this.editorcore.setStylesheets(stylesheets);
27793     },
27794     
27795     removeStylesheets : function()
27796     {
27797         this.editorcore.removeStylesheets();
27798     }
27799      
27800     
27801     // hide stuff that is not compatible
27802     /**
27803      * @event blur
27804      * @hide
27805      */
27806     /**
27807      * @event change
27808      * @hide
27809      */
27810     /**
27811      * @event focus
27812      * @hide
27813      */
27814     /**
27815      * @event specialkey
27816      * @hide
27817      */
27818     /**
27819      * @cfg {String} fieldClass @hide
27820      */
27821     /**
27822      * @cfg {String} focusClass @hide
27823      */
27824     /**
27825      * @cfg {String} autoCreate @hide
27826      */
27827     /**
27828      * @cfg {String} inputType @hide
27829      */
27830     /**
27831      * @cfg {String} invalidClass @hide
27832      */
27833     /**
27834      * @cfg {String} invalidText @hide
27835      */
27836     /**
27837      * @cfg {String} msgFx @hide
27838      */
27839     /**
27840      * @cfg {String} validateOnBlur @hide
27841      */
27842 });
27843  
27844     /*
27845  * Based on
27846  * Ext JS Library 1.1.1
27847  * Copyright(c) 2006-2007, Ext JS, LLC.
27848  *  
27849  
27850  */
27851
27852 /**
27853  * @class Roo.form.HtmlEditor.ToolbarStandard
27854  * Basic Toolbar
27855
27856  * Usage:
27857  *
27858  new Roo.form.HtmlEditor({
27859     ....
27860     toolbars : [
27861         new Roo.form.HtmlEditorToolbar1({
27862             disable : { fonts: 1 , format: 1, ..., ... , ...],
27863             btns : [ .... ]
27864         })
27865     }
27866      
27867  * 
27868  * @cfg {Object} disable List of elements to disable..
27869  * @cfg {Roo.Toolbar.Item|Roo.Toolbar.Button|Roo.Toolbar.SplitButton|Roo.form.Field} btns[] List of additional buttons.
27870  * 
27871  * 
27872  * NEEDS Extra CSS? 
27873  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
27874  */
27875  
27876 Roo.form.HtmlEditor.ToolbarStandard = function(config)
27877 {
27878     
27879     Roo.apply(this, config);
27880     
27881     // default disabled, based on 'good practice'..
27882     this.disable = this.disable || {};
27883     Roo.applyIf(this.disable, {
27884         fontSize : true,
27885         colors : true,
27886         specialElements : true
27887     });
27888     
27889     
27890     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
27891     // dont call parent... till later.
27892 }
27893
27894 Roo.form.HtmlEditor.ToolbarStandard.prototype = {
27895     
27896     tb: false,
27897     
27898     rendered: false,
27899     
27900     editor : false,
27901     editorcore : false,
27902     /**
27903      * @cfg {Object} disable  List of toolbar elements to disable
27904          
27905      */
27906     disable : false,
27907     
27908     
27909      /**
27910      * @cfg {String} createLinkText The default text for the create link prompt
27911      */
27912     createLinkText : 'Please enter the URL for the link:',
27913     /**
27914      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
27915      */
27916     defaultLinkValue : 'http:/'+'/',
27917    
27918     
27919       /**
27920      * @cfg {Array} fontFamilies An array of available font families
27921      */
27922     fontFamilies : [
27923         'Arial',
27924         'Courier New',
27925         'Tahoma',
27926         'Times New Roman',
27927         'Verdana'
27928     ],
27929     
27930     specialChars : [
27931            "&#169;",
27932           "&#174;",     
27933           "&#8482;",    
27934           "&#163;" ,    
27935          // "&#8212;",    
27936           "&#8230;",    
27937           "&#247;" ,    
27938         //  "&#225;" ,     ?? a acute?
27939            "&#8364;"    , //Euro
27940        //   "&#8220;"    ,
27941         //  "&#8221;"    ,
27942         //  "&#8226;"    ,
27943           "&#176;"  //   , // degrees
27944
27945          // "&#233;"     , // e ecute
27946          // "&#250;"     , // u ecute?
27947     ],
27948     
27949     specialElements : [
27950         {
27951             text: "Insert Table",
27952             xtype: 'MenuItem',
27953             xns : Roo.Menu,
27954             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
27955                 
27956         },
27957         {    
27958             text: "Insert Image",
27959             xtype: 'MenuItem',
27960             xns : Roo.Menu,
27961             ihtml : '<img src="about:blank"/>'
27962             
27963         }
27964         
27965          
27966     ],
27967     
27968     
27969     inputElements : [ 
27970             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
27971             "input:submit", "input:button", "select", "textarea", "label" ],
27972     formats : [
27973         ["p"] ,  
27974         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
27975         ["pre"],[ "code"], 
27976         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
27977         ['div'],['span'],
27978         ['sup'],['sub']
27979     ],
27980     
27981     cleanStyles : [
27982         "font-size"
27983     ],
27984      /**
27985      * @cfg {String} defaultFont default font to use.
27986      */
27987     defaultFont: 'tahoma',
27988    
27989     fontSelect : false,
27990     
27991     
27992     formatCombo : false,
27993     
27994     init : function(editor)
27995     {
27996         this.editor = editor;
27997         this.editorcore = editor.editorcore ? editor.editorcore : editor;
27998         var editorcore = this.editorcore;
27999         
28000         var _t = this;
28001         
28002         var fid = editorcore.frameId;
28003         var etb = this;
28004         function btn(id, toggle, handler){
28005             var xid = fid + '-'+ id ;
28006             return {
28007                 id : xid,
28008                 cmd : id,
28009                 cls : 'x-btn-icon x-edit-'+id,
28010                 enableToggle:toggle !== false,
28011                 scope: _t, // was editor...
28012                 handler:handler||_t.relayBtnCmd,
28013                 clickEvent:'mousedown',
28014                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
28015                 tabIndex:-1
28016             };
28017         }
28018         
28019         
28020         
28021         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
28022         this.tb = tb;
28023          // stop form submits
28024         tb.el.on('click', function(e){
28025             e.preventDefault(); // what does this do?
28026         });
28027
28028         if(!this.disable.font) { // && !Roo.isSafari){
28029             /* why no safari for fonts 
28030             editor.fontSelect = tb.el.createChild({
28031                 tag:'select',
28032                 tabIndex: -1,
28033                 cls:'x-font-select',
28034                 html: this.createFontOptions()
28035             });
28036             
28037             editor.fontSelect.on('change', function(){
28038                 var font = editor.fontSelect.dom.value;
28039                 editor.relayCmd('fontname', font);
28040                 editor.deferFocus();
28041             }, editor);
28042             
28043             tb.add(
28044                 editor.fontSelect.dom,
28045                 '-'
28046             );
28047             */
28048             
28049         };
28050         if(!this.disable.formats){
28051             this.formatCombo = new Roo.form.ComboBox({
28052                 store: new Roo.data.SimpleStore({
28053                     id : 'tag',
28054                     fields: ['tag'],
28055                     data : this.formats // from states.js
28056                 }),
28057                 blockFocus : true,
28058                 name : '',
28059                 //autoCreate : {tag: "div",  size: "20"},
28060                 displayField:'tag',
28061                 typeAhead: false,
28062                 mode: 'local',
28063                 editable : false,
28064                 triggerAction: 'all',
28065                 emptyText:'Add tag',
28066                 selectOnFocus:true,
28067                 width:135,
28068                 listeners : {
28069                     'select': function(c, r, i) {
28070                         editorcore.insertTag(r.get('tag'));
28071                         editor.focus();
28072                     }
28073                 }
28074
28075             });
28076             tb.addField(this.formatCombo);
28077             
28078         }
28079         
28080         if(!this.disable.format){
28081             tb.add(
28082                 btn('bold'),
28083                 btn('italic'),
28084                 btn('underline'),
28085                 btn('strikethrough')
28086             );
28087         };
28088         if(!this.disable.fontSize){
28089             tb.add(
28090                 '-',
28091                 
28092                 
28093                 btn('increasefontsize', false, editorcore.adjustFont),
28094                 btn('decreasefontsize', false, editorcore.adjustFont)
28095             );
28096         };
28097         
28098         
28099         if(!this.disable.colors){
28100             tb.add(
28101                 '-', {
28102                     id:editorcore.frameId +'-forecolor',
28103                     cls:'x-btn-icon x-edit-forecolor',
28104                     clickEvent:'mousedown',
28105                     tooltip: this.buttonTips['forecolor'] || undefined,
28106                     tabIndex:-1,
28107                     menu : new Roo.menu.ColorMenu({
28108                         allowReselect: true,
28109                         focus: Roo.emptyFn,
28110                         value:'000000',
28111                         plain:true,
28112                         selectHandler: function(cp, color){
28113                             editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
28114                             editor.deferFocus();
28115                         },
28116                         scope: editorcore,
28117                         clickEvent:'mousedown'
28118                     })
28119                 }, {
28120                     id:editorcore.frameId +'backcolor',
28121                     cls:'x-btn-icon x-edit-backcolor',
28122                     clickEvent:'mousedown',
28123                     tooltip: this.buttonTips['backcolor'] || undefined,
28124                     tabIndex:-1,
28125                     menu : new Roo.menu.ColorMenu({
28126                         focus: Roo.emptyFn,
28127                         value:'FFFFFF',
28128                         plain:true,
28129                         allowReselect: true,
28130                         selectHandler: function(cp, color){
28131                             if(Roo.isGecko){
28132                                 editorcore.execCmd('useCSS', false);
28133                                 editorcore.execCmd('hilitecolor', color);
28134                                 editorcore.execCmd('useCSS', true);
28135                                 editor.deferFocus();
28136                             }else{
28137                                 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
28138                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
28139                                 editor.deferFocus();
28140                             }
28141                         },
28142                         scope:editorcore,
28143                         clickEvent:'mousedown'
28144                     })
28145                 }
28146             );
28147         };
28148         // now add all the items...
28149         
28150
28151         if(!this.disable.alignments){
28152             tb.add(
28153                 '-',
28154                 btn('justifyleft'),
28155                 btn('justifycenter'),
28156                 btn('justifyright')
28157             );
28158         };
28159
28160         //if(!Roo.isSafari){
28161             if(!this.disable.links){
28162                 tb.add(
28163                     '-',
28164                     btn('createlink', false, this.createLink)    /// MOVE TO HERE?!!?!?!?!
28165                 );
28166             };
28167
28168             if(!this.disable.lists){
28169                 tb.add(
28170                     '-',
28171                     btn('insertorderedlist'),
28172                     btn('insertunorderedlist')
28173                 );
28174             }
28175             if(!this.disable.sourceEdit){
28176                 tb.add(
28177                     '-',
28178                     btn('sourceedit', true, function(btn){
28179                         this.toggleSourceEdit(btn.pressed);
28180                     })
28181                 );
28182             }
28183         //}
28184         
28185         var smenu = { };
28186         // special menu.. - needs to be tidied up..
28187         if (!this.disable.special) {
28188             smenu = {
28189                 text: "&#169;",
28190                 cls: 'x-edit-none',
28191                 
28192                 menu : {
28193                     items : []
28194                 }
28195             };
28196             for (var i =0; i < this.specialChars.length; i++) {
28197                 smenu.menu.items.push({
28198                     
28199                     html: this.specialChars[i],
28200                     handler: function(a,b) {
28201                         editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
28202                         //editor.insertAtCursor(a.html);
28203                         
28204                     },
28205                     tabIndex:-1
28206                 });
28207             }
28208             
28209             
28210             tb.add(smenu);
28211             
28212             
28213         }
28214         
28215         var cmenu = { };
28216         if (!this.disable.cleanStyles) {
28217             cmenu = {
28218                 cls: 'x-btn-icon x-btn-clear',
28219                 
28220                 menu : {
28221                     items : []
28222                 }
28223             };
28224             for (var i =0; i < this.cleanStyles.length; i++) {
28225                 cmenu.menu.items.push({
28226                     actiontype : this.cleanStyles[i],
28227                     html: 'Remove ' + this.cleanStyles[i],
28228                     handler: function(a,b) {
28229 //                        Roo.log(a);
28230 //                        Roo.log(b);
28231                         var c = Roo.get(editorcore.doc.body);
28232                         c.select('[style]').each(function(s) {
28233                             s.dom.style.removeProperty(a.actiontype);
28234                         });
28235                         editorcore.syncValue();
28236                     },
28237                     tabIndex:-1
28238                 });
28239             }
28240             cmenu.menu.items.push({
28241                 actiontype : 'tablewidths',
28242                 html: 'Remove Table Widths',
28243                 handler: function(a,b) {
28244                     editorcore.cleanTableWidths();
28245                     editorcore.syncValue();
28246                 },
28247                 tabIndex:-1
28248             });
28249             cmenu.menu.items.push({
28250                 actiontype : 'word',
28251                 html: 'Remove MS Word Formating',
28252                 handler: function(a,b) {
28253                     editorcore.cleanWord();
28254                     editorcore.syncValue();
28255                 },
28256                 tabIndex:-1
28257             });
28258             
28259             cmenu.menu.items.push({
28260                 actiontype : 'all',
28261                 html: 'Remove All Styles',
28262                 handler: function(a,b) {
28263                     
28264                     var c = Roo.get(editorcore.doc.body);
28265                     c.select('[style]').each(function(s) {
28266                         s.dom.removeAttribute('style');
28267                     });
28268                     editorcore.syncValue();
28269                 },
28270                 tabIndex:-1
28271             });
28272             
28273             cmenu.menu.items.push({
28274                 actiontype : 'all',
28275                 html: 'Remove All CSS Classes',
28276                 handler: function(a,b) {
28277                     
28278                     var c = Roo.get(editorcore.doc.body);
28279                     c.select('[class]').each(function(s) {
28280                         s.dom.removeAttribute('class');
28281                     });
28282                     editorcore.cleanWord();
28283                     editorcore.syncValue();
28284                 },
28285                 tabIndex:-1
28286             });
28287             
28288              cmenu.menu.items.push({
28289                 actiontype : 'tidy',
28290                 html: 'Tidy HTML Source',
28291                 handler: function(a,b) {
28292                     new Roo.htmleditor.Tidy(editorcore.doc.body);
28293                     editorcore.syncValue();
28294                 },
28295                 tabIndex:-1
28296             });
28297             
28298             
28299             tb.add(cmenu);
28300         }
28301          
28302         if (!this.disable.specialElements) {
28303             var semenu = {
28304                 text: "Other;",
28305                 cls: 'x-edit-none',
28306                 menu : {
28307                     items : []
28308                 }
28309             };
28310             for (var i =0; i < this.specialElements.length; i++) {
28311                 semenu.menu.items.push(
28312                     Roo.apply({ 
28313                         handler: function(a,b) {
28314                             editor.insertAtCursor(this.ihtml);
28315                         }
28316                     }, this.specialElements[i])
28317                 );
28318                     
28319             }
28320             
28321             tb.add(semenu);
28322             
28323             
28324         }
28325          
28326         
28327         if (this.btns) {
28328             for(var i =0; i< this.btns.length;i++) {
28329                 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
28330                 b.cls =  'x-edit-none';
28331                 
28332                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
28333                     b.cls += ' x-init-enable';
28334                 }
28335                 
28336                 b.scope = editorcore;
28337                 tb.add(b);
28338             }
28339         
28340         }
28341         
28342         
28343         
28344         // disable everything...
28345         
28346         this.tb.items.each(function(item){
28347             
28348            if(
28349                 item.id != editorcore.frameId+ '-sourceedit' && 
28350                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
28351             ){
28352                 
28353                 item.disable();
28354             }
28355         });
28356         this.rendered = true;
28357         
28358         // the all the btns;
28359         editor.on('editorevent', this.updateToolbar, this);
28360         // other toolbars need to implement this..
28361         //editor.on('editmodechange', this.updateToolbar, this);
28362     },
28363     
28364     
28365     relayBtnCmd : function(btn) {
28366         this.editorcore.relayCmd(btn.cmd);
28367     },
28368     // private used internally
28369     createLink : function(){
28370         //Roo.log("create link?");
28371         var ec = this.editorcore;
28372         var ar = ec.getAllAncestors();
28373         var n = false;
28374         for(var i = 0;i< ar.length;i++) {
28375             if (ar[i] && ar[i].nodeName == 'A') {
28376                 n = ar[i];
28377                 break;
28378             }
28379         }
28380         
28381         (function() {
28382             
28383             Roo.MessageBox.show({
28384                 title : "Add / Edit Link URL",
28385                 msg : "Enter the url for the link",
28386                 buttons: Roo.MessageBox.OKCANCEL,
28387                 fn: function(btn, url){
28388                     if (btn != 'ok') {
28389                         return;
28390                     }
28391                     if(url && url != 'http:/'+'/'){
28392                         if (n) {
28393                             n.setAttribute('href', url);
28394                         } else {
28395                             ec.relayCmd('createlink', url);
28396                         }
28397                     }
28398                 },
28399                 minWidth:250,
28400                 prompt:true,
28401                 //multiline: multiline,
28402                 modal : true,
28403                 value :  n  ? n.getAttribute('href') : '' 
28404             });
28405             
28406              
28407         }).defer(100, this); // we have to defer this , otherwise the mouse click gives focus to the main window.
28408         
28409     },
28410
28411     
28412     /**
28413      * Protected method that will not generally be called directly. It triggers
28414      * a toolbar update by reading the markup state of the current selection in the editor.
28415      */
28416     updateToolbar: function(){
28417
28418         if(!this.editorcore.activated){
28419             this.editor.onFirstFocus();
28420             return;
28421         }
28422
28423         var btns = this.tb.items.map, 
28424             doc = this.editorcore.doc,
28425             frameId = this.editorcore.frameId;
28426
28427         if(!this.disable.font && !Roo.isSafari){
28428             /*
28429             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
28430             if(name != this.fontSelect.dom.value){
28431                 this.fontSelect.dom.value = name;
28432             }
28433             */
28434         }
28435         if(!this.disable.format){
28436             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
28437             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
28438             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
28439             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
28440         }
28441         if(!this.disable.alignments){
28442             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
28443             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
28444             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
28445         }
28446         if(!Roo.isSafari && !this.disable.lists){
28447             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
28448             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
28449         }
28450         
28451         var ans = this.editorcore.getAllAncestors();
28452         if (this.formatCombo) {
28453             
28454             
28455             var store = this.formatCombo.store;
28456             this.formatCombo.setValue("");
28457             for (var i =0; i < ans.length;i++) {
28458                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
28459                     // select it..
28460                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
28461                     break;
28462                 }
28463             }
28464         }
28465         
28466         
28467         
28468         // hides menus... - so this cant be on a menu...
28469         Roo.menu.MenuMgr.hideAll();
28470
28471         //this.editorsyncValue();
28472     },
28473    
28474     
28475     createFontOptions : function(){
28476         var buf = [], fs = this.fontFamilies, ff, lc;
28477         
28478         
28479         
28480         for(var i = 0, len = fs.length; i< len; i++){
28481             ff = fs[i];
28482             lc = ff.toLowerCase();
28483             buf.push(
28484                 '<option value="',lc,'" style="font-family:',ff,';"',
28485                     (this.defaultFont == lc ? ' selected="true">' : '>'),
28486                     ff,
28487                 '</option>'
28488             );
28489         }
28490         return buf.join('');
28491     },
28492     
28493     toggleSourceEdit : function(sourceEditMode){
28494         
28495         Roo.log("toolbar toogle");
28496         if(sourceEditMode === undefined){
28497             sourceEditMode = !this.sourceEditMode;
28498         }
28499         this.sourceEditMode = sourceEditMode === true;
28500         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
28501         // just toggle the button?
28502         if(btn.pressed !== this.sourceEditMode){
28503             btn.toggle(this.sourceEditMode);
28504             return;
28505         }
28506         
28507         if(sourceEditMode){
28508             Roo.log("disabling buttons");
28509             this.tb.items.each(function(item){
28510                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
28511                     item.disable();
28512                 }
28513             });
28514           
28515         }else{
28516             Roo.log("enabling buttons");
28517             if(this.editorcore.initialized){
28518                 this.tb.items.each(function(item){
28519                     item.enable();
28520                 });
28521                 // initialize 'blocks'
28522                 Roo.each(Roo.get(this.editorcore.doc.body).query('*[data-block]'), function(e) {
28523                     Roo.htmleditor.Block.factory(e).updateElement(e);
28524                 },this);
28525             
28526             }
28527             
28528         }
28529         Roo.log("calling toggole on editor");
28530         // tell the editor that it's been pressed..
28531         this.editor.toggleSourceEdit(sourceEditMode);
28532        
28533     },
28534      /**
28535      * Object collection of toolbar tooltips for the buttons in the editor. The key
28536      * is the command id associated with that button and the value is a valid QuickTips object.
28537      * For example:
28538 <pre><code>
28539 {
28540     bold : {
28541         title: 'Bold (Ctrl+B)',
28542         text: 'Make the selected text bold.',
28543         cls: 'x-html-editor-tip'
28544     },
28545     italic : {
28546         title: 'Italic (Ctrl+I)',
28547         text: 'Make the selected text italic.',
28548         cls: 'x-html-editor-tip'
28549     },
28550     ...
28551 </code></pre>
28552     * @type Object
28553      */
28554     buttonTips : {
28555         bold : {
28556             title: 'Bold (Ctrl+B)',
28557             text: 'Make the selected text bold.',
28558             cls: 'x-html-editor-tip'
28559         },
28560         italic : {
28561             title: 'Italic (Ctrl+I)',
28562             text: 'Make the selected text italic.',
28563             cls: 'x-html-editor-tip'
28564         },
28565         underline : {
28566             title: 'Underline (Ctrl+U)',
28567             text: 'Underline the selected text.',
28568             cls: 'x-html-editor-tip'
28569         },
28570         strikethrough : {
28571             title: 'Strikethrough',
28572             text: 'Strikethrough the selected text.',
28573             cls: 'x-html-editor-tip'
28574         },
28575         increasefontsize : {
28576             title: 'Grow Text',
28577             text: 'Increase the font size.',
28578             cls: 'x-html-editor-tip'
28579         },
28580         decreasefontsize : {
28581             title: 'Shrink Text',
28582             text: 'Decrease the font size.',
28583             cls: 'x-html-editor-tip'
28584         },
28585         backcolor : {
28586             title: 'Text Highlight Color',
28587             text: 'Change the background color of the selected text.',
28588             cls: 'x-html-editor-tip'
28589         },
28590         forecolor : {
28591             title: 'Font Color',
28592             text: 'Change the color of the selected text.',
28593             cls: 'x-html-editor-tip'
28594         },
28595         justifyleft : {
28596             title: 'Align Text Left',
28597             text: 'Align text to the left.',
28598             cls: 'x-html-editor-tip'
28599         },
28600         justifycenter : {
28601             title: 'Center Text',
28602             text: 'Center text in the editor.',
28603             cls: 'x-html-editor-tip'
28604         },
28605         justifyright : {
28606             title: 'Align Text Right',
28607             text: 'Align text to the right.',
28608             cls: 'x-html-editor-tip'
28609         },
28610         insertunorderedlist : {
28611             title: 'Bullet List',
28612             text: 'Start a bulleted list.',
28613             cls: 'x-html-editor-tip'
28614         },
28615         insertorderedlist : {
28616             title: 'Numbered List',
28617             text: 'Start a numbered list.',
28618             cls: 'x-html-editor-tip'
28619         },
28620         createlink : {
28621             title: 'Hyperlink',
28622             text: 'Make the selected text a hyperlink.',
28623             cls: 'x-html-editor-tip'
28624         },
28625         sourceedit : {
28626             title: 'Source Edit',
28627             text: 'Switch to source editing mode.',
28628             cls: 'x-html-editor-tip'
28629         }
28630     },
28631     // private
28632     onDestroy : function(){
28633         if(this.rendered){
28634             
28635             this.tb.items.each(function(item){
28636                 if(item.menu){
28637                     item.menu.removeAll();
28638                     if(item.menu.el){
28639                         item.menu.el.destroy();
28640                     }
28641                 }
28642                 item.destroy();
28643             });
28644              
28645         }
28646     },
28647     onFirstFocus: function() {
28648         this.tb.items.each(function(item){
28649            item.enable();
28650         });
28651     }
28652 };
28653
28654
28655
28656
28657 // <script type="text/javascript">
28658 /*
28659  * Based on
28660  * Ext JS Library 1.1.1
28661  * Copyright(c) 2006-2007, Ext JS, LLC.
28662  *  
28663  
28664  */
28665
28666  
28667 /**
28668  * @class Roo.form.HtmlEditor.ToolbarContext
28669  * Context Toolbar
28670  * 
28671  * Usage:
28672  *
28673  new Roo.form.HtmlEditor({
28674     ....
28675     toolbars : [
28676         { xtype: 'ToolbarStandard', styles : {} }
28677         { xtype: 'ToolbarContext', disable : {} }
28678     ]
28679 })
28680
28681      
28682  * 
28683  * @config : {Object} disable List of elements to disable.. (not done yet.)
28684  * @config : {Object} styles  Map of styles available.
28685  * 
28686  */
28687
28688 Roo.form.HtmlEditor.ToolbarContext = function(config)
28689 {
28690     
28691     Roo.apply(this, config);
28692     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
28693     // dont call parent... till later.
28694     this.styles = this.styles || {};
28695 }
28696
28697  
28698
28699 Roo.form.HtmlEditor.ToolbarContext.types = {
28700     'IMG' : [
28701         {
28702             name : 'width',
28703             title: "Width",
28704             width: 40
28705         },
28706         {
28707             name : 'height',
28708             title: "Height",
28709             width: 40
28710         },
28711         {
28712             name : 'align',
28713             title: "Align",
28714             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
28715             width : 80
28716             
28717         },
28718         {
28719             name : 'border',
28720             title: "Border",
28721             width: 40
28722         },
28723         {
28724             name : 'alt',
28725             title: "Alt",
28726             width: 120
28727         },
28728         {
28729             name : 'src',
28730             title: "Src",
28731             width: 220
28732         }
28733         
28734     ],
28735     
28736     'FIGURE' : [
28737         {
28738             name : 'align',
28739             title: "Align",
28740             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
28741             width : 80  
28742         }
28743     ],
28744     'A' : [
28745         {
28746             name : 'name',
28747             title: "Name",
28748             width: 50
28749         },
28750         {
28751             name : 'target',
28752             title: "Target",
28753             width: 120
28754         },
28755         {
28756             name : 'href',
28757             title: "Href",
28758             width: 220
28759         } // border?
28760         
28761     ],
28762     
28763     'INPUT' : [
28764         {
28765             name : 'name',
28766             title: "name",
28767             width: 120
28768         },
28769         {
28770             name : 'value',
28771             title: "Value",
28772             width: 120
28773         },
28774         {
28775             name : 'width',
28776             title: "Width",
28777             width: 40
28778         }
28779     ],
28780     'LABEL' : [
28781          {
28782             name : 'for',
28783             title: "For",
28784             width: 120
28785         }
28786     ],
28787     'TEXTAREA' : [
28788         {
28789             name : 'name',
28790             title: "name",
28791             width: 120
28792         },
28793         {
28794             name : 'rows',
28795             title: "Rows",
28796             width: 20
28797         },
28798         {
28799             name : 'cols',
28800             title: "Cols",
28801             width: 20
28802         }
28803     ],
28804     'SELECT' : [
28805         {
28806             name : 'name',
28807             title: "name",
28808             width: 120
28809         },
28810         {
28811             name : 'selectoptions',
28812             title: "Options",
28813             width: 200
28814         }
28815     ],
28816     
28817     // should we really allow this??
28818     // should this just be 
28819     'BODY' : [
28820         
28821         {
28822             name : 'title',
28823             title: "Title",
28824             width: 200,
28825             disabled : true
28826         }
28827     ],
28828  
28829     '*' : [
28830         // empty.
28831     ]
28832
28833 };
28834
28835 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
28836 Roo.form.HtmlEditor.ToolbarContext.stores = false;
28837
28838 Roo.form.HtmlEditor.ToolbarContext.options = {
28839         'font-family'  : [ 
28840                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
28841                 [ 'Courier New', 'Courier New'],
28842                 [ 'Tahoma', 'Tahoma'],
28843                 [ 'Times New Roman,serif', 'Times'],
28844                 [ 'Verdana','Verdana' ]
28845         ]
28846 };
28847
28848 // fixme - these need to be configurable..
28849  
28850
28851 //Roo.form.HtmlEditor.ToolbarContext.types
28852
28853
28854 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
28855     
28856     tb: false,
28857     
28858     rendered: false,
28859     
28860     editor : false,
28861     editorcore : false,
28862     /**
28863      * @cfg {Object} disable  List of toolbar elements to disable
28864          
28865      */
28866     disable : false,
28867     /**
28868      * @cfg {Object} styles List of styles 
28869      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
28870      *
28871      * These must be defined in the page, so they get rendered correctly..
28872      * .headline { }
28873      * TD.underline { }
28874      * 
28875      */
28876     styles : false,
28877     
28878     options: false,
28879     
28880     toolbars : false,
28881     
28882     init : function(editor)
28883     {
28884         this.editor = editor;
28885         this.editorcore = editor.editorcore ? editor.editorcore : editor;
28886         var editorcore = this.editorcore;
28887         
28888         var fid = editorcore.frameId;
28889         var etb = this;
28890         function btn(id, toggle, handler){
28891             var xid = fid + '-'+ id ;
28892             return {
28893                 id : xid,
28894                 cmd : id,
28895                 cls : 'x-btn-icon x-edit-'+id,
28896                 enableToggle:toggle !== false,
28897                 scope: editorcore, // was editor...
28898                 handler:handler||editorcore.relayBtnCmd,
28899                 clickEvent:'mousedown',
28900                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
28901                 tabIndex:-1
28902             };
28903         }
28904         // create a new element.
28905         var wdiv = editor.wrap.createChild({
28906                 tag: 'div'
28907             }, editor.wrap.dom.firstChild.nextSibling, true);
28908         
28909         // can we do this more than once??
28910         
28911          // stop form submits
28912       
28913  
28914         // disable everything...
28915         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
28916         this.toolbars = {};
28917         // block toolbars are built in updateToolbar when needed.
28918         for (var i in  ty) {
28919             
28920             this.toolbars[i] = this.buildToolbar(ty[i],i);
28921         }
28922         this.tb = this.toolbars.BODY;
28923         this.tb.el.show();
28924         this.buildFooter();
28925         this.footer.show();
28926         editor.on('hide', function( ) { this.footer.hide() }, this);
28927         editor.on('show', function( ) { this.footer.show() }, this);
28928         
28929          
28930         this.rendered = true;
28931         
28932         // the all the btns;
28933         editor.on('editorevent', this.updateToolbar, this);
28934         // other toolbars need to implement this..
28935         //editor.on('editmodechange', this.updateToolbar, this);
28936     },
28937     
28938     
28939     
28940     /**
28941      * Protected method that will not generally be called directly. It triggers
28942      * a toolbar update by reading the markup state of the current selection in the editor.
28943      *
28944      * Note you can force an update by calling on('editorevent', scope, false)
28945      */
28946     updateToolbar: function(editor ,ev, sel)
28947     {
28948         
28949         if (ev) {
28950             ev.stopEvent(); // se if we can stop this looping with mutiple events.
28951         }
28952         
28953         //Roo.log(ev);
28954         // capture mouse up - this is handy for selecting images..
28955         // perhaps should go somewhere else...
28956         if(!this.editorcore.activated){
28957              this.editor.onFirstFocus();
28958             return;
28959         }
28960         //Roo.log(ev ? ev.target : 'NOTARGET');
28961         
28962         
28963         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
28964         // selectNode - might want to handle IE?
28965         
28966         
28967         
28968         if (ev &&
28969             (ev.type == 'mouseup' || ev.type == 'click' ) &&
28970             ev.target && ev.target.tagName != 'BODY' ) { // && ev.target.tagName == 'IMG') {
28971             // they have click on an image...
28972             // let's see if we can change the selection...
28973             sel = ev.target;
28974             
28975             // this triggers looping?
28976             //this.editorcore.selectNode(sel);
28977              
28978         }
28979         
28980         // this forces an id..
28981         Array.from(this.editorcore.doc.body.querySelectorAll('.roo-ed-selection')).forEach(function(e) {
28982              e.classList.remove('roo-ed-selection');
28983         });
28984         //Roo.select('.roo-ed-selection', false, this.editorcore.doc).removeClass('roo-ed-selection');
28985         //Roo.get(node).addClass('roo-ed-selection');
28986       
28987         //var updateFooter = sel ? false : true; 
28988         
28989         
28990         var ans = this.editorcore.getAllAncestors();
28991         
28992         // pick
28993         var ty = Roo.form.HtmlEditor.ToolbarContext.types;
28994         
28995         if (!sel) { 
28996             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editorcore.doc.body;
28997             sel = sel ? sel : this.editorcore.doc.body;
28998             sel = sel.tagName.length ? sel : this.editorcore.doc.body;
28999             
29000         }
29001         
29002         var tn = sel.tagName.toUpperCase();
29003         var lastSel = this.tb.selectedNode;
29004         this.tb.selectedNode = sel;
29005         var left_label = tn;
29006         
29007         // ok see if we are editing a block?
29008         
29009         var db = false;
29010         // you are not actually selecting the block.
29011         if (sel && sel.hasAttribute('data-block')) {
29012             db = sel;
29013         } else if (sel && sel.closest('[data-block]')) {
29014             
29015             db = sel.closest('[data-block]');
29016             //var cepar = sel.closest('[contenteditable=true]');
29017             //if (db && cepar && cepar.tagName != 'BODY') {
29018             //   db = false; // we are inside an editable block.. = not sure how we are going to handle nested blocks!?
29019             //}   
29020         }
29021         
29022         
29023         var block = false;
29024         //if (db && !sel.hasAttribute('contenteditable') && sel.getAttribute('contenteditable') != 'true' ) {
29025         if (db && this.editorcore.enableBlocks) {
29026             block = Roo.htmleditor.Block.factory(db);
29027             
29028             
29029             if (block) {
29030                  db.className = (
29031                         db.classList.length > 0  ? db.className + ' ' : ''
29032                     )  + 'roo-ed-selection';
29033                  
29034                  // since we removed it earlier... its not there..
29035                 tn = 'BLOCK.' + db.getAttribute('data-block');
29036                 
29037                 //this.editorcore.selectNode(db);
29038                 if (typeof(this.toolbars[tn]) == 'undefined') {
29039                    this.toolbars[tn] = this.buildToolbar( false  ,tn ,block.friendly_name, block);
29040                 }
29041                 this.toolbars[tn].selectedNode = db;
29042                 left_label = block.friendly_name;
29043                 ans = this.editorcore.getAllAncestors();
29044             }
29045             
29046                 
29047             
29048         }
29049         
29050         
29051         if (this.tb.name == tn && lastSel == this.tb.selectedNode && ev !== false) {
29052             return; // no change?
29053         }
29054         
29055         
29056           
29057         this.tb.el.hide();
29058         ///console.log("show: " + tn);
29059         this.tb =  typeof(this.toolbars[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
29060         
29061         this.tb.el.show();
29062         // update name
29063         this.tb.items.first().el.innerHTML = left_label + ':&nbsp;';
29064         
29065         
29066         // update attributes
29067         if (block && this.tb.fields) {
29068              
29069             this.tb.fields.each(function(e) {
29070                 e.setValue(block[e.name]);
29071             });
29072             
29073             
29074         } else  if (this.tb.fields && this.tb.selectedNode) {
29075             this.tb.fields.each( function(e) {
29076                 if (e.stylename) {
29077                     e.setValue(this.tb.selectedNode.style[e.stylename]);
29078                     return;
29079                 } 
29080                 e.setValue(this.tb.selectedNode.getAttribute(e.attrname));
29081             }, this);
29082             this.updateToolbarStyles(this.tb.selectedNode);  
29083         }
29084         
29085         
29086        
29087         Roo.menu.MenuMgr.hideAll();
29088
29089         
29090         
29091     
29092         // update the footer
29093         //
29094         this.updateFooter(ans);
29095              
29096     },
29097     
29098     updateToolbarStyles : function(sel)
29099     {
29100         var hasStyles = false;
29101         for(var i in this.styles) {
29102             hasStyles = true;
29103             break;
29104         }
29105         
29106         // update styles
29107         if (hasStyles && this.tb.hasStyles) { 
29108             var st = this.tb.fields.item(0);
29109             
29110             st.store.removeAll();
29111             var cn = sel.className.split(/\s+/);
29112             
29113             var avs = [];
29114             if (this.styles['*']) {
29115                 
29116                 Roo.each(this.styles['*'], function(v) {
29117                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
29118                 });
29119             }
29120             if (this.styles[tn]) { 
29121                 Roo.each(this.styles[tn], function(v) {
29122                     avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
29123                 });
29124             }
29125             
29126             st.store.loadData(avs);
29127             st.collapse();
29128             st.setValue(cn);
29129         }
29130     },
29131     
29132      
29133     updateFooter : function(ans)
29134     {
29135         var html = '';
29136         if (ans === false) {
29137             this.footDisp.dom.innerHTML = '';
29138             return;
29139         }
29140         
29141         this.footerEls = ans.reverse();
29142         Roo.each(this.footerEls, function(a,i) {
29143             if (!a) { return; }
29144             html += html.length ? ' &gt; '  :  '';
29145             
29146             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
29147             
29148         });
29149        
29150         // 
29151         var sz = this.footDisp.up('td').getSize();
29152         this.footDisp.dom.style.width = (sz.width -10) + 'px';
29153         this.footDisp.dom.style.marginLeft = '5px';
29154         
29155         this.footDisp.dom.style.overflow = 'hidden';
29156         
29157         this.footDisp.dom.innerHTML = html;
29158             
29159         
29160     },
29161    
29162        
29163     // private
29164     onDestroy : function(){
29165         if(this.rendered){
29166             
29167             this.tb.items.each(function(item){
29168                 if(item.menu){
29169                     item.menu.removeAll();
29170                     if(item.menu.el){
29171                         item.menu.el.destroy();
29172                     }
29173                 }
29174                 item.destroy();
29175             });
29176              
29177         }
29178     },
29179     onFirstFocus: function() {
29180         // need to do this for all the toolbars..
29181         this.tb.items.each(function(item){
29182            item.enable();
29183         });
29184     },
29185     buildToolbar: function(tlist, nm, friendly_name, block)
29186     {
29187         var editor = this.editor;
29188         var editorcore = this.editorcore;
29189          // create a new element.
29190         var wdiv = editor.wrap.createChild({
29191                 tag: 'div'
29192             }, editor.wrap.dom.firstChild.nextSibling, true);
29193         
29194        
29195         var tb = new Roo.Toolbar(wdiv);
29196         ///this.tb = tb; // << this sets the active toolbar..
29197         if (tlist === false && block) {
29198             tlist = block.contextMenu(this);
29199         }
29200         
29201         tb.hasStyles = false;
29202         tb.name = nm;
29203         
29204         tb.add((typeof(friendly_name) == 'undefined' ? nm : friendly_name) + ":&nbsp;");
29205         
29206         var styles = Array.from(this.styles);
29207         
29208         
29209         // styles...
29210         if (styles && styles.length) {
29211             tb.hasStyles = true;
29212             // this needs a multi-select checkbox...
29213             tb.addField( new Roo.form.ComboBox({
29214                 store: new Roo.data.SimpleStore({
29215                     id : 'val',
29216                     fields: ['val', 'selected'],
29217                     data : [] 
29218                 }),
29219                 name : '-roo-edit-className',
29220                 attrname : 'className',
29221                 displayField: 'val',
29222                 typeAhead: false,
29223                 mode: 'local',
29224                 editable : false,
29225                 triggerAction: 'all',
29226                 emptyText:'Select Style',
29227                 selectOnFocus:true,
29228                 width: 130,
29229                 listeners : {
29230                     'select': function(c, r, i) {
29231                         // initial support only for on class per el..
29232                         tb.selectedNode.className =  r ? r.get('val') : '';
29233                         editorcore.syncValue();
29234                     }
29235                 }
29236     
29237             }));
29238         }
29239         
29240         var tbc = Roo.form.HtmlEditor.ToolbarContext;
29241         
29242         
29243         for (var i = 0; i < tlist.length; i++) {
29244             
29245             // newer versions will use xtype cfg to create menus.
29246             if (typeof(tlist[i].xtype) != 'undefined') {
29247                 
29248                 tb[typeof(tlist[i].name)== 'undefined' ? 'add' : 'addField'](Roo.factory(tlist[i]));
29249                 
29250                 
29251                 continue;
29252             }
29253             
29254             var item = tlist[i];
29255             tb.add(item.title + ":&nbsp;");
29256             
29257             
29258             //optname == used so you can configure the options available..
29259             var opts = item.opts ? item.opts : false;
29260             if (item.optname) { // use the b
29261                 opts = Roo.form.HtmlEditor.ToolbarContext.options[item.optname];
29262            
29263             }
29264             
29265             if (opts) {
29266                 // opts == pulldown..
29267                 tb.addField( new Roo.form.ComboBox({
29268                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
29269                         id : 'val',
29270                         fields: ['val', 'display'],
29271                         data : opts  
29272                     }),
29273                     name : '-roo-edit-' + tlist[i].name,
29274                     
29275                     attrname : tlist[i].name,
29276                     stylename : item.style ? item.style : false,
29277                     
29278                     displayField: item.displayField ? item.displayField : 'val',
29279                     valueField :  'val',
29280                     typeAhead: false,
29281                     mode: typeof(tbc.stores[tlist[i].name]) != 'undefined'  ? 'remote' : 'local',
29282                     editable : false,
29283                     triggerAction: 'all',
29284                     emptyText:'Select',
29285                     selectOnFocus:true,
29286                     width: item.width ? item.width  : 130,
29287                     listeners : {
29288                         'select': function(c, r, i) {
29289                              
29290                             
29291                             if (c.stylename) {
29292                                 tb.selectedNode.style[c.stylename] =  r.get('val');
29293                                 editorcore.syncValue();
29294                                 return;
29295                             }
29296                             if (r === false) {
29297                                 tb.selectedNode.removeAttribute(c.attrname);
29298                                 editorcore.syncValue();
29299                                 return;
29300                             }
29301                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
29302                             editorcore.syncValue();
29303                         }
29304                     }
29305
29306                 }));
29307                 continue;
29308                     
29309                  
29310                 /*
29311                 tb.addField( new Roo.form.TextField({
29312                     name: i,
29313                     width: 100,
29314                     //allowBlank:false,
29315                     value: ''
29316                 }));
29317                 continue;
29318                 */
29319             }
29320             tb.addField( new Roo.form.TextField({
29321                 name: '-roo-edit-' + tlist[i].name,
29322                 attrname : tlist[i].name,
29323                 
29324                 width: item.width,
29325                 //allowBlank:true,
29326                 value: '',
29327                 listeners: {
29328                     'change' : function(f, nv, ov) {
29329                         
29330                          
29331                         tb.selectedNode.setAttribute(f.attrname, nv);
29332                         editorcore.syncValue();
29333                     }
29334                 }
29335             }));
29336              
29337         }
29338         
29339         var _this = this;
29340         var show_delete = !block || block.deleteTitle !== false;
29341         if(nm == 'BODY'){
29342             show_delete = false;
29343             tb.addSeparator();
29344         
29345             tb.addButton( {
29346                 text: 'Stylesheets',
29347
29348                 listeners : {
29349                     click : function ()
29350                     {
29351                         _this.editor.fireEvent('stylesheetsclick', _this.editor);
29352                     }
29353                 }
29354             });
29355         }
29356         
29357         tb.addFill();
29358         if (show_delete) {
29359             tb.addButton({
29360                 text: block && block.deleteTitle ? block.deleteTitle  : 'Remove Block or Formating', // remove the tag, and puts the children outside...
29361         
29362                 listeners : {
29363                     click : function ()
29364                     {
29365                         var sn = tb.selectedNode;
29366                         if (block) {
29367                             sn = Roo.htmleditor.Block.factory(tb.selectedNode).removeNode();
29368                             
29369                         }
29370                         if (!sn) {
29371                             return;
29372                         }
29373                         var stn =  sn.childNodes[0] || sn.nextSibling || sn.previousSibling || sn.parentNode;
29374                         if (sn.hasAttribute('data-block')) {
29375                             stn =  sn.nextSibling || sn.previousSibling || sn.parentNode;
29376                             sn.parentNode.removeChild(sn);
29377                             
29378                         } else if (sn && sn.tagName != 'BODY') {
29379                             // remove and keep parents.
29380                             a = new Roo.htmleditor.FilterKeepChildren({tag : false});
29381                             a.replaceTag(sn);
29382                         }
29383                         
29384                         
29385                         var range = editorcore.createRange();
29386             
29387                         range.setStart(stn,0);
29388                         range.setEnd(stn,0); 
29389                         var selection = editorcore.getSelection();
29390                         selection.removeAllRanges();
29391                         selection.addRange(range);
29392                         
29393                         
29394                         //_this.updateToolbar(null, null, pn);
29395                         _this.updateToolbar(null, null, null);
29396                         _this.updateFooter(false);
29397                         
29398                     }
29399                 }
29400                 
29401                         
29402                     
29403                 
29404             });
29405         }    
29406         
29407         tb.el.on('click', function(e){
29408             e.preventDefault(); // what does this do?
29409         });
29410         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
29411         tb.el.hide();
29412         
29413         // dont need to disable them... as they will get hidden
29414         return tb;
29415          
29416         
29417     },
29418     buildFooter : function()
29419     {
29420         
29421         var fel = this.editor.wrap.createChild();
29422         this.footer = new Roo.Toolbar(fel);
29423         // toolbar has scrolly on left / right?
29424         var footDisp= new Roo.Toolbar.Fill();
29425         var _t = this;
29426         this.footer.add(
29427             {
29428                 text : '&lt;',
29429                 xtype: 'Button',
29430                 handler : function() {
29431                     _t.footDisp.scrollTo('left',0,true)
29432                 }
29433             }
29434         );
29435         this.footer.add( footDisp );
29436         this.footer.add( 
29437             {
29438                 text : '&gt;',
29439                 xtype: 'Button',
29440                 handler : function() {
29441                     // no animation..
29442                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
29443                 }
29444             }
29445         );
29446         var fel = Roo.get(footDisp.el);
29447         fel.addClass('x-editor-context');
29448         this.footDispWrap = fel; 
29449         this.footDispWrap.overflow  = 'hidden';
29450         
29451         this.footDisp = fel.createChild();
29452         this.footDispWrap.on('click', this.onContextClick, this)
29453         
29454         
29455     },
29456     // when the footer contect changes
29457     onContextClick : function (ev,dom)
29458     {
29459         ev.preventDefault();
29460         var  cn = dom.className;
29461         //Roo.log(cn);
29462         if (!cn.match(/x-ed-loc-/)) {
29463             return;
29464         }
29465         var n = cn.split('-').pop();
29466         var ans = this.footerEls;
29467         var sel = ans[n];
29468         
29469         this.editorcore.selectNode(sel);
29470         
29471         
29472         this.updateToolbar(null, null, sel);
29473         
29474         
29475     }
29476     
29477     
29478     
29479     
29480     
29481 });
29482
29483
29484
29485
29486
29487 /*
29488  * Based on:
29489  * Ext JS Library 1.1.1
29490  * Copyright(c) 2006-2007, Ext JS, LLC.
29491  *
29492  * Originally Released Under LGPL - original licence link has changed is not relivant.
29493  *
29494  * Fork - LGPL
29495  * <script type="text/javascript">
29496  */
29497  
29498 /**
29499  * @class Roo.form.BasicForm
29500  * @extends Roo.util.Observable
29501  * Supplies the functionality to do "actions" on forms and initialize Roo.form.Field types on existing markup.
29502  * @constructor
29503  * @param {String/HTMLElement/Roo.Element} el The form element or its id
29504  * @param {Object} config Configuration options
29505  */
29506 Roo.form.BasicForm = function(el, config){
29507     this.allItems = [];
29508     this.childForms = [];
29509     Roo.apply(this, config);
29510     /*
29511      * The Roo.form.Field items in this form.
29512      * @type MixedCollection
29513      */
29514      
29515      
29516     this.items = new Roo.util.MixedCollection(false, function(o){
29517         return o.id || (o.id = Roo.id());
29518     });
29519     this.addEvents({
29520         /**
29521          * @event beforeaction
29522          * Fires before any action is performed. Return false to cancel the action.
29523          * @param {Form} this
29524          * @param {Action} action The action to be performed
29525          */
29526         beforeaction: true,
29527         /**
29528          * @event actionfailed
29529          * Fires when an action fails.
29530          * @param {Form} this
29531          * @param {Action} action The action that failed
29532          */
29533         actionfailed : true,
29534         /**
29535          * @event actioncomplete
29536          * Fires when an action is completed.
29537          * @param {Form} this
29538          * @param {Action} action The action that completed
29539          */
29540         actioncomplete : true
29541     });
29542     if(el){
29543         this.initEl(el);
29544     }
29545     Roo.form.BasicForm.superclass.constructor.call(this);
29546     
29547     Roo.form.BasicForm.popover.apply();
29548 };
29549
29550 Roo.extend(Roo.form.BasicForm, Roo.util.Observable, {
29551     /**
29552      * @cfg {String} method
29553      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
29554      */
29555     /**
29556      * @cfg {DataReader} reader
29557      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when executing "load" actions.
29558      * This is optional as there is built-in support for processing JSON.
29559      */
29560     /**
29561      * @cfg {DataReader} errorReader
29562      * An Roo.data.DataReader (e.g. {@link Roo.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions.
29563      * This is completely optional as there is built-in support for processing JSON.
29564      */
29565     /**
29566      * @cfg {String} url
29567      * The URL to use for form actions if one isn't supplied in the action options.
29568      */
29569     /**
29570      * @cfg {Boolean} fileUpload
29571      * Set to true if this form is a file upload.
29572      */
29573      
29574     /**
29575      * @cfg {Object} baseParams
29576      * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
29577      */
29578      /**
29579      
29580     /**
29581      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
29582      */
29583     timeout: 30,
29584
29585     // private
29586     activeAction : null,
29587
29588     /**
29589      * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded
29590      * or setValues() data instead of when the form was first created.
29591      */
29592     trackResetOnLoad : false,
29593     
29594     
29595     /**
29596      * childForms - used for multi-tab forms
29597      * @type {Array}
29598      */
29599     childForms : false,
29600     
29601     /**
29602      * allItems - full list of fields.
29603      * @type {Array}
29604      */
29605     allItems : false,
29606     
29607     /**
29608      * By default wait messages are displayed with Roo.MessageBox.wait. You can target a specific
29609      * element by passing it or its id or mask the form itself by passing in true.
29610      * @type Mixed
29611      */
29612     waitMsgTarget : false,
29613     
29614     /**
29615      * @type Boolean
29616      */
29617     disableMask : false,
29618     
29619     /**
29620      * @cfg {Boolean} errorMask Should the form be masked (and the active element highlighted on error - default false
29621      */
29622     errorMask : false,
29623     
29624     /**
29625      * @cfg {Number} maskOffset space around form element to mask if there is an error Default 100
29626      */
29627     maskOffset : 100,
29628
29629     // private
29630     initEl : function(el){
29631         this.el = Roo.get(el);
29632         this.id = this.el.id || Roo.id();
29633         this.el.on('submit', this.onSubmit, this);
29634         this.el.addClass('x-form');
29635     },
29636
29637     // private
29638     onSubmit : function(e){
29639         e.stopEvent();
29640     },
29641
29642     /**
29643      * Returns true if client-side validation on the form is successful.
29644      * @return Boolean
29645      */
29646     isValid : function(){
29647         var valid = true;
29648         var target = false;
29649         this.items.each(function(f){
29650             if(f.validate()){
29651                 return;
29652             }
29653             
29654             valid = false;
29655                 
29656             if(!target && f.el.isVisible(true)){
29657                 target = f;
29658             }
29659         });
29660         
29661         if(this.errorMask && !valid){
29662             Roo.form.BasicForm.popover.mask(this, target);
29663         }
29664         
29665         return valid;
29666     },
29667     /**
29668      * Returns array of invalid form fields.
29669      * @return Array
29670      */
29671     
29672     invalidFields : function()
29673     {
29674         var ret = [];
29675         this.items.each(function(f){
29676             if(f.validate()){
29677                 return;
29678             }
29679             ret.push(f);
29680             
29681         });
29682         
29683         return ret;
29684     },
29685     
29686     
29687     /**
29688      * DEPRICATED Returns true if any fields in this form have changed since their original load. 
29689      * @return Boolean
29690      */
29691     isDirty : function(){
29692         var dirty = false;
29693         this.items.each(function(f){
29694            if(f.isDirty()){
29695                dirty = true;
29696                return false;
29697            }
29698         });
29699         return dirty;
29700     },
29701     
29702     /**
29703      * Returns true if any fields in this form have changed since their original load. (New version)
29704      * @return Boolean
29705      */
29706     
29707     hasChanged : function()
29708     {
29709         var dirty = false;
29710         this.items.each(function(f){
29711            if(f.hasChanged()){
29712                dirty = true;
29713                return false;
29714            }
29715         });
29716         return dirty;
29717         
29718     },
29719     /**
29720      * Resets all hasChanged to 'false' -
29721      * The old 'isDirty' used 'original value..' however this breaks reset() and a few other things.
29722      * So hasChanged storage is only to be used for this purpose
29723      * @return Boolean
29724      */
29725     resetHasChanged : function()
29726     {
29727         this.items.each(function(f){
29728            f.resetHasChanged();
29729         });
29730         
29731     },
29732     
29733     
29734     /**
29735      * Performs a predefined action (submit or load) or custom actions you define on this form.
29736      * @param {String} actionName The name of the action type
29737      * @param {Object} options (optional) The options to pass to the action.  All of the config options listed
29738      * below are supported by both the submit and load actions unless otherwise noted (custom actions could also
29739      * accept other config options):
29740      * <pre>
29741 Property          Type             Description
29742 ----------------  ---------------  ----------------------------------------------------------------------------------
29743 url               String           The url for the action (defaults to the form's url)
29744 method            String           The form method to use (defaults to the form's method, or POST if not defined)
29745 params            String/Object    The params to pass (defaults to the form's baseParams, or none if not defined)
29746 clientValidation  Boolean          Applies to submit only.  Pass true to call form.isValid() prior to posting to
29747                                    validate the form on the client (defaults to false)
29748      * </pre>
29749      * @return {BasicForm} this
29750      */
29751     doAction : function(action, options){
29752         if(typeof action == 'string'){
29753             action = new Roo.form.Action.ACTION_TYPES[action](this, options);
29754         }
29755         if(this.fireEvent('beforeaction', this, action) !== false){
29756             this.beforeAction(action);
29757             action.run.defer(100, action);
29758         }
29759         return this;
29760     },
29761
29762     /**
29763      * Shortcut to do a submit action.
29764      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
29765      * @return {BasicForm} this
29766      */
29767     submit : function(options){
29768         this.doAction('submit', options);
29769         return this;
29770     },
29771
29772     /**
29773      * Shortcut to do a load action.
29774      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
29775      * @return {BasicForm} this
29776      */
29777     load : function(options){
29778         this.doAction('load', options);
29779         return this;
29780     },
29781
29782     /**
29783      * Persists the values in this form into the passed Roo.data.Record object in a beginEdit/endEdit block.
29784      * @param {Record} record The record to edit
29785      * @return {BasicForm} this
29786      */
29787     updateRecord : function(record){
29788         record.beginEdit();
29789         var fs = record.fields;
29790         fs.each(function(f){
29791             var field = this.findField(f.name);
29792             if(field){
29793                 record.set(f.name, field.getValue());
29794             }
29795         }, this);
29796         record.endEdit();
29797         return this;
29798     },
29799
29800     /**
29801      * Loads an Roo.data.Record into this form.
29802      * @param {Record} record The record to load
29803      * @return {BasicForm} this
29804      */
29805     loadRecord : function(record){
29806         this.setValues(record.data);
29807         return this;
29808     },
29809
29810     // private
29811     beforeAction : function(action){
29812         var o = action.options;
29813         
29814         if(!this.disableMask) {
29815             if(this.waitMsgTarget === true){
29816                 this.el.mask(o.waitMsg || "Sending", 'x-mask-loading');
29817             }else if(this.waitMsgTarget){
29818                 this.waitMsgTarget = Roo.get(this.waitMsgTarget);
29819                 this.waitMsgTarget.mask(o.waitMsg || "Sending", 'x-mask-loading');
29820             }else {
29821                 Roo.MessageBox.wait(o.waitMsg || "Sending", o.waitTitle || this.waitTitle || 'Please Wait...');
29822             }
29823         }
29824         
29825          
29826     },
29827
29828     // private
29829     afterAction : function(action, success){
29830         this.activeAction = null;
29831         var o = action.options;
29832         
29833         if(!this.disableMask) {
29834             if(this.waitMsgTarget === true){
29835                 this.el.unmask();
29836             }else if(this.waitMsgTarget){
29837                 this.waitMsgTarget.unmask();
29838             }else{
29839                 Roo.MessageBox.updateProgress(1);
29840                 Roo.MessageBox.hide();
29841             }
29842         }
29843         
29844         if(success){
29845             if(o.reset){
29846                 this.reset();
29847             }
29848             Roo.callback(o.success, o.scope, [this, action]);
29849             this.fireEvent('actioncomplete', this, action);
29850             
29851         }else{
29852             
29853             // failure condition..
29854             // we have a scenario where updates need confirming.
29855             // eg. if a locking scenario exists..
29856             // we look for { errors : { needs_confirm : true }} in the response.
29857             if (
29858                 (typeof(action.result) != 'undefined')  &&
29859                 (typeof(action.result.errors) != 'undefined')  &&
29860                 (typeof(action.result.errors.needs_confirm) != 'undefined')
29861            ){
29862                 var _t = this;
29863                 Roo.MessageBox.confirm(
29864                     "Change requires confirmation",
29865                     action.result.errorMsg,
29866                     function(r) {
29867                         if (r != 'yes') {
29868                             return;
29869                         }
29870                         _t.doAction('submit', { params :  { _submit_confirmed : 1 } }  );
29871                     }
29872                     
29873                 );
29874                 
29875                 
29876                 
29877                 return;
29878             }
29879             
29880             Roo.callback(o.failure, o.scope, [this, action]);
29881             // show an error message if no failed handler is set..
29882             if (!this.hasListener('actionfailed')) {
29883                 Roo.MessageBox.alert("Error",
29884                     (typeof(action.result) != 'undefined' && typeof(action.result.errorMsg) != 'undefined') ?
29885                         action.result.errorMsg :
29886                         "Saving Failed, please check your entries or try again"
29887                 );
29888             }
29889             
29890             this.fireEvent('actionfailed', this, action);
29891         }
29892         
29893     },
29894
29895     /**
29896      * Find a Roo.form.Field in this form by id, dataIndex, name or hiddenName
29897      * @param {String} id The value to search for
29898      * @return Field
29899      */
29900     findField : function(id){
29901         var field = this.items.get(id);
29902         if(!field){
29903             this.items.each(function(f){
29904                 if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
29905                     field = f;
29906                     return false;
29907                 }
29908             });
29909         }
29910         return field || null;
29911     },
29912
29913     /**
29914      * Add a secondary form to this one, 
29915      * Used to provide tabbed forms. One form is primary, with hidden values 
29916      * which mirror the elements from the other forms.
29917      * 
29918      * @param {Roo.form.Form} form to add.
29919      * 
29920      */
29921     addForm : function(form)
29922     {
29923        
29924         if (this.childForms.indexOf(form) > -1) {
29925             // already added..
29926             return;
29927         }
29928         this.childForms.push(form);
29929         var n = '';
29930         Roo.each(form.allItems, function (fe) {
29931             
29932             n = typeof(fe.getName) == 'undefined' ? fe.name : fe.getName();
29933             if (this.findField(n)) { // already added..
29934                 return;
29935             }
29936             var add = new Roo.form.Hidden({
29937                 name : n
29938             });
29939             add.render(this.el);
29940             
29941             this.add( add );
29942         }, this);
29943         
29944     },
29945     /**
29946      * Mark fields in this form invalid in bulk.
29947      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
29948      * @return {BasicForm} this
29949      */
29950     markInvalid : function(errors){
29951         if(errors instanceof Array){
29952             for(var i = 0, len = errors.length; i < len; i++){
29953                 var fieldError = errors[i];
29954                 var f = this.findField(fieldError.id);
29955                 if(f){
29956                     f.markInvalid(fieldError.msg);
29957                 }
29958             }
29959         }else{
29960             var field, id;
29961             for(id in errors){
29962                 if(typeof errors[id] != 'function' && (field = this.findField(id))){
29963                     field.markInvalid(errors[id]);
29964                 }
29965             }
29966         }
29967         Roo.each(this.childForms || [], function (f) {
29968             f.markInvalid(errors);
29969         });
29970         
29971         return this;
29972     },
29973
29974     /**
29975      * Set values for fields in this form in bulk.
29976      * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2}
29977      * @return {BasicForm} this
29978      */
29979     setValues : function(values){
29980         if(values instanceof Array){ // array of objects
29981             for(var i = 0, len = values.length; i < len; i++){
29982                 var v = values[i];
29983                 var f = this.findField(v.id);
29984                 if(f){
29985                     f.setValue(v.value);
29986                     if(this.trackResetOnLoad){
29987                         f.originalValue = f.getValue();
29988                     }
29989                 }
29990             }
29991         }else{ // object hash
29992             var field, id;
29993             for(id in values){
29994                 if(typeof values[id] != 'function' && (field = this.findField(id))){
29995                     
29996                     
29997                     
29998                     
29999                     if (field.setFromData && 
30000                         field.valueField && 
30001                         field.displayField &&
30002                         // combos' with local stores can 
30003                         // be queried via setValue()
30004                         // to set their value..
30005                         (field.store && !field.store.isLocal)
30006                         ) {
30007                         // it's a combo
30008                         var sd = { };
30009                         sd[field.valueField] = typeof(values[field.hiddenName]) == 'undefined' ? '' : values[field.hiddenName];
30010                         sd[field.displayField] = typeof(values[field.name]) == 'undefined' ? '' : values[field.name];
30011                         field.setFromData(sd);
30012                         
30013                     } else if (field.inputType && field.inputType == 'radio') {
30014                         
30015                         field.setValue(values[id]);
30016                     } else {
30017                         field.setValue(values[id]);
30018                     }
30019                     
30020                     
30021                     if(this.trackResetOnLoad){
30022                         field.originalValue = field.getValue();
30023                     }
30024                 }
30025             }
30026         }
30027         this.resetHasChanged();
30028         
30029         
30030         Roo.each(this.childForms || [], function (f) {
30031             f.setValues(values);
30032             f.resetHasChanged();
30033         });
30034                 
30035         return this;
30036     },
30037  
30038     /**
30039      * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name
30040      * they are returned as an array.
30041      * @param {Boolean} asString (def)
30042      * @return {Object}
30043      */
30044     getValues : function(asString)
30045     {
30046         if (this.childForms) {
30047             // copy values from the child forms
30048             Roo.each(this.childForms, function (f) {
30049                 this.setValues(f.getFieldValues()); // get the full set of data, as we might be copying comboboxes from external into this one.
30050             }, this);
30051         }
30052         
30053         // use formdata
30054         if (typeof(FormData) != 'undefined' && asString !== true) {
30055             // this relies on a 'recent' version of chrome apparently...
30056             try {
30057                 var fd = (new FormData(this.el.dom)).entries();
30058                 var ret = {};
30059                 var ent = fd.next();
30060                 while (!ent.done) {
30061                     ret[ent.value[0]] = ent.value[1]; // not sure how this will handle duplicates..
30062                     ent = fd.next();
30063                 };
30064                 return ret;
30065             } catch(e) {
30066                 
30067             }
30068             
30069         }
30070         
30071         
30072         var fs = Roo.lib.Ajax.serializeForm(this.el.dom);
30073         if(asString === true){
30074             return fs;
30075         }
30076         return Roo.urlDecode(fs);
30077     },
30078     
30079     /**
30080      * Returns the fields in this form as an object with key/value pairs. 
30081      * This differs from getValues as it calls getValue on each child item, rather than using dom data.
30082      * Normally this will not return readOnly data 
30083      * @param {Boolean} with_readonly return readonly field data.
30084      * @return {Object}
30085      */
30086     getFieldValues : function(with_readonly)
30087     {
30088         if (this.childForms) {
30089             // copy values from the child forms
30090             // should this call getFieldValues - probably not as we do not currently copy
30091             // hidden fields when we generate..
30092             Roo.each(this.childForms, function (f) {
30093                 this.setValues(f.getFieldValues());
30094             }, this);
30095         }
30096         
30097         var ret = {};
30098         this.items.each(function(f){
30099             
30100             if (f.readOnly && with_readonly !== true) {
30101                 return; // skip read only values. - this is in theory to stop 'old' values being copied over new ones
30102                         // if a subform contains a copy of them.
30103                         // if you have subforms with the same editable data, you will need to copy the data back
30104                         // and forth.
30105             }
30106             
30107             if (!f.getName()) {
30108                 return;
30109             }
30110             var v = f.getValue();
30111             if (f.inputType =='radio') {
30112                 if (typeof(ret[f.getName()]) == 'undefined') {
30113                     ret[f.getName()] = ''; // empty..
30114                 }
30115                 
30116                 if (!f.el.dom.checked) {
30117                     return;
30118                     
30119                 }
30120                 v = f.el.dom.value;
30121                 
30122             }
30123             
30124             // not sure if this supported any more..
30125             if ((typeof(v) == 'object') && f.getRawValue) {
30126                 v = f.getRawValue() ; // dates..
30127             }
30128             // combo boxes where name != hiddenName...
30129             if (f.name != f.getName()) {
30130                 ret[f.name] = f.getRawValue();
30131             }
30132             ret[f.getName()] = v;
30133         });
30134         
30135         return ret;
30136     },
30137
30138     /**
30139      * Clears all invalid messages in this form.
30140      * @return {BasicForm} this
30141      */
30142     clearInvalid : function(){
30143         this.items.each(function(f){
30144            f.clearInvalid();
30145         });
30146         
30147         Roo.each(this.childForms || [], function (f) {
30148             f.clearInvalid();
30149         });
30150         
30151         
30152         return this;
30153     },
30154
30155     /**
30156      * Resets this form.
30157      * @return {BasicForm} this
30158      */
30159     reset : function(){
30160         this.items.each(function(f){
30161             f.reset();
30162         });
30163         
30164         Roo.each(this.childForms || [], function (f) {
30165             f.reset();
30166         });
30167         this.resetHasChanged();
30168         
30169         return this;
30170     },
30171
30172     /**
30173      * Add Roo.form components to this form.
30174      * @param {Field} field1
30175      * @param {Field} field2 (optional)
30176      * @param {Field} etc (optional)
30177      * @return {BasicForm} this
30178      */
30179     add : function(){
30180         this.items.addAll(Array.prototype.slice.call(arguments, 0));
30181         return this;
30182     },
30183
30184
30185     /**
30186      * Removes a field from the items collection (does NOT remove its markup).
30187      * @param {Field} field
30188      * @return {BasicForm} this
30189      */
30190     remove : function(field){
30191         this.items.remove(field);
30192         return this;
30193     },
30194
30195     /**
30196      * Looks at the fields in this form, checks them for an id attribute,
30197      * and calls applyTo on the existing dom element with that id.
30198      * @return {BasicForm} this
30199      */
30200     render : function(){
30201         this.items.each(function(f){
30202             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
30203                 f.applyTo(f.id);
30204             }
30205         });
30206         return this;
30207     },
30208
30209     /**
30210      * Calls {@link Ext#apply} for all fields in this form with the passed object.
30211      * @param {Object} values
30212      * @return {BasicForm} this
30213      */
30214     applyToFields : function(o){
30215         this.items.each(function(f){
30216            Roo.apply(f, o);
30217         });
30218         return this;
30219     },
30220
30221     /**
30222      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
30223      * @param {Object} values
30224      * @return {BasicForm} this
30225      */
30226     applyIfToFields : function(o){
30227         this.items.each(function(f){
30228            Roo.applyIf(f, o);
30229         });
30230         return this;
30231     }
30232 });
30233
30234 // back compat
30235 Roo.BasicForm = Roo.form.BasicForm;
30236
30237 Roo.apply(Roo.form.BasicForm, {
30238     
30239     popover : {
30240         
30241         padding : 5,
30242         
30243         isApplied : false,
30244         
30245         isMasked : false,
30246         
30247         form : false,
30248         
30249         target : false,
30250         
30251         intervalID : false,
30252         
30253         maskEl : false,
30254         
30255         apply : function()
30256         {
30257             if(this.isApplied){
30258                 return;
30259             }
30260             
30261             this.maskEl = {
30262                 top : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-top-mask" }, true),
30263                 left : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-left-mask" }, true),
30264                 bottom : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-bottom-mask" }, true),
30265                 right : Roo.DomHelper.append(Roo.get(document.body), { tag: "div", cls:"x-dlg-mask roo-form-right-mask" }, true)
30266             };
30267             
30268             this.maskEl.top.enableDisplayMode("block");
30269             this.maskEl.left.enableDisplayMode("block");
30270             this.maskEl.bottom.enableDisplayMode("block");
30271             this.maskEl.right.enableDisplayMode("block");
30272             
30273             Roo.get(document.body).on('click', function(){
30274                 this.unmask();
30275             }, this);
30276             
30277             Roo.get(document.body).on('touchstart', function(){
30278                 this.unmask();
30279             }, this);
30280             
30281             this.isApplied = true
30282         },
30283         
30284         mask : function(form, target)
30285         {
30286             this.form = form;
30287             
30288             this.target = target;
30289             
30290             if(!this.form.errorMask || !target.el){
30291                 return;
30292             }
30293             
30294             var scrollable = this.target.el.findScrollableParent() || this.target.el.findParent('div.x-layout-active-content', 100, true) || Roo.get(document.body);
30295             
30296             var ot = this.target.el.calcOffsetsTo(scrollable);
30297             
30298             var scrollTo = ot[1] - this.form.maskOffset;
30299             
30300             scrollTo = Math.min(scrollTo, scrollable.dom.scrollHeight);
30301             
30302             scrollable.scrollTo('top', scrollTo);
30303             
30304             var el = this.target.wrap || this.target.el;
30305             
30306             var box = el.getBox();
30307             
30308             this.maskEl.top.setStyle('position', 'absolute');
30309             this.maskEl.top.setStyle('z-index', 10000);
30310             this.maskEl.top.setSize(Roo.lib.Dom.getDocumentWidth(), box.y - this.padding);
30311             this.maskEl.top.setLeft(0);
30312             this.maskEl.top.setTop(0);
30313             this.maskEl.top.show();
30314             
30315             this.maskEl.left.setStyle('position', 'absolute');
30316             this.maskEl.left.setStyle('z-index', 10000);
30317             this.maskEl.left.setSize(box.x - this.padding, box.height + this.padding * 2);
30318             this.maskEl.left.setLeft(0);
30319             this.maskEl.left.setTop(box.y - this.padding);
30320             this.maskEl.left.show();
30321
30322             this.maskEl.bottom.setStyle('position', 'absolute');
30323             this.maskEl.bottom.setStyle('z-index', 10000);
30324             this.maskEl.bottom.setSize(Roo.lib.Dom.getDocumentWidth(), Roo.lib.Dom.getDocumentHeight() - box.bottom - this.padding);
30325             this.maskEl.bottom.setLeft(0);
30326             this.maskEl.bottom.setTop(box.bottom + this.padding);
30327             this.maskEl.bottom.show();
30328
30329             this.maskEl.right.setStyle('position', 'absolute');
30330             this.maskEl.right.setStyle('z-index', 10000);
30331             this.maskEl.right.setSize(Roo.lib.Dom.getDocumentWidth() - box.right - this.padding, box.height + this.padding * 2);
30332             this.maskEl.right.setLeft(box.right + this.padding);
30333             this.maskEl.right.setTop(box.y - this.padding);
30334             this.maskEl.right.show();
30335
30336             this.intervalID = window.setInterval(function() {
30337                 Roo.form.BasicForm.popover.unmask();
30338             }, 10000);
30339
30340             window.onwheel = function(){ return false;};
30341             
30342             (function(){ this.isMasked = true; }).defer(500, this);
30343             
30344         },
30345         
30346         unmask : function()
30347         {
30348             if(!this.isApplied || !this.isMasked || !this.form || !this.target || !this.form.errorMask){
30349                 return;
30350             }
30351             
30352             this.maskEl.top.setStyle('position', 'absolute');
30353             this.maskEl.top.setSize(0, 0).setXY([0, 0]);
30354             this.maskEl.top.hide();
30355
30356             this.maskEl.left.setStyle('position', 'absolute');
30357             this.maskEl.left.setSize(0, 0).setXY([0, 0]);
30358             this.maskEl.left.hide();
30359
30360             this.maskEl.bottom.setStyle('position', 'absolute');
30361             this.maskEl.bottom.setSize(0, 0).setXY([0, 0]);
30362             this.maskEl.bottom.hide();
30363
30364             this.maskEl.right.setStyle('position', 'absolute');
30365             this.maskEl.right.setSize(0, 0).setXY([0, 0]);
30366             this.maskEl.right.hide();
30367             
30368             window.onwheel = function(){ return true;};
30369             
30370             if(this.intervalID){
30371                 window.clearInterval(this.intervalID);
30372                 this.intervalID = false;
30373             }
30374             
30375             this.isMasked = false;
30376             
30377         }
30378         
30379     }
30380     
30381 });/*
30382  * Based on:
30383  * Ext JS Library 1.1.1
30384  * Copyright(c) 2006-2007, Ext JS, LLC.
30385  *
30386  * Originally Released Under LGPL - original licence link has changed is not relivant.
30387  *
30388  * Fork - LGPL
30389  * <script type="text/javascript">
30390  */
30391
30392 /**
30393  * @class Roo.form.Form
30394  * @extends Roo.form.BasicForm
30395  * @children Roo.form.Column Roo.form.FieldSet Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
30396  * Adds the ability to dynamically render forms with JavaScript to {@link Roo.form.BasicForm}.
30397  * @constructor
30398  * @param {Object} config Configuration options
30399  */
30400 Roo.form.Form = function(config){
30401     var xitems =  [];
30402     if (config.items) {
30403         xitems = config.items;
30404         delete config.items;
30405     }
30406    
30407     
30408     Roo.form.Form.superclass.constructor.call(this, null, config);
30409     this.url = this.url || this.action;
30410     if(!this.root){
30411         this.root = new Roo.form.Layout(Roo.applyIf({
30412             id: Roo.id()
30413         }, config));
30414     }
30415     this.active = this.root;
30416     /**
30417      * Array of all the buttons that have been added to this form via {@link addButton}
30418      * @type Array
30419      */
30420     this.buttons = [];
30421     this.allItems = [];
30422     this.addEvents({
30423         /**
30424          * @event clientvalidation
30425          * If the monitorValid config option is true, this event fires repetitively to notify of valid state
30426          * @param {Form} this
30427          * @param {Boolean} valid true if the form has passed client-side validation
30428          */
30429         clientvalidation: true,
30430         /**
30431          * @event rendered
30432          * Fires when the form is rendered
30433          * @param {Roo.form.Form} form
30434          */
30435         rendered : true
30436     });
30437     
30438     if (this.progressUrl) {
30439             // push a hidden field onto the list of fields..
30440             this.addxtype( {
30441                     xns: Roo.form, 
30442                     xtype : 'Hidden', 
30443                     name : 'UPLOAD_IDENTIFIER' 
30444             });
30445         }
30446         
30447     
30448     Roo.each(xitems, this.addxtype, this);
30449     
30450 };
30451
30452 Roo.extend(Roo.form.Form, Roo.form.BasicForm, {
30453      /**
30454      * @cfg {Roo.Button} buttons[] buttons at bottom of form
30455      */
30456     
30457     /**
30458      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
30459      */
30460     /**
30461      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
30462      */
30463     /**
30464      * @cfg {String} buttonAlign (left|center|right)  Valid values are "left," "center" and "right" (defaults to "center")
30465      */
30466     buttonAlign:'center',
30467
30468     /**
30469      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75)
30470      */
30471     minButtonWidth:75,
30472
30473     /**
30474      * @cfg {String} labelAlign (left|top|right) Valid values are "left," "top" and "right" (defaults to "left").
30475      * This property cascades to child containers if not set.
30476      */
30477     labelAlign:'left',
30478
30479     /**
30480      * @cfg {Boolean} monitorValid If true the form monitors its valid state <b>client-side</b> and
30481      * fires a looping event with that state. This is required to bind buttons to the valid
30482      * state using the config value formBind:true on the button.
30483      */
30484     monitorValid : false,
30485
30486     /**
30487      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
30488      */
30489     monitorPoll : 200,
30490     
30491     /**
30492      * @cfg {String} progressUrl - Url to return progress data 
30493      */
30494     
30495     progressUrl : false,
30496     /**
30497      * @cfg {boolean|FormData} formData - true to use new 'FormData' post, or set to a new FormData({dom form}) Object, if
30498      * sending a formdata with extra parameters - eg uploaded elements.
30499      */
30500     
30501     formData : false,
30502     
30503     /**
30504      * Opens a new {@link Roo.form.Column} container in the layout stack. If fields are passed after the config, the
30505      * fields are added and the column is closed. If no fields are passed the column remains open
30506      * until end() is called.
30507      * @param {Object} config The config to pass to the column
30508      * @param {Field} field1 (optional)
30509      * @param {Field} field2 (optional)
30510      * @param {Field} etc (optional)
30511      * @return Column The column container object
30512      */
30513     column : function(c){
30514         var col = new Roo.form.Column(c);
30515         this.start(col);
30516         if(arguments.length > 1){ // duplicate code required because of Opera
30517             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
30518             this.end();
30519         }
30520         return col;
30521     },
30522
30523     /**
30524      * Opens a new {@link Roo.form.FieldSet} container in the layout stack. If fields are passed after the config, the
30525      * fields are added and the fieldset is closed. If no fields are passed the fieldset remains open
30526      * until end() is called.
30527      * @param {Object} config The config to pass to the fieldset
30528      * @param {Field} field1 (optional)
30529      * @param {Field} field2 (optional)
30530      * @param {Field} etc (optional)
30531      * @return FieldSet The fieldset container object
30532      */
30533     fieldset : function(c){
30534         var fs = new Roo.form.FieldSet(c);
30535         this.start(fs);
30536         if(arguments.length > 1){ // duplicate code required because of Opera
30537             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
30538             this.end();
30539         }
30540         return fs;
30541     },
30542
30543     /**
30544      * Opens a new {@link Roo.form.Layout} container in the layout stack. If fields are passed after the config, the
30545      * fields are added and the container is closed. If no fields are passed the container remains open
30546      * until end() is called.
30547      * @param {Object} config The config to pass to the Layout
30548      * @param {Field} field1 (optional)
30549      * @param {Field} field2 (optional)
30550      * @param {Field} etc (optional)
30551      * @return Layout The container object
30552      */
30553     container : function(c){
30554         var l = new Roo.form.Layout(c);
30555         this.start(l);
30556         if(arguments.length > 1){ // duplicate code required because of Opera
30557             this.add.apply(this, Array.prototype.slice.call(arguments, 1));
30558             this.end();
30559         }
30560         return l;
30561     },
30562
30563     /**
30564      * Opens the passed container in the layout stack. The container can be any {@link Roo.form.Layout} or subclass.
30565      * @param {Object} container A Roo.form.Layout or subclass of Layout
30566      * @return {Form} this
30567      */
30568     start : function(c){
30569         // cascade label info
30570         Roo.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls});
30571         this.active.stack.push(c);
30572         c.ownerCt = this.active;
30573         this.active = c;
30574         return this;
30575     },
30576
30577     /**
30578      * Closes the current open container
30579      * @return {Form} this
30580      */
30581     end : function(){
30582         if(this.active == this.root){
30583             return this;
30584         }
30585         this.active = this.active.ownerCt;
30586         return this;
30587     },
30588
30589     /**
30590      * Add Roo.form components to the current open container (e.g. column, fieldset, etc.).  Fields added via this method
30591      * can also be passed with an additional property of fieldLabel, which if supplied, will provide the text to display
30592      * as the label of the field.
30593      * @param {Field} field1
30594      * @param {Field} field2 (optional)
30595      * @param {Field} etc. (optional)
30596      * @return {Form} this
30597      */
30598     add : function(){
30599         this.active.stack.push.apply(this.active.stack, arguments);
30600         this.allItems.push.apply(this.allItems,arguments);
30601         var r = [];
30602         for(var i = 0, a = arguments, len = a.length; i < len; i++) {
30603             if(a[i].isFormField){
30604                 r.push(a[i]);
30605             }
30606         }
30607         if(r.length > 0){
30608             Roo.form.Form.superclass.add.apply(this, r);
30609         }
30610         return this;
30611     },
30612     
30613
30614     
30615     
30616     
30617      /**
30618      * Find any element that has been added to a form, using it's ID or name
30619      * This can include framesets, columns etc. along with regular fields..
30620      * @param {String} id - id or name to find.
30621      
30622      * @return {Element} e - or false if nothing found.
30623      */
30624     findbyId : function(id)
30625     {
30626         var ret = false;
30627         if (!id) {
30628             return ret;
30629         }
30630         Roo.each(this.allItems, function(f){
30631             if (f.id == id || f.name == id ){
30632                 ret = f;
30633                 return false;
30634             }
30635         });
30636         return ret;
30637     },
30638
30639     
30640     
30641     /**
30642      * Render this form into the passed container. This should only be called once!
30643      * @param {String/HTMLElement/Element} container The element this component should be rendered into
30644      * @return {Form} this
30645      */
30646     render : function(ct)
30647     {
30648         
30649         
30650         
30651         ct = Roo.get(ct);
30652         var o = this.autoCreate || {
30653             tag: 'form',
30654             method : this.method || 'POST',
30655             id : this.id || Roo.id()
30656         };
30657         this.initEl(ct.createChild(o));
30658
30659         this.root.render(this.el);
30660         
30661        
30662              
30663         this.items.each(function(f){
30664             f.render('x-form-el-'+f.id);
30665         });
30666
30667         if(this.buttons.length > 0){
30668             // tables are required to maintain order and for correct IE layout
30669             var tb = this.el.createChild({cls:'x-form-btns-ct', cn: {
30670                 cls:"x-form-btns x-form-btns-"+this.buttonAlign,
30671                 html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
30672             }}, null, true);
30673             var tr = tb.getElementsByTagName('tr')[0];
30674             for(var i = 0, len = this.buttons.length; i < len; i++) {
30675                 var b = this.buttons[i];
30676                 var td = document.createElement('td');
30677                 td.className = 'x-form-btn-td';
30678                 b.render(tr.appendChild(td));
30679             }
30680         }
30681         if(this.monitorValid){ // initialize after render
30682             this.startMonitoring();
30683         }
30684         this.fireEvent('rendered', this);
30685         return this;
30686     },
30687
30688     /**
30689      * Adds a button to the footer of the form - this <b>must</b> be called before the form is rendered.
30690      * @param {String/Object} config A string becomes the button text, an object can either be a Button config
30691      * object or a valid Roo.DomHelper element config
30692      * @param {Function} handler The function called when the button is clicked
30693      * @param {Object} scope (optional) The scope of the handler function
30694      * @return {Roo.Button}
30695      */
30696     addButton : function(config, handler, scope){
30697         var bc = {
30698             handler: handler,
30699             scope: scope,
30700             minWidth: this.minButtonWidth,
30701             hideParent:true
30702         };
30703         if(typeof config == "string"){
30704             bc.text = config;
30705         }else{
30706             Roo.apply(bc, config);
30707         }
30708         var btn = new Roo.Button(null, bc);
30709         this.buttons.push(btn);
30710         return btn;
30711     },
30712
30713      /**
30714      * Adds a series of form elements (using the xtype property as the factory method.
30715      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column, (and 'end' to close a block)
30716      * @param {Object} config 
30717      */
30718     
30719     addxtype : function()
30720     {
30721         var ar = Array.prototype.slice.call(arguments, 0);
30722         var ret = false;
30723         for(var i = 0; i < ar.length; i++) {
30724             if (!ar[i]) {
30725                 continue; // skip -- if this happends something invalid got sent, we 
30726                 // should ignore it, as basically that interface element will not show up
30727                 // and that should be pretty obvious!!
30728             }
30729             
30730             if (Roo.form[ar[i].xtype]) {
30731                 ar[i].form = this;
30732                 var fe = Roo.factory(ar[i], Roo.form);
30733                 if (!ret) {
30734                     ret = fe;
30735                 }
30736                 fe.form = this;
30737                 if (fe.store) {
30738                     fe.store.form = this;
30739                 }
30740                 if (fe.isLayout) {  
30741                          
30742                     this.start(fe);
30743                     this.allItems.push(fe);
30744                     if (fe.items && fe.addxtype) {
30745                         fe.addxtype.apply(fe, fe.items);
30746                         delete fe.items;
30747                     }
30748                      this.end();
30749                     continue;
30750                 }
30751                 
30752                 
30753                  
30754                 this.add(fe);
30755               //  console.log('adding ' + ar[i].xtype);
30756             }
30757             if (ar[i].xtype == 'Button') {  
30758                 //console.log('adding button');
30759                 //console.log(ar[i]);
30760                 this.addButton(ar[i]);
30761                 this.allItems.push(fe);
30762                 continue;
30763             }
30764             
30765             if (ar[i].xtype == 'end') { // so we can add fieldsets... / layout etc.
30766                 alert('end is not supported on xtype any more, use items');
30767             //    this.end();
30768             //    //console.log('adding end');
30769             }
30770             
30771         }
30772         return ret;
30773     },
30774     
30775     /**
30776      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
30777      * option "monitorValid"
30778      */
30779     startMonitoring : function(){
30780         if(!this.bound){
30781             this.bound = true;
30782             Roo.TaskMgr.start({
30783                 run : this.bindHandler,
30784                 interval : this.monitorPoll || 200,
30785                 scope: this
30786             });
30787         }
30788     },
30789
30790     /**
30791      * Stops monitoring of the valid state of this form
30792      */
30793     stopMonitoring : function(){
30794         this.bound = false;
30795     },
30796
30797     // private
30798     bindHandler : function(){
30799         if(!this.bound){
30800             return false; // stops binding
30801         }
30802         var valid = true;
30803         this.items.each(function(f){
30804             if(!f.isValid(true)){
30805                 valid = false;
30806                 return false;
30807             }
30808         });
30809         for(var i = 0, len = this.buttons.length; i < len; i++){
30810             var btn = this.buttons[i];
30811             if(btn.formBind === true && btn.disabled === valid){
30812                 btn.setDisabled(!valid);
30813             }
30814         }
30815         this.fireEvent('clientvalidation', this, valid);
30816     }
30817     
30818     
30819     
30820     
30821     
30822     
30823     
30824     
30825 });
30826
30827
30828 // back compat
30829 Roo.Form = Roo.form.Form;
30830 /*
30831  * Based on:
30832  * Ext JS Library 1.1.1
30833  * Copyright(c) 2006-2007, Ext JS, LLC.
30834  *
30835  * Originally Released Under LGPL - original licence link has changed is not relivant.
30836  *
30837  * Fork - LGPL
30838  * <script type="text/javascript">
30839  */
30840
30841 // as we use this in bootstrap.
30842 Roo.namespace('Roo.form');
30843  /**
30844  * @class Roo.form.Action
30845  * Internal Class used to handle form actions
30846  * @constructor
30847  * @param {Roo.form.BasicForm} el The form element or its id
30848  * @param {Object} config Configuration options
30849  */
30850
30851  
30852  
30853 // define the action interface
30854 Roo.form.Action = function(form, options){
30855     this.form = form;
30856     this.options = options || {};
30857 };
30858 /**
30859  * Client Validation Failed
30860  * @const 
30861  */
30862 Roo.form.Action.CLIENT_INVALID = 'client';
30863 /**
30864  * Server Validation Failed
30865  * @const 
30866  */
30867 Roo.form.Action.SERVER_INVALID = 'server';
30868  /**
30869  * Connect to Server Failed
30870  * @const 
30871  */
30872 Roo.form.Action.CONNECT_FAILURE = 'connect';
30873 /**
30874  * Reading Data from Server Failed
30875  * @const 
30876  */
30877 Roo.form.Action.LOAD_FAILURE = 'load';
30878
30879 Roo.form.Action.prototype = {
30880     type : 'default',
30881     failureType : undefined,
30882     response : undefined,
30883     result : undefined,
30884
30885     // interface method
30886     run : function(options){
30887
30888     },
30889
30890     // interface method
30891     success : function(response){
30892
30893     },
30894
30895     // interface method
30896     handleResponse : function(response){
30897
30898     },
30899
30900     // default connection failure
30901     failure : function(response){
30902         
30903         this.response = response;
30904         this.failureType = Roo.form.Action.CONNECT_FAILURE;
30905         this.form.afterAction(this, false);
30906     },
30907
30908     processResponse : function(response){
30909         this.response = response;
30910         if(!response.responseText){
30911             return true;
30912         }
30913         this.result = this.handleResponse(response);
30914         return this.result;
30915     },
30916
30917     // utility functions used internally
30918     getUrl : function(appendParams){
30919         var url = this.options.url || this.form.url || this.form.el.dom.action;
30920         if(appendParams){
30921             var p = this.getParams();
30922             if(p){
30923                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
30924             }
30925         }
30926         return url;
30927     },
30928
30929     getMethod : function(){
30930         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
30931     },
30932
30933     getParams : function(){
30934         var bp = this.form.baseParams;
30935         var p = this.options.params;
30936         if(p){
30937             if(typeof p == "object"){
30938                 p = Roo.urlEncode(Roo.applyIf(p, bp));
30939             }else if(typeof p == 'string' && bp){
30940                 p += '&' + Roo.urlEncode(bp);
30941             }
30942         }else if(bp){
30943             p = Roo.urlEncode(bp);
30944         }
30945         return p;
30946     },
30947
30948     createCallback : function(){
30949         return {
30950             success: this.success,
30951             failure: this.failure,
30952             scope: this,
30953             timeout: (this.form.timeout*1000),
30954             upload: this.form.fileUpload ? this.success : undefined
30955         };
30956     }
30957 };
30958
30959 Roo.form.Action.Submit = function(form, options){
30960     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
30961 };
30962
30963 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
30964     type : 'submit',
30965
30966     haveProgress : false,
30967     uploadComplete : false,
30968     
30969     // uploadProgress indicator.
30970     uploadProgress : function()
30971     {
30972         if (!this.form.progressUrl) {
30973             return;
30974         }
30975         
30976         if (!this.haveProgress) {
30977             Roo.MessageBox.progress("Uploading", "Uploading");
30978         }
30979         if (this.uploadComplete) {
30980            Roo.MessageBox.hide();
30981            return;
30982         }
30983         
30984         this.haveProgress = true;
30985    
30986         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
30987         
30988         var c = new Roo.data.Connection();
30989         c.request({
30990             url : this.form.progressUrl,
30991             params: {
30992                 id : uid
30993             },
30994             method: 'GET',
30995             success : function(req){
30996                //console.log(data);
30997                 var rdata = false;
30998                 var edata;
30999                 try  {
31000                    rdata = Roo.decode(req.responseText)
31001                 } catch (e) {
31002                     Roo.log("Invalid data from server..");
31003                     Roo.log(edata);
31004                     return;
31005                 }
31006                 if (!rdata || !rdata.success) {
31007                     Roo.log(rdata);
31008                     Roo.MessageBox.alert(Roo.encode(rdata));
31009                     return;
31010                 }
31011                 var data = rdata.data;
31012                 
31013                 if (this.uploadComplete) {
31014                    Roo.MessageBox.hide();
31015                    return;
31016                 }
31017                    
31018                 if (data){
31019                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
31020                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
31021                     );
31022                 }
31023                 this.uploadProgress.defer(2000,this);
31024             },
31025        
31026             failure: function(data) {
31027                 Roo.log('progress url failed ');
31028                 Roo.log(data);
31029             },
31030             scope : this
31031         });
31032            
31033     },
31034     
31035     
31036     run : function()
31037     {
31038         // run get Values on the form, so it syncs any secondary forms.
31039         this.form.getValues();
31040         
31041         var o = this.options;
31042         var method = this.getMethod();
31043         var isPost = method == 'POST';
31044         if(o.clientValidation === false || this.form.isValid()){
31045             
31046             if (this.form.progressUrl) {
31047                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
31048                     (new Date() * 1) + '' + Math.random());
31049                     
31050             } 
31051             
31052             
31053             Roo.Ajax.request(Roo.apply(this.createCallback(), {
31054                 form:this.form.el.dom,
31055                 url:this.getUrl(!isPost),
31056                 method: method,
31057                 params:isPost ? this.getParams() : null,
31058                 isUpload: this.form.fileUpload,
31059                 formData : this.form.formData
31060             }));
31061             
31062             this.uploadProgress();
31063
31064         }else if (o.clientValidation !== false){ // client validation failed
31065             this.failureType = Roo.form.Action.CLIENT_INVALID;
31066             this.form.afterAction(this, false);
31067         }
31068     },
31069
31070     success : function(response)
31071     {
31072         this.uploadComplete= true;
31073         if (this.haveProgress) {
31074             Roo.MessageBox.hide();
31075         }
31076         
31077         
31078         var result = this.processResponse(response);
31079         if(result === true || result.success){
31080             this.form.afterAction(this, true);
31081             return;
31082         }
31083         if(result.errors){
31084             this.form.markInvalid(result.errors);
31085             this.failureType = Roo.form.Action.SERVER_INVALID;
31086         }
31087         this.form.afterAction(this, false);
31088     },
31089     failure : function(response)
31090     {
31091         this.uploadComplete= true;
31092         if (this.haveProgress) {
31093             Roo.MessageBox.hide();
31094         }
31095         
31096         this.response = response;
31097         this.failureType = Roo.form.Action.CONNECT_FAILURE;
31098         this.form.afterAction(this, false);
31099     },
31100     
31101     handleResponse : function(response){
31102         if(this.form.errorReader){
31103             var rs = this.form.errorReader.read(response);
31104             var errors = [];
31105             if(rs.records){
31106                 for(var i = 0, len = rs.records.length; i < len; i++) {
31107                     var r = rs.records[i];
31108                     errors[i] = r.data;
31109                 }
31110             }
31111             if(errors.length < 1){
31112                 errors = null;
31113             }
31114             return {
31115                 success : rs.success,
31116                 errors : errors
31117             };
31118         }
31119         var ret = false;
31120         try {
31121             var rt = response.responseText;
31122             if (rt.match(/^\<!--\[CDATA\[/)) {
31123                 rt = rt.replace(/^\<!--\[CDATA\[/,'');
31124                 rt = rt.replace(/\]\]--\>$/,'');
31125             }
31126             
31127             ret = Roo.decode(rt);
31128         } catch (e) {
31129             ret = {
31130                 success: false,
31131                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
31132                 errors : []
31133             };
31134         }
31135         return ret;
31136         
31137     }
31138 });
31139
31140
31141 Roo.form.Action.Load = function(form, options){
31142     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
31143     this.reader = this.form.reader;
31144 };
31145
31146 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
31147     type : 'load',
31148
31149     run : function(){
31150         
31151         Roo.Ajax.request(Roo.apply(
31152                 this.createCallback(), {
31153                     method:this.getMethod(),
31154                     url:this.getUrl(false),
31155                     params:this.getParams()
31156         }));
31157     },
31158
31159     success : function(response){
31160         
31161         var result = this.processResponse(response);
31162         if(result === true || !result.success || !result.data){
31163             this.failureType = Roo.form.Action.LOAD_FAILURE;
31164             this.form.afterAction(this, false);
31165             return;
31166         }
31167         this.form.clearInvalid();
31168         this.form.setValues(result.data);
31169         this.form.afterAction(this, true);
31170     },
31171
31172     handleResponse : function(response){
31173         if(this.form.reader){
31174             var rs = this.form.reader.read(response);
31175             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
31176             return {
31177                 success : rs.success,
31178                 data : data
31179             };
31180         }
31181         return Roo.decode(response.responseText);
31182     }
31183 });
31184
31185 Roo.form.Action.ACTION_TYPES = {
31186     'load' : Roo.form.Action.Load,
31187     'submit' : Roo.form.Action.Submit
31188 };/*
31189  * Based on:
31190  * Ext JS Library 1.1.1
31191  * Copyright(c) 2006-2007, Ext JS, LLC.
31192  *
31193  * Originally Released Under LGPL - original licence link has changed is not relivant.
31194  *
31195  * Fork - LGPL
31196  * <script type="text/javascript">
31197  */
31198  
31199 /**
31200  * @class Roo.form.Layout
31201  * @extends Roo.Component
31202  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
31203  * Creates a container for layout and rendering of fields in an {@link Roo.form.Form}.
31204  * @constructor
31205  * @param {Object} config Configuration options
31206  */
31207 Roo.form.Layout = function(config){
31208     var xitems = [];
31209     if (config.items) {
31210         xitems = config.items;
31211         delete config.items;
31212     }
31213     Roo.form.Layout.superclass.constructor.call(this, config);
31214     this.stack = [];
31215     Roo.each(xitems, this.addxtype, this);
31216      
31217 };
31218
31219 Roo.extend(Roo.form.Layout, Roo.Component, {
31220     /**
31221      * @cfg {String/Object} autoCreate
31222      * A DomHelper element spec used to autocreate the layout (defaults to {tag: 'div', cls: 'x-form-ct'})
31223      */
31224     /**
31225      * @cfg {String/Object/Function} style
31226      * A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
31227      * a function which returns such a specification.
31228      */
31229     /**
31230      * @cfg {String} labelAlign (left|top|right)
31231      * Valid values are "left," "top" and "right" (defaults to "left")
31232      */
31233     /**
31234      * @cfg {Number} labelWidth
31235      * Fixed width in pixels of all field labels (defaults to undefined)
31236      */
31237     /**
31238      * @cfg {Boolean} clear
31239      * True to add a clearing element at the end of this layout, equivalent to CSS clear: both (defaults to true)
31240      */
31241     clear : true,
31242     /**
31243      * @cfg {String} labelSeparator
31244      * The separator to use after field labels (defaults to ':')
31245      */
31246     labelSeparator : ':',
31247     /**
31248      * @cfg {Boolean} hideLabels
31249      * True to suppress the display of field labels in this layout (defaults to false)
31250      */
31251     hideLabels : false,
31252
31253     // private
31254     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'},
31255     
31256     isLayout : true,
31257     
31258     // private
31259     onRender : function(ct, position){
31260         if(this.el){ // from markup
31261             this.el = Roo.get(this.el);
31262         }else {  // generate
31263             var cfg = this.getAutoCreate();
31264             this.el = ct.createChild(cfg, position);
31265         }
31266         if(this.style){
31267             this.el.applyStyles(this.style);
31268         }
31269         if(this.labelAlign){
31270             this.el.addClass('x-form-label-'+this.labelAlign);
31271         }
31272         if(this.hideLabels){
31273             this.labelStyle = "display:none";
31274             this.elementStyle = "padding-left:0;";
31275         }else{
31276             if(typeof this.labelWidth == 'number'){
31277                 this.labelStyle = "width:"+this.labelWidth+"px;";
31278                 this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";";
31279             }
31280             if(this.labelAlign == 'top'){
31281                 this.labelStyle = "width:auto;";
31282                 this.elementStyle = "padding-left:0;";
31283             }
31284         }
31285         var stack = this.stack;
31286         var slen = stack.length;
31287         if(slen > 0){
31288             if(!this.fieldTpl){
31289                 var t = new Roo.Template(
31290                     '<div class="x-form-item {5}">',
31291                         '<label for="{0}" style="{2}">{1}{4}</label>',
31292                         '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
31293                         '</div>',
31294                     '</div><div class="x-form-clear-left"></div>'
31295                 );
31296                 t.disableFormats = true;
31297                 t.compile();
31298                 Roo.form.Layout.prototype.fieldTpl = t;
31299             }
31300             for(var i = 0; i < slen; i++) {
31301                 if(stack[i].isFormField){
31302                     this.renderField(stack[i]);
31303                 }else{
31304                     this.renderComponent(stack[i]);
31305                 }
31306             }
31307         }
31308         if(this.clear){
31309             this.el.createChild({cls:'x-form-clear'});
31310         }
31311     },
31312
31313     // private
31314     renderField : function(f){
31315         f.fieldEl = Roo.get(this.fieldTpl.append(this.el, [
31316                f.id, //0
31317                f.fieldLabel, //1
31318                f.labelStyle||this.labelStyle||'', //2
31319                this.elementStyle||'', //3
31320                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, //4
31321                f.itemCls||this.itemCls||''  //5
31322        ], true).getPrevSibling());
31323     },
31324
31325     // private
31326     renderComponent : function(c){
31327         c.render(c.isLayout ? this.el : this.el.createChild());    
31328     },
31329     /**
31330      * Adds a object form elements (using the xtype property as the factory method.)
31331      * Valid xtypes are:  TextField, TextArea .... Button, Layout, FieldSet, Column
31332      * @param {Object} config 
31333      */
31334     addxtype : function(o)
31335     {
31336         // create the lement.
31337         o.form = this.form;
31338         var fe = Roo.factory(o, Roo.form);
31339         this.form.allItems.push(fe);
31340         this.stack.push(fe);
31341         
31342         if (fe.isFormField) {
31343             this.form.items.add(fe);
31344         }
31345          
31346         return fe;
31347     }
31348 });
31349
31350
31351 /**
31352  * @class Roo.form.Column
31353  * @extends Roo.form.Layout
31354  * @children Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
31355  * Creates a column container for layout and rendering of fields in an {@link Roo.form.Form}.
31356  * @constructor
31357  * @param {Object} config Configuration options
31358  */
31359 Roo.form.Column = function(config){
31360     Roo.form.Column.superclass.constructor.call(this, config);
31361 };
31362
31363 Roo.extend(Roo.form.Column, Roo.form.Layout, {
31364     /**
31365      * @cfg {Number/String} width
31366      * The fixed width of the column in pixels or CSS value (defaults to "auto")
31367      */
31368     /**
31369      * @cfg {String/Object} autoCreate
31370      * A DomHelper element spec used to autocreate the column (defaults to {tag: 'div', cls: 'x-form-ct x-form-column'})
31371      */
31372
31373     // private
31374     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'},
31375
31376     // private
31377     onRender : function(ct, position){
31378         Roo.form.Column.superclass.onRender.call(this, ct, position);
31379         if(this.width){
31380             this.el.setWidth(this.width);
31381         }
31382     }
31383 });
31384
31385 /**
31386  * @class Roo.form.Row
31387  * @extends Roo.form.Layout
31388  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem Roo.form.FieldSet
31389  * Creates a row container for layout and rendering of fields in an {@link Roo.form.Form}.
31390  * @constructor
31391  * @param {Object} config Configuration options
31392  */
31393
31394  
31395 Roo.form.Row = function(config){
31396     Roo.form.Row.superclass.constructor.call(this, config);
31397 };
31398  
31399 Roo.extend(Roo.form.Row, Roo.form.Layout, {
31400       /**
31401      * @cfg {Number/String} width
31402      * The fixed width of the column in pixels or CSS value (defaults to "auto")
31403      */
31404     /**
31405      * @cfg {Number/String} height
31406      * The fixed height of the column in pixels or CSS value (defaults to "auto")
31407      */
31408     defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-row'},
31409     
31410     padWidth : 20,
31411     // private
31412     onRender : function(ct, position){
31413         //console.log('row render');
31414         if(!this.rowTpl){
31415             var t = new Roo.Template(
31416                 '<div class="x-form-item {5}" style="float:left;width:{6}px">',
31417                     '<label for="{0}" style="{2}">{1}{4}</label>',
31418                     '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
31419                     '</div>',
31420                 '</div>'
31421             );
31422             t.disableFormats = true;
31423             t.compile();
31424             Roo.form.Layout.prototype.rowTpl = t;
31425         }
31426         this.fieldTpl = this.rowTpl;
31427         
31428         //console.log('lw' + this.labelWidth +', la:' + this.labelAlign);
31429         var labelWidth = 100;
31430         
31431         if ((this.labelAlign != 'top')) {
31432             if (typeof this.labelWidth == 'number') {
31433                 labelWidth = this.labelWidth
31434             }
31435             this.padWidth =  20 + labelWidth;
31436             
31437         }
31438         
31439         Roo.form.Column.superclass.onRender.call(this, ct, position);
31440         if(this.width){
31441             this.el.setWidth(this.width);
31442         }
31443         if(this.height){
31444             this.el.setHeight(this.height);
31445         }
31446     },
31447     
31448     // private
31449     renderField : function(f){
31450         f.fieldEl = this.fieldTpl.append(this.el, [
31451                f.id, f.fieldLabel,
31452                f.labelStyle||this.labelStyle||'',
31453                this.elementStyle||'',
31454                typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator,
31455                f.itemCls||this.itemCls||'',
31456                f.width ? f.width + this.padWidth : 160 + this.padWidth
31457        ],true);
31458     }
31459 });
31460  
31461
31462 /**
31463  * @class Roo.form.FieldSet
31464  * @extends Roo.form.Layout
31465  * @children Roo.form.Column Roo.form.Row Roo.form.Field Roo.Button Roo.form.TextItem
31466  * Creates a fieldset container for layout and rendering of fields in an {@link Roo.form.Form}.
31467  * @constructor
31468  * @param {Object} config Configuration options
31469  */
31470 Roo.form.FieldSet = function(config){
31471     Roo.form.FieldSet.superclass.constructor.call(this, config);
31472 };
31473
31474 Roo.extend(Roo.form.FieldSet, Roo.form.Layout, {
31475     /**
31476      * @cfg {String} legend
31477      * The text to display as the legend for the FieldSet (defaults to '')
31478      */
31479     /**
31480      * @cfg {String/Object} autoCreate
31481      * A DomHelper element spec used to autocreate the fieldset (defaults to {tag: 'fieldset', cn: {tag:'legend'}})
31482      */
31483
31484     // private
31485     defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}},
31486
31487     // private
31488     onRender : function(ct, position){
31489         Roo.form.FieldSet.superclass.onRender.call(this, ct, position);
31490         if(this.legend){
31491             this.setLegend(this.legend);
31492         }
31493     },
31494
31495     // private
31496     setLegend : function(text){
31497         if(this.rendered){
31498             this.el.child('legend').update(text);
31499         }
31500     }
31501 });/*
31502  * Based on:
31503  * Ext JS Library 1.1.1
31504  * Copyright(c) 2006-2007, Ext JS, LLC.
31505  *
31506  * Originally Released Under LGPL - original licence link has changed is not relivant.
31507  *
31508  * Fork - LGPL
31509  * <script type="text/javascript">
31510  */
31511 /**
31512  * @class Roo.form.VTypes
31513  * Overridable validation definitions. The validations provided are basic and intended to be easily customizable and extended.
31514  * @static
31515  */
31516 Roo.form.VTypes = function(){
31517     // closure these in so they are only created once.
31518     var alpha = /^[a-zA-Z_]+$/;
31519     var alphanum = /^[a-zA-Z0-9_]+$/;
31520     var email = /^([\w'-]+)(\.[\w'-]+)*@([\w-]+\.){1,5}([A-Za-z]){2,24}$/;
31521     var url = /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
31522     var urlWeb = /^((https?):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
31523
31524     // All these messages and functions are configurable
31525     return {
31526         /**
31527          * The function used to validate email addresses
31528          * @param {String} value The email address
31529          */
31530         email : function(v){
31531             return email.test(v);
31532         },
31533         /**
31534          * The error text to display when the email validation function returns false
31535          * @type String
31536          */
31537         emailText : 'This field should be an e-mail address in the format "user@domain.com"',
31538         /**
31539          * The keystroke filter mask to be applied on email input
31540          * @type RegExp
31541          */
31542         emailMask : /[a-z0-9_\.\-@]/i,
31543
31544         /**
31545          * The function used to validate URLs
31546          * @param {String} value The URL
31547          */
31548         url : function(v){
31549             return url.test(v);
31550         },
31551         /**
31552          * The funciton used to validate URLs (only allow schemes 'https' and 'http')
31553          * @param {String} v The URL
31554          */
31555         urlWeb : function(v) {
31556             return urlWeb.test(v);
31557         },
31558         /**
31559          * The error text to display when the url validation function returns false
31560          * @type String
31561          */
31562         urlText : 'This field should be a URL in the format "http:/'+'/www.domain.com"',
31563         
31564         /**
31565          * The function used to validate alpha values
31566          * @param {String} value The value
31567          */
31568         alpha : function(v){
31569             return alpha.test(v);
31570         },
31571         /**
31572          * The error text to display when the alpha validation function returns false
31573          * @type String
31574          */
31575         alphaText : 'This field should only contain letters and _',
31576         /**
31577          * The keystroke filter mask to be applied on alpha input
31578          * @type RegExp
31579          */
31580         alphaMask : /[a-z_]/i,
31581
31582         /**
31583          * The function used to validate alphanumeric values
31584          * @param {String} value The value
31585          */
31586         alphanum : function(v){
31587             return alphanum.test(v);
31588         },
31589         /**
31590          * The error text to display when the alphanumeric validation function returns false
31591          * @type String
31592          */
31593         alphanumText : 'This field should only contain letters, numbers and _',
31594         /**
31595          * The keystroke filter mask to be applied on alphanumeric input
31596          * @type RegExp
31597          */
31598         alphanumMask : /[a-z0-9_]/i
31599     };
31600 }();//<script type="text/javascript">
31601
31602 /**
31603  * @class Roo.form.FCKeditor
31604  * @extends Roo.form.TextArea
31605  * Wrapper around the FCKEditor http://www.fckeditor.net
31606  * @constructor
31607  * Creates a new FCKeditor
31608  * @param {Object} config Configuration options
31609  */
31610 Roo.form.FCKeditor = function(config){
31611     Roo.form.FCKeditor.superclass.constructor.call(this, config);
31612     this.addEvents({
31613          /**
31614          * @event editorinit
31615          * Fired when the editor is initialized - you can add extra handlers here..
31616          * @param {FCKeditor} this
31617          * @param {Object} the FCK object.
31618          */
31619         editorinit : true
31620     });
31621     
31622     
31623 };
31624 Roo.form.FCKeditor.editors = { };
31625 Roo.extend(Roo.form.FCKeditor, Roo.form.TextArea,
31626 {
31627     //defaultAutoCreate : {
31628     //    tag : "textarea",style   : "width:100px;height:60px;" ,autocomplete    : "off"
31629     //},
31630     // private
31631     /**
31632      * @cfg {Object} fck options - see fck manual for details.
31633      */
31634     fckconfig : false,
31635     
31636     /**
31637      * @cfg {Object} fck toolbar set (Basic or Default)
31638      */
31639     toolbarSet : 'Basic',
31640     /**
31641      * @cfg {Object} fck BasePath
31642      */ 
31643     basePath : '/fckeditor/',
31644     
31645     
31646     frame : false,
31647     
31648     value : '',
31649     
31650    
31651     onRender : function(ct, position)
31652     {
31653         if(!this.el){
31654             this.defaultAutoCreate = {
31655                 tag: "textarea",
31656                 style:"width:300px;height:60px;",
31657                 autocomplete: "new-password"
31658             };
31659         }
31660         Roo.form.FCKeditor.superclass.onRender.call(this, ct, position);
31661         /*
31662         if(this.grow){
31663             this.textSizeEl = Roo.DomHelper.append(document.body, {tag: "pre", cls: "x-form-grow-sizer"});
31664             if(this.preventScrollbars){
31665                 this.el.setStyle("overflow", "hidden");
31666             }
31667             this.el.setHeight(this.growMin);
31668         }
31669         */
31670         //console.log('onrender' + this.getId() );
31671         Roo.form.FCKeditor.editors[this.getId()] = this;
31672          
31673
31674         this.replaceTextarea() ;
31675         
31676     },
31677     
31678     getEditor : function() {
31679         return this.fckEditor;
31680     },
31681     /**
31682      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
31683      * @param {Mixed} value The value to set
31684      */
31685     
31686     
31687     setValue : function(value)
31688     {
31689         //console.log('setValue: ' + value);
31690         
31691         if(typeof(value) == 'undefined') { // not sure why this is happending...
31692             return;
31693         }
31694         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
31695         
31696         //if(!this.el || !this.getEditor()) {
31697         //    this.value = value;
31698             //this.setValue.defer(100,this,[value]);    
31699         //    return;
31700         //} 
31701         
31702         if(!this.getEditor()) {
31703             return;
31704         }
31705         
31706         this.getEditor().SetData(value);
31707         
31708         //
31709
31710     },
31711
31712     /**
31713      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
31714      * @return {Mixed} value The field value
31715      */
31716     getValue : function()
31717     {
31718         
31719         if (this.frame && this.frame.dom.style.display == 'none') {
31720             return Roo.form.FCKeditor.superclass.getValue.call(this);
31721         }
31722         
31723         if(!this.el || !this.getEditor()) {
31724            
31725            // this.getValue.defer(100,this); 
31726             return this.value;
31727         }
31728        
31729         
31730         var value=this.getEditor().GetData();
31731         Roo.form.FCKeditor.superclass.setValue.apply(this,[value]);
31732         return Roo.form.FCKeditor.superclass.getValue.call(this);
31733         
31734
31735     },
31736
31737     /**
31738      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
31739      * @return {Mixed} value The field value
31740      */
31741     getRawValue : function()
31742     {
31743         if (this.frame && this.frame.dom.style.display == 'none') {
31744             return Roo.form.FCKeditor.superclass.getRawValue.call(this);
31745         }
31746         
31747         if(!this.el || !this.getEditor()) {
31748             //this.getRawValue.defer(100,this); 
31749             return this.value;
31750             return;
31751         }
31752         
31753         
31754         
31755         var value=this.getEditor().GetData();
31756         Roo.form.FCKeditor.superclass.setRawValue.apply(this,[value]);
31757         return Roo.form.FCKeditor.superclass.getRawValue.call(this);
31758          
31759     },
31760     
31761     setSize : function(w,h) {
31762         
31763         
31764         
31765         //if (this.frame && this.frame.dom.style.display == 'none') {
31766         //    Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
31767         //    return;
31768         //}
31769         //if(!this.el || !this.getEditor()) {
31770         //    this.setSize.defer(100,this, [w,h]); 
31771         //    return;
31772         //}
31773         
31774         
31775         
31776         Roo.form.FCKeditor.superclass.setSize.apply(this, [w, h]);
31777         
31778         this.frame.dom.setAttribute('width', w);
31779         this.frame.dom.setAttribute('height', h);
31780         this.frame.setSize(w,h);
31781         
31782     },
31783     
31784     toggleSourceEdit : function(value) {
31785         
31786       
31787          
31788         this.el.dom.style.display = value ? '' : 'none';
31789         this.frame.dom.style.display = value ?  'none' : '';
31790         
31791     },
31792     
31793     
31794     focus: function(tag)
31795     {
31796         if (this.frame.dom.style.display == 'none') {
31797             return Roo.form.FCKeditor.superclass.focus.call(this);
31798         }
31799         if(!this.el || !this.getEditor()) {
31800             this.focus.defer(100,this, [tag]); 
31801             return;
31802         }
31803         
31804         
31805         
31806         
31807         var tgs = this.getEditor().EditorDocument.getElementsByTagName(tag);
31808         this.getEditor().Focus();
31809         if (tgs.length) {
31810             if (!this.getEditor().Selection.GetSelection()) {
31811                 this.focus.defer(100,this, [tag]); 
31812                 return;
31813             }
31814             
31815             
31816             var r = this.getEditor().EditorDocument.createRange();
31817             r.setStart(tgs[0],0);
31818             r.setEnd(tgs[0],0);
31819             this.getEditor().Selection.GetSelection().removeAllRanges();
31820             this.getEditor().Selection.GetSelection().addRange(r);
31821             this.getEditor().Focus();
31822         }
31823         
31824     },
31825     
31826     
31827     
31828     replaceTextarea : function()
31829     {
31830         if ( document.getElementById( this.getId() + '___Frame' ) ) {
31831             return ;
31832         }
31833         //if ( !this.checkBrowser || this._isCompatibleBrowser() )
31834         //{
31835             // We must check the elements firstly using the Id and then the name.
31836         var oTextarea = document.getElementById( this.getId() );
31837         
31838         var colElementsByName = document.getElementsByName( this.getId() ) ;
31839          
31840         oTextarea.style.display = 'none' ;
31841
31842         if ( oTextarea.tabIndex ) {            
31843             this.TabIndex = oTextarea.tabIndex ;
31844         }
31845         
31846         this._insertHtmlBefore( this._getConfigHtml(), oTextarea ) ;
31847         this._insertHtmlBefore( this._getIFrameHtml(), oTextarea ) ;
31848         this.frame = Roo.get(this.getId() + '___Frame')
31849     },
31850     
31851     _getConfigHtml : function()
31852     {
31853         var sConfig = '' ;
31854
31855         for ( var o in this.fckconfig ) {
31856             sConfig += sConfig.length > 0  ? '&amp;' : '';
31857             sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.fckconfig[o] ) ;
31858         }
31859
31860         return '<input type="hidden" id="' + this.getId() + '___Config" value="' + sConfig + '" style="display:none" />' ;
31861     },
31862     
31863     
31864     _getIFrameHtml : function()
31865     {
31866         var sFile = 'fckeditor.html' ;
31867         /* no idea what this is about..
31868         try
31869         {
31870             if ( (/fcksource=true/i).test( window.top.location.search ) )
31871                 sFile = 'fckeditor.original.html' ;
31872         }
31873         catch (e) { 
31874         */
31875
31876         var sLink = this.basePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.getId() ) ;
31877         sLink += this.toolbarSet ? ( '&amp;Toolbar=' + this.toolbarSet)  : '';
31878         
31879         
31880         var html = '<iframe id="' + this.getId() +
31881             '___Frame" src="' + sLink +
31882             '" width="' + this.width +
31883             '" height="' + this.height + '"' +
31884             (this.tabIndex ?  ' tabindex="' + this.tabIndex + '"' :'' ) +
31885             ' frameborder="0" scrolling="no"></iframe>' ;
31886
31887         return html ;
31888     },
31889     
31890     _insertHtmlBefore : function( html, element )
31891     {
31892         if ( element.insertAdjacentHTML )       {
31893             // IE
31894             element.insertAdjacentHTML( 'beforeBegin', html ) ;
31895         } else { // Gecko
31896             var oRange = document.createRange() ;
31897             oRange.setStartBefore( element ) ;
31898             var oFragment = oRange.createContextualFragment( html );
31899             element.parentNode.insertBefore( oFragment, element ) ;
31900         }
31901     }
31902     
31903     
31904   
31905     
31906     
31907     
31908     
31909
31910 });
31911
31912 //Roo.reg('fckeditor', Roo.form.FCKeditor);
31913
31914 function FCKeditor_OnComplete(editorInstance){
31915     var f = Roo.form.FCKeditor.editors[editorInstance.Name];
31916     f.fckEditor = editorInstance;
31917     //console.log("loaded");
31918     f.fireEvent('editorinit', f, editorInstance);
31919
31920   
31921
31922  
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938 //<script type="text/javascript">
31939 /**
31940  * @class Roo.form.GridField
31941  * @extends Roo.form.Field
31942  * Embed a grid (or editable grid into a form)
31943  * STATUS ALPHA
31944  * 
31945  * This embeds a grid in a form, the value of the field should be the json encoded array of rows
31946  * it needs 
31947  * xgrid.store = Roo.data.Store
31948  * xgrid.store.proxy = Roo.data.MemoryProxy (data = [] )
31949  * xgrid.store.reader = Roo.data.JsonReader 
31950  * 
31951  * 
31952  * @constructor
31953  * Creates a new GridField
31954  * @param {Object} config Configuration options
31955  */
31956 Roo.form.GridField = function(config){
31957     Roo.form.GridField.superclass.constructor.call(this, config);
31958      
31959 };
31960
31961 Roo.extend(Roo.form.GridField, Roo.form.Field,  {
31962     /**
31963      * @cfg {Number} width  - used to restrict width of grid..
31964      */
31965     width : 100,
31966     /**
31967      * @cfg {Number} height - used to restrict height of grid..
31968      */
31969     height : 50,
31970      /**
31971      * @cfg {Object} xgrid (xtype'd description of grid) { xtype : 'Grid', dataSource: .... }
31972          * 
31973          *}
31974      */
31975     xgrid : false, 
31976     /**
31977      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
31978      * {tag: "input", type: "checkbox", autocomplete: "off"})
31979      */
31980    // defaultAutoCreate : { tag: 'div' },
31981     defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'new-password'},
31982     /**
31983      * @cfg {String} addTitle Text to include for adding a title.
31984      */
31985     addTitle : false,
31986     //
31987     onResize : function(){
31988         Roo.form.Field.superclass.onResize.apply(this, arguments);
31989     },
31990
31991     initEvents : function(){
31992         // Roo.form.Checkbox.superclass.initEvents.call(this);
31993         // has no events...
31994        
31995     },
31996
31997
31998     getResizeEl : function(){
31999         return this.wrap;
32000     },
32001
32002     getPositionEl : function(){
32003         return this.wrap;
32004     },
32005
32006     // private
32007     onRender : function(ct, position){
32008         
32009         this.style = this.style || 'overflow: hidden; border:1px solid #c3daf9;';
32010         var style = this.style;
32011         delete this.style;
32012         
32013         Roo.form.GridField.superclass.onRender.call(this, ct, position);
32014         this.wrap = this.el.wrap({cls: ''}); // not sure why ive done thsi...
32015         this.viewEl = this.wrap.createChild({ tag: 'div' });
32016         if (style) {
32017             this.viewEl.applyStyles(style);
32018         }
32019         if (this.width) {
32020             this.viewEl.setWidth(this.width);
32021         }
32022         if (this.height) {
32023             this.viewEl.setHeight(this.height);
32024         }
32025         //if(this.inputValue !== undefined){
32026         //this.setValue(this.value);
32027         
32028         
32029         this.grid = new Roo.grid[this.xgrid.xtype](this.viewEl, this.xgrid);
32030         
32031         
32032         this.grid.render();
32033         this.grid.getDataSource().on('remove', this.refreshValue, this);
32034         this.grid.getDataSource().on('update', this.refreshValue, this);
32035         this.grid.on('afteredit', this.refreshValue, this);
32036  
32037     },
32038      
32039     
32040     /**
32041      * Sets the value of the item. 
32042      * @param {String} either an object  or a string..
32043      */
32044     setValue : function(v){
32045         //this.value = v;
32046         v = v || []; // empty set..
32047         // this does not seem smart - it really only affects memoryproxy grids..
32048         if (this.grid && this.grid.getDataSource() && typeof(v) != 'undefined') {
32049             var ds = this.grid.getDataSource();
32050             // assumes a json reader..
32051             var data = {}
32052             data[ds.reader.meta.root ] =  typeof(v) == 'string' ? Roo.decode(v) : v;
32053             ds.loadData( data);
32054         }
32055         // clear selection so it does not get stale.
32056         if (this.grid.sm) { 
32057             this.grid.sm.clearSelections();
32058         }
32059         
32060         Roo.form.GridField.superclass.setValue.call(this, v);
32061         this.refreshValue();
32062         // should load data in the grid really....
32063     },
32064     
32065     // private
32066     refreshValue: function() {
32067          var val = [];
32068         this.grid.getDataSource().each(function(r) {
32069             val.push(r.data);
32070         });
32071         this.el.dom.value = Roo.encode(val);
32072     }
32073     
32074      
32075     
32076     
32077 });/*
32078  * Based on:
32079  * Ext JS Library 1.1.1
32080  * Copyright(c) 2006-2007, Ext JS, LLC.
32081  *
32082  * Originally Released Under LGPL - original licence link has changed is not relivant.
32083  *
32084  * Fork - LGPL
32085  * <script type="text/javascript">
32086  */
32087 /**
32088  * @class Roo.form.DisplayField
32089  * @extends Roo.form.Field
32090  * A generic Field to display non-editable data.
32091  * @cfg {Boolean} closable (true|false) default false
32092  * @constructor
32093  * Creates a new Display Field item.
32094  * @param {Object} config Configuration options
32095  */
32096 Roo.form.DisplayField = function(config){
32097     Roo.form.DisplayField.superclass.constructor.call(this, config);
32098     
32099     this.addEvents({
32100         /**
32101          * @event close
32102          * Fires after the click the close btn
32103              * @param {Roo.form.DisplayField} this
32104              */
32105         close : true
32106     });
32107 };
32108
32109 Roo.extend(Roo.form.DisplayField, Roo.form.TextField,  {
32110     inputType:      'hidden',
32111     allowBlank:     true,
32112     readOnly:         true,
32113     
32114  
32115     /**
32116      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
32117      */
32118     focusClass : undefined,
32119     /**
32120      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
32121      */
32122     fieldClass: 'x-form-field',
32123     
32124      /**
32125      * @cfg {Function} valueRenderer The renderer for the field (so you can reformat output). should return raw HTML
32126      */
32127     valueRenderer: undefined,
32128     
32129     width: 100,
32130     /**
32131      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
32132      * {tag: "input", type: "checkbox", autocomplete: "off"})
32133      */
32134      
32135  //   defaultAutoCreate : { tag: 'input', type: 'hidden', autocomplete: 'off'},
32136  
32137     closable : false,
32138     
32139     onResize : function(){
32140         Roo.form.DisplayField.superclass.onResize.apply(this, arguments);
32141         
32142     },
32143
32144     initEvents : function(){
32145         // Roo.form.Checkbox.superclass.initEvents.call(this);
32146         // has no events...
32147         
32148         if(this.closable){
32149             this.closeEl.on('click', this.onClose, this);
32150         }
32151        
32152     },
32153
32154
32155     getResizeEl : function(){
32156         return this.wrap;
32157     },
32158
32159     getPositionEl : function(){
32160         return this.wrap;
32161     },
32162
32163     // private
32164     onRender : function(ct, position){
32165         
32166         Roo.form.DisplayField.superclass.onRender.call(this, ct, position);
32167         //if(this.inputValue !== undefined){
32168         this.wrap = this.el.wrap();
32169         
32170         this.viewEl = this.wrap.createChild({ tag: 'div', cls: 'x-form-displayfield'});
32171         
32172         if(this.closable){
32173             this.closeEl = this.wrap.createChild({ tag: 'div', cls: 'x-dlg-close'});
32174         }
32175         
32176         if (this.bodyStyle) {
32177             this.viewEl.applyStyles(this.bodyStyle);
32178         }
32179         //this.viewEl.setStyle('padding', '2px');
32180         
32181         this.setValue(this.value);
32182         
32183     },
32184 /*
32185     // private
32186     initValue : Roo.emptyFn,
32187
32188   */
32189
32190         // private
32191     onClick : function(){
32192         
32193     },
32194
32195     /**
32196      * Sets the checked state of the checkbox.
32197      * @param {Boolean/String} checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
32198      */
32199     setValue : function(v){
32200         this.value = v;
32201         var html = this.valueRenderer ?  this.valueRenderer(v) : String.format('{0}', v);
32202         // this might be called before we have a dom element..
32203         if (!this.viewEl) {
32204             return;
32205         }
32206         this.viewEl.dom.innerHTML = html;
32207         Roo.form.DisplayField.superclass.setValue.call(this, v);
32208
32209     },
32210     
32211     onClose : function(e)
32212     {
32213         e.preventDefault();
32214         
32215         this.fireEvent('close', this);
32216     }
32217 });/*
32218  * 
32219  * Licence- LGPL
32220  * 
32221  */
32222
32223 /**
32224  * @class Roo.form.DayPicker
32225  * @extends Roo.form.Field
32226  * A Day picker show [M] [T] [W] ....
32227  * @constructor
32228  * Creates a new Day Picker
32229  * @param {Object} config Configuration options
32230  */
32231 Roo.form.DayPicker= function(config){
32232     Roo.form.DayPicker.superclass.constructor.call(this, config);
32233      
32234 };
32235
32236 Roo.extend(Roo.form.DayPicker, Roo.form.Field,  {
32237     /**
32238      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
32239      */
32240     focusClass : undefined,
32241     /**
32242      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to "x-form-field")
32243      */
32244     fieldClass: "x-form-field",
32245    
32246     /**
32247      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
32248      * {tag: "input", type: "checkbox", autocomplete: "off"})
32249      */
32250     defaultAutoCreate : { tag: "input", type: 'hidden', autocomplete: "new-password"},
32251     
32252    
32253     actionMode : 'viewEl', 
32254     //
32255     // private
32256  
32257     inputType : 'hidden',
32258     
32259      
32260     inputElement: false, // real input element?
32261     basedOn: false, // ????
32262     
32263     isFormField: true, // not sure where this is needed!!!!
32264
32265     onResize : function(){
32266         Roo.form.Checkbox.superclass.onResize.apply(this, arguments);
32267         if(!this.boxLabel){
32268             this.el.alignTo(this.wrap, 'c-c');
32269         }
32270     },
32271
32272     initEvents : function(){
32273         Roo.form.Checkbox.superclass.initEvents.call(this);
32274         this.el.on("click", this.onClick,  this);
32275         this.el.on("change", this.onClick,  this);
32276     },
32277
32278
32279     getResizeEl : function(){
32280         return this.wrap;
32281     },
32282
32283     getPositionEl : function(){
32284         return this.wrap;
32285     },
32286
32287     
32288     // private
32289     onRender : function(ct, position){
32290         Roo.form.Checkbox.superclass.onRender.call(this, ct, position);
32291        
32292         this.wrap = this.el.wrap({cls: 'x-form-daypick-item '});
32293         
32294         var r1 = '<table><tr>';
32295         var r2 = '<tr class="x-form-daypick-icons">';
32296         for (var i=0; i < 7; i++) {
32297             r1+= '<td><div>' + Date.dayNames[i].substring(0,3) + '</div></td>';
32298             r2+= '<td><img class="x-menu-item-icon" src="' + Roo.BLANK_IMAGE_URL  +'"></td>';
32299         }
32300         
32301         var viewEl = this.wrap.createChild( r1 + '</tr>' + r2 + '</tr></table>');
32302         viewEl.select('img').on('click', this.onClick, this);
32303         this.viewEl = viewEl;   
32304         
32305         
32306         // this will not work on Chrome!!!
32307         this.el.on('DOMAttrModified', this.setFromHidden,  this); //ff
32308         this.el.on('propertychange', this.setFromHidden,  this);  //ie
32309         
32310         
32311           
32312
32313     },
32314
32315     // private
32316     initValue : Roo.emptyFn,
32317
32318     /**
32319      * Returns the checked state of the checkbox.
32320      * @return {Boolean} True if checked, else false
32321      */
32322     getValue : function(){
32323         return this.el.dom.value;
32324         
32325     },
32326
32327         // private
32328     onClick : function(e){ 
32329         //this.setChecked(!this.checked);
32330         Roo.get(e.target).toggleClass('x-menu-item-checked');
32331         this.refreshValue();
32332         //if(this.el.dom.checked != this.checked){
32333         //    this.setValue(this.el.dom.checked);
32334        // }
32335     },
32336     
32337     // private
32338     refreshValue : function()
32339     {
32340         var val = '';
32341         this.viewEl.select('img',true).each(function(e,i,n)  {
32342             val += e.is(".x-menu-item-checked") ? String(n) : '';
32343         });
32344         this.setValue(val, true);
32345     },
32346
32347     /**
32348      * Sets the checked state of the checkbox.
32349      * On is always based on a string comparison between inputValue and the param.
32350      * @param {Boolean/String} value - the value to set 
32351      * @param {Boolean/String} suppressEvent - whether to suppress the checkchange event.
32352      */
32353     setValue : function(v,suppressEvent){
32354         if (!this.el.dom) {
32355             return;
32356         }
32357         var old = this.el.dom.value ;
32358         this.el.dom.value = v;
32359         if (suppressEvent) {
32360             return ;
32361         }
32362          
32363         // update display..
32364         this.viewEl.select('img',true).each(function(e,i,n)  {
32365             
32366             var on = e.is(".x-menu-item-checked");
32367             var newv = v.indexOf(String(n)) > -1;
32368             if (on != newv) {
32369                 e.toggleClass('x-menu-item-checked');
32370             }
32371             
32372         });
32373         
32374         
32375         this.fireEvent('change', this, v, old);
32376         
32377         
32378     },
32379    
32380     // handle setting of hidden value by some other method!!?!?
32381     setFromHidden: function()
32382     {
32383         if(!this.el){
32384             return;
32385         }
32386         //console.log("SET FROM HIDDEN");
32387         //alert('setFrom hidden');
32388         this.setValue(this.el.dom.value);
32389     },
32390     
32391     onDestroy : function()
32392     {
32393         if(this.viewEl){
32394             Roo.get(this.viewEl).remove();
32395         }
32396          
32397         Roo.form.DayPicker.superclass.onDestroy.call(this);
32398     }
32399
32400 });/*
32401  * RooJS Library 1.1.1
32402  * Copyright(c) 2008-2011  Alan Knowles
32403  *
32404  * License - LGPL
32405  */
32406  
32407
32408 /**
32409  * @class Roo.form.ComboCheck
32410  * @extends Roo.form.ComboBox
32411  * A combobox for multiple select items.
32412  *
32413  * FIXME - could do with a reset button..
32414  * 
32415  * @constructor
32416  * Create a new ComboCheck
32417  * @param {Object} config Configuration options
32418  */
32419 Roo.form.ComboCheck = function(config){
32420     Roo.form.ComboCheck.superclass.constructor.call(this, config);
32421     // should verify some data...
32422     // like
32423     // hiddenName = required..
32424     // displayField = required
32425     // valudField == required
32426     var req= [ 'hiddenName', 'displayField', 'valueField' ];
32427     var _t = this;
32428     Roo.each(req, function(e) {
32429         if ((typeof(_t[e]) == 'undefined' ) || !_t[e].length) {
32430             throw "Roo.form.ComboCheck : missing value for: " + e;
32431         }
32432     });
32433     
32434     
32435 };
32436
32437 Roo.extend(Roo.form.ComboCheck, Roo.form.ComboBox, {
32438      
32439      
32440     editable : false,
32441      
32442     selectedClass: 'x-menu-item-checked', 
32443     
32444     // private
32445     onRender : function(ct, position){
32446         var _t = this;
32447         
32448         
32449         
32450         if(!this.tpl){
32451             var cls = 'x-combo-list';
32452
32453             
32454             this.tpl =  new Roo.Template({
32455                 html :  '<div class="'+cls+'-item x-menu-check-item">' +
32456                    '<img class="x-menu-item-icon" style="margin: 0px;" src="' + Roo.BLANK_IMAGE_URL + '">' + 
32457                    '<span>{' + this.displayField + '}</span>' +
32458                     '</div>' 
32459                 
32460             });
32461         }
32462  
32463         
32464         Roo.form.ComboCheck.superclass.onRender.call(this, ct, position);
32465         this.view.singleSelect = false;
32466         this.view.multiSelect = true;
32467         this.view.toggleSelect = true;
32468         this.pageTb.add(new Roo.Toolbar.Fill(),{
32469             
32470             text: 'Select All',
32471             handler: function() {
32472                 _t.selectAll();
32473             }
32474         },
32475         {
32476             text: 'Done',
32477             handler: function() {
32478                 _t.collapse();
32479             }
32480         });
32481     },
32482     
32483     cleanLeadingSpace : function(e)
32484     {
32485         // this is disabled, as it retriggers setvalue on blur
32486         return;
32487     },
32488     doForce : function() {
32489         // no idea what this did, but it blanks out our values.
32490         return;
32491     },
32492     onViewOver : function(e, t){
32493         // do nothing...
32494         return;
32495         
32496     },
32497     
32498     onViewClick : function(doFocus,index){
32499         return;
32500         
32501     },
32502     select: function () {
32503         //Roo.log("SELECT CALLED");
32504     },
32505      
32506     selectByValue : function(xv, scrollIntoView){
32507         var ar = this.getValueArray();
32508         var sels = [];
32509         
32510         Roo.each(ar, function(v) {
32511             if(v === undefined || v === null){
32512                 return;
32513             }
32514             var r = this.findRecord(this.valueField, v);
32515             if(r){
32516                 sels.push(this.store.indexOf(r))
32517                 
32518             }
32519         },this);
32520         this.view.select(sels);
32521         return false;
32522     },
32523     
32524     selectAll : function()
32525     {
32526         var sels = [];
32527         this.store.each(function(r,i) {
32528             sels.push(i);
32529         });
32530         this.view.select(sels);
32531         this.collapse();
32532         return false;
32533
32534     },
32535     
32536     onSelect : function(record, index){
32537        // Roo.log("onselect Called");
32538        // this is only called by the clear button now..
32539         this.view.clearSelections();
32540         this.setValue('[]');
32541         if (this.value != this.valueBefore) {
32542             this.fireEvent('change', this, this.value, this.valueBefore);
32543             this.valueBefore = this.value;
32544         }
32545     },
32546     getValueArray : function()
32547     {
32548         var ar = [] ;
32549         
32550         try {
32551             //Roo.log(this.value);
32552             if (typeof(this.value) == 'undefined') {
32553                 return [];
32554             }
32555             var ar = Roo.decode(this.value);
32556             return  ar instanceof Array ? ar : []; //?? valid?
32557             
32558         } catch(e) {
32559             Roo.log(e + "\nRoo.form.ComboCheck:getValueArray  invalid data:" + this.getValue());
32560             return [];
32561         }
32562          
32563     },
32564     expand : function ()
32565     {
32566         
32567         Roo.form.ComboCheck.superclass.expand.call(this);
32568         this.valueBefore = typeof(this.value) == 'undefined' ? '' : this.value;
32569         //this.valueBefore = typeof(this.valueBefore) == 'undefined' ? '' : this.valueBefore;
32570         
32571
32572     },
32573     
32574     collapse : function(){
32575         Roo.form.ComboCheck.superclass.collapse.call(this);
32576         var sl = this.view.getSelectedIndexes();
32577         var st = this.store;
32578         var nv = [];
32579         var tv = [];
32580         var r;
32581         Roo.each(sl, function(i) {
32582             r = st.getAt(i);
32583             nv.push(r.get(this.valueField));
32584         },this);
32585         this.setValue(Roo.encode(nv));
32586         if (this.value != this.valueBefore) {
32587
32588             this.fireEvent('change', this, this.value, this.valueBefore);
32589             this.valueBefore = this.value;
32590         }
32591         
32592     },
32593     
32594     setValue : function(v){
32595         // Roo.log(v);
32596         this.value = v;
32597         
32598         var vals = this.getValueArray();
32599         var tv = [];
32600         Roo.each(vals, function(k) {
32601             var r = this.findRecord(this.valueField, k);
32602             if(r){
32603                 tv.push(r.data[this.displayField]);
32604             }else if(this.valueNotFoundText !== undefined){
32605                 tv.push( this.valueNotFoundText );
32606             }
32607         },this);
32608        // Roo.log(tv);
32609         
32610         Roo.form.ComboBox.superclass.setValue.call(this, tv.join(', '));
32611         this.hiddenField.value = v;
32612         this.value = v;
32613     }
32614     
32615 });/*
32616  * Based on:
32617  * Ext JS Library 1.1.1
32618  * Copyright(c) 2006-2007, Ext JS, LLC.
32619  *
32620  * Originally Released Under LGPL - original licence link has changed is not relivant.
32621  *
32622  * Fork - LGPL
32623  * <script type="text/javascript">
32624  */
32625  
32626 /**
32627  * @class Roo.form.Signature
32628  * @extends Roo.form.Field
32629  * Signature field.  
32630  * @constructor
32631  * 
32632  * @param {Object} config Configuration options
32633  */
32634
32635 Roo.form.Signature = function(config){
32636     Roo.form.Signature.superclass.constructor.call(this, config);
32637     
32638     this.addEvents({// not in used??
32639          /**
32640          * @event confirm
32641          * Fires when the 'confirm' icon is pressed (add a listener to enable add button)
32642              * @param {Roo.form.Signature} combo This combo box
32643              */
32644         'confirm' : true,
32645         /**
32646          * @event reset
32647          * Fires when the 'edit' icon is pressed (add a listener to enable add button)
32648              * @param {Roo.form.ComboBox} combo This combo box
32649              * @param {Roo.data.Record|false} record The data record returned from the underlying store (or false on nothing selected)
32650              */
32651         'reset' : true
32652     });
32653 };
32654
32655 Roo.extend(Roo.form.Signature, Roo.form.Field,  {
32656     /**
32657      * @cfg {Object} labels Label to use when rendering a form.
32658      * defaults to 
32659      * labels : { 
32660      *      clear : "Clear",
32661      *      confirm : "Confirm"
32662      *  }
32663      */
32664     labels : { 
32665         clear : "Clear",
32666         confirm : "Confirm"
32667     },
32668     /**
32669      * @cfg {Number} width The signature panel width (defaults to 300)
32670      */
32671     width: 300,
32672     /**
32673      * @cfg {Number} height The signature panel height (defaults to 100)
32674      */
32675     height : 100,
32676     /**
32677      * @cfg {Boolean} allowBlank False to validate that the value length > 0 (defaults to false)
32678      */
32679     allowBlank : false,
32680     
32681     //private
32682     // {Object} signPanel The signature SVG panel element (defaults to {})
32683     signPanel : {},
32684     // {Boolean} isMouseDown False to validate that the mouse down event (defaults to false)
32685     isMouseDown : false,
32686     // {Boolean} isConfirmed validate the signature is confirmed or not for submitting form (defaults to false)
32687     isConfirmed : false,
32688     // {String} signatureTmp SVG mapping string (defaults to empty string)
32689     signatureTmp : '',
32690     
32691     
32692     defaultAutoCreate : { // modified by initCompnoent..
32693         tag: "input",
32694         type:"hidden"
32695     },
32696
32697     // private
32698     onRender : function(ct, position){
32699         
32700         Roo.form.Signature.superclass.onRender.call(this, ct, position);
32701         
32702         this.wrap = this.el.wrap({
32703             cls:'x-form-signature-wrap', style : 'width: ' + this.width + 'px', cn:{cls:'x-form-signature'}
32704         });
32705         
32706         this.createToolbar(this);
32707         this.signPanel = this.wrap.createChild({
32708                 tag: 'div',
32709                 style: 'width: ' + this.width + 'px; height: ' + this.height + 'px; border: 0;'
32710             }, this.el
32711         );
32712             
32713         this.svgID = Roo.id();
32714         this.svgEl = this.signPanel.createChild({
32715               xmlns : 'http://www.w3.org/2000/svg',
32716               tag : 'svg',
32717               id : this.svgID + "-svg",
32718               width: this.width,
32719               height: this.height,
32720               viewBox: '0 0 '+this.width+' '+this.height,
32721               cn : [
32722                 {
32723                     tag: "rect",
32724                     id: this.svgID + "-svg-r",
32725                     width: this.width,
32726                     height: this.height,
32727                     fill: "#ffa"
32728                 },
32729                 {
32730                     tag: "line",
32731                     id: this.svgID + "-svg-l",
32732                     x1: "0", // start
32733                     y1: (this.height*0.8), // start set the line in 80% of height
32734                     x2: this.width, // end
32735                     y2: (this.height*0.8), // end set the line in 80% of height
32736                     'stroke': "#666",
32737                     'stroke-width': "1",
32738                     'stroke-dasharray': "3",
32739                     'shape-rendering': "crispEdges",
32740                     'pointer-events': "none"
32741                 },
32742                 {
32743                     tag: "path",
32744                     id: this.svgID + "-svg-p",
32745                     'stroke': "navy",
32746                     'stroke-width': "3",
32747                     'fill': "none",
32748                     'pointer-events': 'none'
32749                 }
32750               ]
32751         });
32752         this.createSVG();
32753         this.svgBox = this.svgEl.dom.getScreenCTM();
32754     },
32755     createSVG : function(){ 
32756         var svg = this.signPanel;
32757         var r = svg.select('#'+ this.svgID + '-svg-r', true).first().dom;
32758         var t = this;
32759
32760         r.addEventListener('mousedown', function(e) { return t.down(e); }, false);
32761         r.addEventListener('mousemove', function(e) { return t.move(e); }, false);
32762         r.addEventListener('mouseup', function(e) { return t.up(e); }, false);
32763         r.addEventListener('mouseout', function(e) { return t.up(e); }, false);
32764         r.addEventListener('touchstart', function(e) { return t.down(e); }, false);
32765         r.addEventListener('touchmove', function(e) { return t.move(e); }, false);
32766         r.addEventListener('touchend', function(e) { return t.up(e); }, false);
32767         
32768     },
32769     isTouchEvent : function(e){
32770         return e.type.match(/^touch/);
32771     },
32772     getCoords : function (e) {
32773         var pt    = this.svgEl.dom.createSVGPoint();
32774         pt.x = e.clientX; 
32775         pt.y = e.clientY;
32776         if (this.isTouchEvent(e)) {
32777             pt.x =  e.targetTouches[0].clientX;
32778             pt.y = e.targetTouches[0].clientY;
32779         }
32780         var a = this.svgEl.dom.getScreenCTM();
32781         var b = a.inverse();
32782         var mx = pt.matrixTransform(b);
32783         return mx.x + ',' + mx.y;
32784     },
32785     //mouse event headler 
32786     down : function (e) {
32787         this.signatureTmp += 'M' + this.getCoords(e) + ' ';
32788         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr('d', this.signatureTmp);
32789         
32790         this.isMouseDown = true;
32791         
32792         e.preventDefault();
32793     },
32794     move : function (e) {
32795         if (this.isMouseDown) {
32796             this.signatureTmp += 'L' + this.getCoords(e) + ' ';
32797             this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', this.signatureTmp);
32798         }
32799         
32800         e.preventDefault();
32801     },
32802     up : function (e) {
32803         this.isMouseDown = false;
32804         var sp = this.signatureTmp.split(' ');
32805         
32806         if(sp.length > 1){
32807             if(!sp[sp.length-2].match(/^L/)){
32808                 sp.pop();
32809                 sp.pop();
32810                 sp.push("");
32811                 this.signatureTmp = sp.join(" ");
32812             }
32813         }
32814         if(this.getValue() != this.signatureTmp){
32815             this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
32816             this.isConfirmed = false;
32817         }
32818         e.preventDefault();
32819     },
32820     
32821     /**
32822      * Protected method that will not generally be called directly. It
32823      * is called when the editor creates its toolbar. Override this method if you need to
32824      * add custom toolbar buttons.
32825      * @param {HtmlEditor} editor
32826      */
32827     createToolbar : function(editor){
32828          function btn(id, toggle, handler){
32829             var xid = fid + '-'+ id ;
32830             return {
32831                 id : xid,
32832                 cmd : id,
32833                 cls : 'x-btn-icon x-edit-'+id,
32834                 enableToggle:toggle !== false,
32835                 scope: editor, // was editor...
32836                 handler:handler||editor.relayBtnCmd,
32837                 clickEvent:'mousedown',
32838                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
32839                 tabIndex:-1
32840             };
32841         }
32842         
32843         
32844         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
32845         this.tb = tb;
32846         this.tb.add(
32847            {
32848                 cls : ' x-signature-btn x-signature-'+id,
32849                 scope: editor, // was editor...
32850                 handler: this.reset,
32851                 clickEvent:'mousedown',
32852                 text: this.labels.clear
32853             },
32854             {
32855                  xtype : 'Fill',
32856                  xns: Roo.Toolbar
32857             }, 
32858             {
32859                 cls : '  x-signature-btn x-signature-'+id,
32860                 scope: editor, // was editor...
32861                 handler: this.confirmHandler,
32862                 clickEvent:'mousedown',
32863                 text: this.labels.confirm
32864             }
32865         );
32866     
32867     },
32868     //public
32869     /**
32870      * when user is clicked confirm then show this image.....
32871      * 
32872      * @return {String} Image Data URI
32873      */
32874     getImageDataURI : function(){
32875         var svg = this.svgEl.dom.parentNode.innerHTML;
32876         var src = 'data:image/svg+xml;base64,'+window.btoa(svg);
32877         return src; 
32878     },
32879     /**
32880      * 
32881      * @return {Boolean} this.isConfirmed
32882      */
32883     getConfirmed : function(){
32884         return this.isConfirmed;
32885     },
32886     /**
32887      * 
32888      * @return {Number} this.width
32889      */
32890     getWidth : function(){
32891         return this.width;
32892     },
32893     /**
32894      * 
32895      * @return {Number} this.height
32896      */
32897     getHeight : function(){
32898         return this.height;
32899     },
32900     // private
32901     getSignature : function(){
32902         return this.signatureTmp;
32903     },
32904     // private
32905     reset : function(){
32906         this.signatureTmp = '';
32907         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
32908         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', '');
32909         this.isConfirmed = false;
32910         Roo.form.Signature.superclass.reset.call(this);
32911     },
32912     setSignature : function(s){
32913         this.signatureTmp = s;
32914         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#ffa');
32915         this.signPanel.select('#'+ this.svgID + '-svg-p', true).first().attr( 'd', s);
32916         this.setValue(s);
32917         this.isConfirmed = false;
32918         Roo.form.Signature.superclass.reset.call(this);
32919     }, 
32920     test : function(){
32921 //        Roo.log(this.signPanel.dom.contentWindow.up())
32922     },
32923     //private
32924     setConfirmed : function(){
32925         
32926         
32927         
32928 //        Roo.log(Roo.get(this.signPanel.dom.contentWindow.r).attr('fill', '#cfc'));
32929     },
32930     // private
32931     confirmHandler : function(){
32932         if(!this.getSignature()){
32933             return;
32934         }
32935         
32936         this.signPanel.select('#'+ this.svgID + '-svg-r', true).first().attr('fill', '#cfc');
32937         this.setValue(this.getSignature());
32938         this.isConfirmed = true;
32939         
32940         this.fireEvent('confirm', this);
32941     },
32942     // private
32943     // Subclasses should provide the validation implementation by overriding this
32944     validateValue : function(value){
32945         if(this.allowBlank){
32946             return true;
32947         }
32948         
32949         if(this.isConfirmed){
32950             return true;
32951         }
32952         return false;
32953     }
32954 });/*
32955  * Based on:
32956  * Ext JS Library 1.1.1
32957  * Copyright(c) 2006-2007, Ext JS, LLC.
32958  *
32959  * Originally Released Under LGPL - original licence link has changed is not relivant.
32960  *
32961  * Fork - LGPL
32962  * <script type="text/javascript">
32963  */
32964  
32965
32966 /**
32967  * @class Roo.form.ComboBox
32968  * @extends Roo.form.TriggerField
32969  * A combobox control with support for autocomplete, remote-loading, paging and many other features.
32970  * @constructor
32971  * Create a new ComboBox.
32972  * @param {Object} config Configuration options
32973  */
32974 Roo.form.Select = function(config){
32975     Roo.form.Select.superclass.constructor.call(this, config);
32976      
32977 };
32978
32979 Roo.extend(Roo.form.Select , Roo.form.ComboBox, {
32980     /**
32981      * @cfg {String/HTMLElement/Element} transform The id, DOM node or element of an existing select to convert to a ComboBox
32982      */
32983     /**
32984      * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when
32985      * rendering into an Roo.Editor, defaults to false)
32986      */
32987     /**
32988      * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to:
32989      * {tag: "input", type: "text", size: "24", autocomplete: "off"})
32990      */
32991     /**
32992      * @cfg {Roo.data.Store} store The data store to which this combo is bound (defaults to undefined)
32993      */
32994     /**
32995      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
32996      * the dropdown list (defaults to undefined, with no header element)
32997      */
32998
32999      /**
33000      * @cfg {String/Roo.Template} tpl The template to use to render the output
33001      */
33002      
33003     // private
33004     defaultAutoCreate : {tag: "select"  },
33005     /**
33006      * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
33007      */
33008     listWidth: undefined,
33009     /**
33010      * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if
33011      * mode = 'remote' or 'text' if mode = 'local')
33012      */
33013     displayField: undefined,
33014     /**
33015      * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if
33016      * mode = 'remote' or 'value' if mode = 'local'). 
33017      * Note: use of a valueField requires the user make a selection
33018      * in order for a value to be mapped.
33019      */
33020     valueField: undefined,
33021     
33022     
33023     /**
33024      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
33025      * field's data value (defaults to the underlying DOM element's name)
33026      */
33027     hiddenName: undefined,
33028     /**
33029      * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '')
33030      */
33031     listClass: '',
33032     /**
33033      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
33034      */
33035     selectedClass: 'x-combo-selected',
33036     /**
33037      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always get the
33038      * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
33039      * which displays a downward arrow icon).
33040      */
33041     triggerClass : 'x-form-arrow-trigger',
33042     /**
33043      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
33044      */
33045     shadow:'sides',
33046     /**
33047      * @cfg {String} listAlign A valid anchor position value. See {@link Roo.Element#alignTo} for details on supported
33048      * anchor positions (defaults to 'tl-bl')
33049      */
33050     listAlign: 'tl-bl?',
33051     /**
33052      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
33053      */
33054     maxHeight: 300,
33055     /**
33056      * @cfg {String} triggerAction The action to execute when the trigger field is activated.  Use 'all' to run the
33057      * query specified by the allQuery config option (defaults to 'query')
33058      */
33059     triggerAction: 'query',
33060     /**
33061      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate
33062      * (defaults to 4, does not apply if editable = false)
33063      */
33064     minChars : 4,
33065     /**
33066      * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable
33067      * delay (typeAheadDelay) if it matches a known value (defaults to false)
33068      */
33069     typeAhead: false,
33070     /**
33071      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the
33072      * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
33073      */
33074     queryDelay: 500,
33075     /**
33076      * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
33077      * filter queries will execute with page start and limit parameters.  Only applies when mode = 'remote' (defaults to 0)
33078      */
33079     pageSize: 0,
33080     /**
33081      * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus.  Only applies
33082      * when editable = true (defaults to false)
33083      */
33084     selectOnFocus:false,
33085     /**
33086      * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query')
33087      */
33088     queryParam: 'query',
33089     /**
33090      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
33091      * when mode = 'remote' (defaults to 'Loading...')
33092      */
33093     loadingText: 'Loading...',
33094     /**
33095      * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false)
33096      */
33097     resizable: false,
33098     /**
33099      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
33100      */
33101     handleHeight : 8,
33102     /**
33103      * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a
33104      * traditional select (defaults to true)
33105      */
33106     editable: true,
33107     /**
33108      * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '')
33109      */
33110     allQuery: '',
33111     /**
33112      * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
33113      */
33114     mode: 'remote',
33115     /**
33116      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
33117      * listWidth has a higher value)
33118      */
33119     minListWidth : 70,
33120     /**
33121      * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to
33122      * allow the user to set arbitrary text into the field (defaults to false)
33123      */
33124     forceSelection:false,
33125     /**
33126      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
33127      * if typeAhead = true (defaults to 250)
33128      */
33129     typeAheadDelay : 250,
33130     /**
33131      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
33132      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined)
33133      */
33134     valueNotFoundText : undefined,
33135     
33136     /**
33137      * @cfg {String} defaultValue The value displayed after loading the store.
33138      */
33139     defaultValue: '',
33140     
33141     /**
33142      * @cfg {Boolean} blockFocus Prevents all focus calls, so it can work with things like HTML edtor bar
33143      */
33144     blockFocus : false,
33145     
33146     /**
33147      * @cfg {Boolean} disableClear Disable showing of clear button.
33148      */
33149     disableClear : false,
33150     /**
33151      * @cfg {Boolean} alwaysQuery  Disable caching of results, and always send query
33152      */
33153     alwaysQuery : false,
33154     
33155     //private
33156     addicon : false,
33157     editicon: false,
33158     
33159     // element that contains real text value.. (when hidden is used..)
33160      
33161     // private
33162     onRender : function(ct, position){
33163         Roo.form.Field.prototype.onRender.call(this, ct, position);
33164         
33165         if(this.store){
33166             this.store.on('beforeload', this.onBeforeLoad, this);
33167             this.store.on('load', this.onLoad, this);
33168             this.store.on('loadexception', this.onLoadException, this);
33169             this.store.load({});
33170         }
33171         
33172         
33173         
33174     },
33175
33176     // private
33177     initEvents : function(){
33178         //Roo.form.ComboBox.superclass.initEvents.call(this);
33179  
33180     },
33181
33182     onDestroy : function(){
33183        
33184         if(this.store){
33185             this.store.un('beforeload', this.onBeforeLoad, this);
33186             this.store.un('load', this.onLoad, this);
33187             this.store.un('loadexception', this.onLoadException, this);
33188         }
33189         //Roo.form.ComboBox.superclass.onDestroy.call(this);
33190     },
33191
33192     // private
33193     fireKey : function(e){
33194         if(e.isNavKeyPress() && !this.list.isVisible()){
33195             this.fireEvent("specialkey", this, e);
33196         }
33197     },
33198
33199     // private
33200     onResize: function(w, h){
33201         
33202         return; 
33203     
33204         
33205     },
33206
33207     /**
33208      * Allow or prevent the user from directly editing the field text.  If false is passed,
33209      * the user will only be able to select from the items defined in the dropdown list.  This method
33210      * is the runtime equivalent of setting the 'editable' config option at config time.
33211      * @param {Boolean} value True to allow the user to directly edit the field text
33212      */
33213     setEditable : function(value){
33214          
33215     },
33216
33217     // private
33218     onBeforeLoad : function(){
33219         
33220         Roo.log("Select before load");
33221         return;
33222     
33223         this.innerList.update(this.loadingText ?
33224                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
33225         //this.restrictHeight();
33226         this.selectedIndex = -1;
33227     },
33228
33229     // private
33230     onLoad : function(){
33231
33232     
33233         var dom = this.el.dom;
33234         dom.innerHTML = '';
33235          var od = dom.ownerDocument;
33236          
33237         if (this.emptyText) {
33238             var op = od.createElement('option');
33239             op.setAttribute('value', '');
33240             op.innerHTML = String.format('{0}', this.emptyText);
33241             dom.appendChild(op);
33242         }
33243         if(this.store.getCount() > 0){
33244            
33245             var vf = this.valueField;
33246             var df = this.displayField;
33247             this.store.data.each(function(r) {
33248                 // which colmsn to use... testing - cdoe / title..
33249                 var op = od.createElement('option');
33250                 op.setAttribute('value', r.data[vf]);
33251                 op.innerHTML = String.format('{0}', r.data[df]);
33252                 dom.appendChild(op);
33253             });
33254             if (typeof(this.defaultValue != 'undefined')) {
33255                 this.setValue(this.defaultValue);
33256             }
33257             
33258              
33259         }else{
33260             //this.onEmptyResults();
33261         }
33262         //this.el.focus();
33263     },
33264     // private
33265     onLoadException : function()
33266     {
33267         dom.innerHTML = '';
33268             
33269         Roo.log("Select on load exception");
33270         return;
33271     
33272         this.collapse();
33273         Roo.log(this.store.reader.jsonData);
33274         if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
33275             Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
33276         }
33277         
33278         
33279     },
33280     // private
33281     onTypeAhead : function(){
33282          
33283     },
33284
33285     // private
33286     onSelect : function(record, index){
33287         Roo.log('on select?');
33288         return;
33289         if(this.fireEvent('beforeselect', this, record, index) !== false){
33290             this.setFromData(index > -1 ? record.data : false);
33291             this.collapse();
33292             this.fireEvent('select', this, record, index);
33293         }
33294     },
33295
33296     /**
33297      * Returns the currently selected field value or empty string if no value is set.
33298      * @return {String} value The selected value
33299      */
33300     getValue : function(){
33301         var dom = this.el.dom;
33302         this.value = dom.options[dom.selectedIndex].value;
33303         return this.value;
33304         
33305     },
33306
33307     /**
33308      * Clears any text/value currently set in the field
33309      */
33310     clearValue : function(){
33311         this.value = '';
33312         this.el.dom.selectedIndex = this.emptyText ? 0 : -1;
33313         
33314     },
33315
33316     /**
33317      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
33318      * will be displayed in the field.  If the value does not match the data value of an existing item,
33319      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
33320      * Otherwise the field will be blank (although the value will still be set).
33321      * @param {String} value The value to match
33322      */
33323     setValue : function(v){
33324         var d = this.el.dom;
33325         for (var i =0; i < d.options.length;i++) {
33326             if (v == d.options[i].value) {
33327                 d.selectedIndex = i;
33328                 this.value = v;
33329                 return;
33330             }
33331         }
33332         this.clearValue();
33333     },
33334     /**
33335      * @property {Object} the last set data for the element
33336      */
33337     
33338     lastData : false,
33339     /**
33340      * Sets the value of the field based on a object which is related to the record format for the store.
33341      * @param {Object} value the value to set as. or false on reset?
33342      */
33343     setFromData : function(o){
33344         Roo.log('setfrom data?');
33345          
33346         
33347         
33348     },
33349     // private
33350     reset : function(){
33351         this.clearValue();
33352     },
33353     // private
33354     findRecord : function(prop, value){
33355         
33356         return false;
33357     
33358         var record;
33359         if(this.store.getCount() > 0){
33360             this.store.each(function(r){
33361                 if(r.data[prop] == value){
33362                     record = r;
33363                     return false;
33364                 }
33365                 return true;
33366             });
33367         }
33368         return record;
33369     },
33370     
33371     getName: function()
33372     {
33373         // returns hidden if it's set..
33374         if (!this.rendered) {return ''};
33375         return !this.hiddenName && this.el.dom.name  ? this.el.dom.name : (this.hiddenName || '');
33376         
33377     },
33378      
33379
33380     
33381
33382     // private
33383     onEmptyResults : function(){
33384         Roo.log('empty results');
33385         //this.collapse();
33386     },
33387
33388     /**
33389      * Returns true if the dropdown list is expanded, else false.
33390      */
33391     isExpanded : function(){
33392         return false;
33393     },
33394
33395     /**
33396      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
33397      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
33398      * @param {String} value The data value of the item to select
33399      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
33400      * selected item if it is not currently in view (defaults to true)
33401      * @return {Boolean} True if the value matched an item in the list, else false
33402      */
33403     selectByValue : function(v, scrollIntoView){
33404         Roo.log('select By Value');
33405         return false;
33406     
33407         if(v !== undefined && v !== null){
33408             var r = this.findRecord(this.valueField || this.displayField, v);
33409             if(r){
33410                 this.select(this.store.indexOf(r), scrollIntoView);
33411                 return true;
33412             }
33413         }
33414         return false;
33415     },
33416
33417     /**
33418      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
33419      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
33420      * @param {Number} index The zero-based index of the list item to select
33421      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
33422      * selected item if it is not currently in view (defaults to true)
33423      */
33424     select : function(index, scrollIntoView){
33425         Roo.log('select ');
33426         return  ;
33427         
33428         this.selectedIndex = index;
33429         this.view.select(index);
33430         if(scrollIntoView !== false){
33431             var el = this.view.getNode(index);
33432             if(el){
33433                 this.innerList.scrollChildIntoView(el, false);
33434             }
33435         }
33436     },
33437
33438       
33439
33440     // private
33441     validateBlur : function(){
33442         
33443         return;
33444         
33445     },
33446
33447     // private
33448     initQuery : function(){
33449         this.doQuery(this.getRawValue());
33450     },
33451
33452     // private
33453     doForce : function(){
33454         if(this.el.dom.value.length > 0){
33455             this.el.dom.value =
33456                 this.lastSelectionText === undefined ? '' : this.lastSelectionText;
33457              
33458         }
33459     },
33460
33461     /**
33462      * Execute a query to filter the dropdown list.  Fires the beforequery event prior to performing the
33463      * query allowing the query action to be canceled if needed.
33464      * @param {String} query The SQL query to execute
33465      * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters
33466      * in the field than the minimum specified by the minChars config option.  It also clears any filter previously
33467      * saved in the current store (defaults to false)
33468      */
33469     doQuery : function(q, forceAll){
33470         
33471         Roo.log('doQuery?');
33472         if(q === undefined || q === null){
33473             q = '';
33474         }
33475         var qe = {
33476             query: q,
33477             forceAll: forceAll,
33478             combo: this,
33479             cancel:false
33480         };
33481         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
33482             return false;
33483         }
33484         q = qe.query;
33485         forceAll = qe.forceAll;
33486         if(forceAll === true || (q.length >= this.minChars)){
33487             if(this.lastQuery != q || this.alwaysQuery){
33488                 this.lastQuery = q;
33489                 if(this.mode == 'local'){
33490                     this.selectedIndex = -1;
33491                     if(forceAll){
33492                         this.store.clearFilter();
33493                     }else{
33494                         this.store.filter(this.displayField, q);
33495                     }
33496                     this.onLoad();
33497                 }else{
33498                     this.store.baseParams[this.queryParam] = q;
33499                     this.store.load({
33500                         params: this.getParams(q)
33501                     });
33502                     this.expand();
33503                 }
33504             }else{
33505                 this.selectedIndex = -1;
33506                 this.onLoad();   
33507             }
33508         }
33509     },
33510
33511     // private
33512     getParams : function(q){
33513         var p = {};
33514         //p[this.queryParam] = q;
33515         if(this.pageSize){
33516             p.start = 0;
33517             p.limit = this.pageSize;
33518         }
33519         return p;
33520     },
33521
33522     /**
33523      * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion.
33524      */
33525     collapse : function(){
33526         
33527     },
33528
33529     // private
33530     collapseIf : function(e){
33531         
33532     },
33533
33534     /**
33535      * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion.
33536      */
33537     expand : function(){
33538         
33539     } ,
33540
33541     // private
33542      
33543
33544     /** 
33545     * @cfg {Boolean} grow 
33546     * @hide 
33547     */
33548     /** 
33549     * @cfg {Number} growMin 
33550     * @hide 
33551     */
33552     /** 
33553     * @cfg {Number} growMax 
33554     * @hide 
33555     */
33556     /**
33557      * @hide
33558      * @method autoSize
33559      */
33560     
33561     setWidth : function()
33562     {
33563         
33564     },
33565     getResizeEl : function(){
33566         return this.el;
33567     }
33568 });//<script type="text/javasscript">
33569  
33570
33571 /**
33572  * @class Roo.DDView
33573  * A DnD enabled version of Roo.View.
33574  * @param {Element/String} container The Element in which to create the View.
33575  * @param {String} tpl The template string used to create the markup for each element of the View
33576  * @param {Object} config The configuration properties. These include all the config options of
33577  * {@link Roo.View} plus some specific to this class.<br>
33578  * <p>
33579  * Drag/drop is implemented by adding {@link Roo.data.Record}s to the target DDView. If copying is
33580  * not being performed, the original {@link Roo.data.Record} is removed from the source DDView.<br>
33581  * <p>
33582  * The following extra CSS rules are needed to provide insertion point highlighting:<pre><code>
33583 .x-view-drag-insert-above {
33584         border-top:1px dotted #3366cc;
33585 }
33586 .x-view-drag-insert-below {
33587         border-bottom:1px dotted #3366cc;
33588 }
33589 </code></pre>
33590  * 
33591  */
33592  
33593 Roo.DDView = function(container, tpl, config) {
33594     Roo.DDView.superclass.constructor.apply(this, arguments);
33595     this.getEl().setStyle("outline", "0px none");
33596     this.getEl().unselectable();
33597     if (this.dragGroup) {
33598         this.setDraggable(this.dragGroup.split(","));
33599     }
33600     if (this.dropGroup) {
33601         this.setDroppable(this.dropGroup.split(","));
33602     }
33603     if (this.deletable) {
33604         this.setDeletable();
33605     }
33606     this.isDirtyFlag = false;
33607         this.addEvents({
33608                 "drop" : true
33609         });
33610 };
33611
33612 Roo.extend(Roo.DDView, Roo.View, {
33613 /**     @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone. */
33614 /**     @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone. */
33615 /**     @cfg {Boolean} copy Causes drag operations to copy nodes rather than move. */
33616 /**     @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move. */
33617
33618         isFormField: true,
33619
33620         reset: Roo.emptyFn,
33621         
33622         clearInvalid: Roo.form.Field.prototype.clearInvalid,
33623
33624         validate: function() {
33625                 return true;
33626         },
33627         
33628         destroy: function() {
33629                 this.purgeListeners();
33630                 this.getEl.removeAllListeners();
33631                 this.getEl().remove();
33632                 if (this.dragZone) {
33633                         if (this.dragZone.destroy) {
33634                                 this.dragZone.destroy();
33635                         }
33636                 }
33637                 if (this.dropZone) {
33638                         if (this.dropZone.destroy) {
33639                                 this.dropZone.destroy();
33640                         }
33641                 }
33642         },
33643
33644 /**     Allows this class to be an Roo.form.Field so it can be found using {@link Roo.form.BasicForm#findField}. */
33645         getName: function() {
33646                 return this.name;
33647         },
33648
33649 /**     Loads the View from a JSON string representing the Records to put into the Store. */
33650         setValue: function(v) {
33651                 if (!this.store) {
33652                         throw "DDView.setValue(). DDView must be constructed with a valid Store";
33653                 }
33654                 var data = {};
33655                 data[this.store.reader.meta.root] = v ? [].concat(v) : [];
33656                 this.store.proxy = new Roo.data.MemoryProxy(data);
33657                 this.store.load();
33658         },
33659
33660 /**     @return {String} a parenthesised list of the ids of the Records in the View. */
33661         getValue: function() {
33662                 var result = '(';
33663                 this.store.each(function(rec) {
33664                         result += rec.id + ',';
33665                 });
33666                 return result.substr(0, result.length - 1) + ')';
33667         },
33668         
33669         getIds: function() {
33670                 var i = 0, result = new Array(this.store.getCount());
33671                 this.store.each(function(rec) {
33672                         result[i++] = rec.id;
33673                 });
33674                 return result;
33675         },
33676         
33677         isDirty: function() {
33678                 return this.isDirtyFlag;
33679         },
33680
33681 /**
33682  *      Part of the Roo.dd.DropZone interface. If no target node is found, the
33683  *      whole Element becomes the target, and this causes the drop gesture to append.
33684  */
33685     getTargetFromEvent : function(e) {
33686                 var target = e.getTarget();
33687                 while ((target !== null) && (target.parentNode != this.el.dom)) {
33688                 target = target.parentNode;
33689                 }
33690                 if (!target) {
33691                         target = this.el.dom.lastChild || this.el.dom;
33692                 }
33693                 return target;
33694     },
33695
33696 /**
33697  *      Create the drag data which consists of an object which has the property "ddel" as
33698  *      the drag proxy element. 
33699  */
33700     getDragData : function(e) {
33701         var target = this.findItemFromChild(e.getTarget());
33702                 if(target) {
33703                         this.handleSelection(e);
33704                         var selNodes = this.getSelectedNodes();
33705             var dragData = {
33706                 source: this,
33707                 copy: this.copy || (this.allowCopy && e.ctrlKey),
33708                 nodes: selNodes,
33709                 records: []
33710                         };
33711                         var selectedIndices = this.getSelectedIndexes();
33712                         for (var i = 0; i < selectedIndices.length; i++) {
33713                                 dragData.records.push(this.store.getAt(selectedIndices[i]));
33714                         }
33715                         if (selNodes.length == 1) {
33716                                 dragData.ddel = target.cloneNode(true); // the div element
33717                         } else {
33718                                 var div = document.createElement('div'); // create the multi element drag "ghost"
33719                                 div.className = 'multi-proxy';
33720                                 for (var i = 0, len = selNodes.length; i < len; i++) {
33721                                         div.appendChild(selNodes[i].cloneNode(true));
33722                                 }
33723                                 dragData.ddel = div;
33724                         }
33725             //console.log(dragData)
33726             //console.log(dragData.ddel.innerHTML)
33727                         return dragData;
33728                 }
33729         //console.log('nodragData')
33730                 return false;
33731     },
33732     
33733 /**     Specify to which ddGroup items in this DDView may be dragged. */
33734     setDraggable: function(ddGroup) {
33735         if (ddGroup instanceof Array) {
33736                 Roo.each(ddGroup, this.setDraggable, this);
33737                 return;
33738         }
33739         if (this.dragZone) {
33740                 this.dragZone.addToGroup(ddGroup);
33741         } else {
33742                         this.dragZone = new Roo.dd.DragZone(this.getEl(), {
33743                                 containerScroll: true,
33744                                 ddGroup: ddGroup 
33745
33746                         });
33747 //                      Draggability implies selection. DragZone's mousedown selects the element.
33748                         if (!this.multiSelect) { this.singleSelect = true; }
33749
33750 //                      Wire the DragZone's handlers up to methods in *this*
33751                         this.dragZone.getDragData = this.getDragData.createDelegate(this);
33752                 }
33753     },
33754
33755 /**     Specify from which ddGroup this DDView accepts drops. */
33756     setDroppable: function(ddGroup) {
33757         if (ddGroup instanceof Array) {
33758                 Roo.each(ddGroup, this.setDroppable, this);
33759                 return;
33760         }
33761         if (this.dropZone) {
33762                 this.dropZone.addToGroup(ddGroup);
33763         } else {
33764                         this.dropZone = new Roo.dd.DropZone(this.getEl(), {
33765                                 containerScroll: true,
33766                                 ddGroup: ddGroup
33767                         });
33768
33769 //                      Wire the DropZone's handlers up to methods in *this*
33770                         this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
33771                         this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
33772                         this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
33773                         this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
33774                         this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
33775                 }
33776     },
33777
33778 /**     Decide whether to drop above or below a View node. */
33779     getDropPoint : function(e, n, dd){
33780         if (n == this.el.dom) { return "above"; }
33781                 var t = Roo.lib.Dom.getY(n), b = t + n.offsetHeight;
33782                 var c = t + (b - t) / 2;
33783                 var y = Roo.lib.Event.getPageY(e);
33784                 if(y <= c) {
33785                         return "above";
33786                 }else{
33787                         return "below";
33788                 }
33789     },
33790
33791     onNodeEnter : function(n, dd, e, data){
33792                 return false;
33793     },
33794     
33795     onNodeOver : function(n, dd, e, data){
33796                 var pt = this.getDropPoint(e, n, dd);
33797                 // set the insert point style on the target node
33798                 var dragElClass = this.dropNotAllowed;
33799                 if (pt) {
33800                         var targetElClass;
33801                         if (pt == "above"){
33802                                 dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
33803                                 targetElClass = "x-view-drag-insert-above";
33804                         } else {
33805                                 dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
33806                                 targetElClass = "x-view-drag-insert-below";
33807                         }
33808                         if (this.lastInsertClass != targetElClass){
33809                                 Roo.fly(n).replaceClass(this.lastInsertClass, targetElClass);
33810                                 this.lastInsertClass = targetElClass;
33811                         }
33812                 }
33813                 return dragElClass;
33814         },
33815
33816     onNodeOut : function(n, dd, e, data){
33817                 this.removeDropIndicators(n);
33818     },
33819
33820     onNodeDrop : function(n, dd, e, data){
33821         if (this.fireEvent("drop", this, n, dd, e, data) === false) {
33822                 return false;
33823         }
33824         var pt = this.getDropPoint(e, n, dd);
33825                 var insertAt = (n == this.el.dom) ? this.nodes.length : n.nodeIndex;
33826                 if (pt == "below") { insertAt++; }
33827                 for (var i = 0; i < data.records.length; i++) {
33828                         var r = data.records[i];
33829                         var dup = this.store.getById(r.id);
33830                         if (dup && (dd != this.dragZone)) {
33831                                 Roo.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
33832                         } else {
33833                                 if (data.copy) {
33834                                         this.store.insert(insertAt++, r.copy());
33835                                 } else {
33836                                         data.source.isDirtyFlag = true;
33837                                         r.store.remove(r);
33838                                         this.store.insert(insertAt++, r);
33839                                 }
33840                                 this.isDirtyFlag = true;
33841                         }
33842                 }
33843                 this.dragZone.cachedTarget = null;
33844                 return true;
33845     },
33846
33847     removeDropIndicators : function(n){
33848                 if(n){
33849                         Roo.fly(n).removeClass([
33850                                 "x-view-drag-insert-above",
33851                                 "x-view-drag-insert-below"]);
33852                         this.lastInsertClass = "_noclass";
33853                 }
33854     },
33855
33856 /**
33857  *      Utility method. Add a delete option to the DDView's context menu.
33858  *      @param {String} imageUrl The URL of the "delete" icon image.
33859  */
33860         setDeletable: function(imageUrl) {
33861                 if (!this.singleSelect && !this.multiSelect) {
33862                         this.singleSelect = true;
33863                 }
33864                 var c = this.getContextMenu();
33865                 this.contextMenu.on("itemclick", function(item) {
33866                         switch (item.id) {
33867                                 case "delete":
33868                                         this.remove(this.getSelectedIndexes());
33869                                         break;
33870                         }
33871                 }, this);
33872                 this.contextMenu.add({
33873                         icon: imageUrl,
33874                         id: "delete",
33875                         text: 'Delete'
33876                 });
33877         },
33878         
33879 /**     Return the context menu for this DDView. */
33880         getContextMenu: function() {
33881                 if (!this.contextMenu) {
33882 //                      Create the View's context menu
33883                         this.contextMenu = new Roo.menu.Menu({
33884                                 id: this.id + "-contextmenu"
33885                         });
33886                         this.el.on("contextmenu", this.showContextMenu, this);
33887                 }
33888                 return this.contextMenu;
33889         },
33890         
33891         disableContextMenu: function() {
33892                 if (this.contextMenu) {
33893                         this.el.un("contextmenu", this.showContextMenu, this);
33894                 }
33895         },
33896
33897         showContextMenu: function(e, item) {
33898         item = this.findItemFromChild(e.getTarget());
33899                 if (item) {
33900                         e.stopEvent();
33901                         this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
33902                         this.contextMenu.showAt(e.getXY());
33903             }
33904     },
33905
33906 /**
33907  *      Remove {@link Roo.data.Record}s at the specified indices.
33908  *      @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
33909  */
33910     remove: function(selectedIndices) {
33911                 selectedIndices = [].concat(selectedIndices);
33912                 for (var i = 0; i < selectedIndices.length; i++) {
33913                         var rec = this.store.getAt(selectedIndices[i]);
33914                         this.store.remove(rec);
33915                 }
33916     },
33917
33918 /**
33919  *      Double click fires the event, but also, if this is draggable, and there is only one other
33920  *      related DropZone, it transfers the selected node.
33921  */
33922     onDblClick : function(e){
33923         var item = this.findItemFromChild(e.getTarget());
33924         if(item){
33925             if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
33926                 return false;
33927             }
33928             if (this.dragGroup) {
33929                     var targets = Roo.dd.DragDropMgr.getRelated(this.dragZone, true);
33930                     while (targets.indexOf(this.dropZone) > -1) {
33931                             targets.remove(this.dropZone);
33932                                 }
33933                     if (targets.length == 1) {
33934                                         this.dragZone.cachedTarget = null;
33935                         var el = Roo.get(targets[0].getEl());
33936                         var box = el.getBox(true);
33937                         targets[0].onNodeDrop(el.dom, {
33938                                 target: el.dom,
33939                                 xy: [box.x, box.y + box.height - 1]
33940                         }, null, this.getDragData(e));
33941                     }
33942                 }
33943         }
33944     },
33945     
33946     handleSelection: function(e) {
33947                 this.dragZone.cachedTarget = null;
33948         var item = this.findItemFromChild(e.getTarget());
33949         if (!item) {
33950                 this.clearSelections(true);
33951                 return;
33952         }
33953                 if (item && (this.multiSelect || this.singleSelect)){
33954                         if(this.multiSelect && e.shiftKey && (!e.ctrlKey) && this.lastSelection){
33955                                 this.select(this.getNodes(this.indexOf(this.lastSelection), item.nodeIndex), false);
33956                         }else if (this.isSelected(this.getNode(item)) && e.ctrlKey){
33957                                 this.unselect(item);
33958                         } else {
33959                                 this.select(item, this.multiSelect && e.ctrlKey);
33960                                 this.lastSelection = item;
33961                         }
33962                 }
33963     },
33964
33965     onItemClick : function(item, index, e){
33966                 if(this.fireEvent("beforeclick", this, index, item, e) === false){
33967                         return false;
33968                 }
33969                 return true;
33970     },
33971
33972     unselect : function(nodeInfo, suppressEvent){
33973                 var node = this.getNode(nodeInfo);
33974                 if(node && this.isSelected(node)){
33975                         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
33976                                 Roo.fly(node).removeClass(this.selectedClass);
33977                                 this.selections.remove(node);
33978                                 if(!suppressEvent){
33979                                         this.fireEvent("selectionchange", this, this.selections);
33980                                 }
33981                         }
33982                 }
33983     }
33984 });
33985 /*
33986  * Based on:
33987  * Ext JS Library 1.1.1
33988  * Copyright(c) 2006-2007, Ext JS, LLC.
33989  *
33990  * Originally Released Under LGPL - original licence link has changed is not relivant.
33991  *
33992  * Fork - LGPL
33993  * <script type="text/javascript">
33994  */
33995  
33996 /**
33997  * @class Roo.LayoutManager
33998  * @extends Roo.util.Observable
33999  * Base class for layout managers.
34000  */
34001 Roo.LayoutManager = function(container, config){
34002     Roo.LayoutManager.superclass.constructor.call(this);
34003     this.el = Roo.get(container);
34004     // ie scrollbar fix
34005     if(this.el.dom == document.body && Roo.isIE && !config.allowScroll){
34006         document.body.scroll = "no";
34007     }else if(this.el.dom != document.body && this.el.getStyle('position') == 'static'){
34008         this.el.position('relative');
34009     }
34010     this.id = this.el.id;
34011     this.el.addClass("x-layout-container");
34012     /** false to disable window resize monitoring @type Boolean */
34013     this.monitorWindowResize = true;
34014     this.regions = {};
34015     this.addEvents({
34016         /**
34017          * @event layout
34018          * Fires when a layout is performed. 
34019          * @param {Roo.LayoutManager} this
34020          */
34021         "layout" : true,
34022         /**
34023          * @event regionresized
34024          * Fires when the user resizes a region. 
34025          * @param {Roo.LayoutRegion} region The resized region
34026          * @param {Number} newSize The new size (width for east/west, height for north/south)
34027          */
34028         "regionresized" : true,
34029         /**
34030          * @event regioncollapsed
34031          * Fires when a region is collapsed. 
34032          * @param {Roo.LayoutRegion} region The collapsed region
34033          */
34034         "regioncollapsed" : true,
34035         /**
34036          * @event regionexpanded
34037          * Fires when a region is expanded.  
34038          * @param {Roo.LayoutRegion} region The expanded region
34039          */
34040         "regionexpanded" : true
34041     });
34042     this.updating = false;
34043     Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
34044 };
34045
34046 Roo.extend(Roo.LayoutManager, Roo.util.Observable, {
34047     /**
34048      * Returns true if this layout is currently being updated
34049      * @return {Boolean}
34050      */
34051     isUpdating : function(){
34052         return this.updating; 
34053     },
34054     
34055     /**
34056      * Suspend the LayoutManager from doing auto-layouts while
34057      * making multiple add or remove calls
34058      */
34059     beginUpdate : function(){
34060         this.updating = true;    
34061     },
34062     
34063     /**
34064      * Restore auto-layouts and optionally disable the manager from performing a layout
34065      * @param {Boolean} noLayout true to disable a layout update 
34066      */
34067     endUpdate : function(noLayout){
34068         this.updating = false;
34069         if(!noLayout){
34070             this.layout();
34071         }    
34072     },
34073     
34074     layout: function(){
34075         
34076     },
34077     
34078     onRegionResized : function(region, newSize){
34079         this.fireEvent("regionresized", region, newSize);
34080         this.layout();
34081     },
34082     
34083     onRegionCollapsed : function(region){
34084         this.fireEvent("regioncollapsed", region);
34085     },
34086     
34087     onRegionExpanded : function(region){
34088         this.fireEvent("regionexpanded", region);
34089     },
34090         
34091     /**
34092      * Returns the size of the current view. This method normalizes document.body and element embedded layouts and
34093      * performs box-model adjustments.
34094      * @return {Object} The size as an object {width: (the width), height: (the height)}
34095      */
34096     getViewSize : function(){
34097         var size;
34098         if(this.el.dom != document.body){
34099             size = this.el.getSize();
34100         }else{
34101             size = {width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
34102         }
34103         size.width -= this.el.getBorderWidth("lr")-this.el.getPadding("lr");
34104         size.height -= this.el.getBorderWidth("tb")-this.el.getPadding("tb");
34105         return size;
34106     },
34107     
34108     /**
34109      * Returns the Element this layout is bound to.
34110      * @return {Roo.Element}
34111      */
34112     getEl : function(){
34113         return this.el;
34114     },
34115     
34116     /**
34117      * Returns the specified region.
34118      * @param {String} target The region key ('center', 'north', 'south', 'east' or 'west')
34119      * @return {Roo.LayoutRegion}
34120      */
34121     getRegion : function(target){
34122         return this.regions[target.toLowerCase()];
34123     },
34124     
34125     onWindowResize : function(){
34126         if(this.monitorWindowResize){
34127             this.layout();
34128         }
34129     }
34130 });/*
34131  * Based on:
34132  * Ext JS Library 1.1.1
34133  * Copyright(c) 2006-2007, Ext JS, LLC.
34134  *
34135  * Originally Released Under LGPL - original licence link has changed is not relivant.
34136  *
34137  * Fork - LGPL
34138  * <script type="text/javascript">
34139  */
34140 /**
34141  * @class Roo.BorderLayout
34142  * @extends Roo.LayoutManager
34143  * @children Roo.ContentPanel
34144  * This class represents a common layout manager used in desktop applications. For screenshots and more details,
34145  * please see: <br><br>
34146  * <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>
34147  * <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>
34148  * Example:
34149  <pre><code>
34150  var layout = new Roo.BorderLayout(document.body, {
34151     north: {
34152         initialSize: 25,
34153         titlebar: false
34154     },
34155     west: {
34156         split:true,
34157         initialSize: 200,
34158         minSize: 175,
34159         maxSize: 400,
34160         titlebar: true,
34161         collapsible: true
34162     },
34163     east: {
34164         split:true,
34165         initialSize: 202,
34166         minSize: 175,
34167         maxSize: 400,
34168         titlebar: true,
34169         collapsible: true
34170     },
34171     south: {
34172         split:true,
34173         initialSize: 100,
34174         minSize: 100,
34175         maxSize: 200,
34176         titlebar: true,
34177         collapsible: true
34178     },
34179     center: {
34180         titlebar: true,
34181         autoScroll:true,
34182         resizeTabs: true,
34183         minTabWidth: 50,
34184         preferredTabWidth: 150
34185     }
34186 });
34187
34188 // shorthand
34189 var CP = Roo.ContentPanel;
34190
34191 layout.beginUpdate();
34192 layout.add("north", new CP("north", "North"));
34193 layout.add("south", new CP("south", {title: "South", closable: true}));
34194 layout.add("west", new CP("west", {title: "West"}));
34195 layout.add("east", new CP("autoTabs", {title: "Auto Tabs", closable: true}));
34196 layout.add("center", new CP("center1", {title: "Close Me", closable: true}));
34197 layout.add("center", new CP("center2", {title: "Center Panel", closable: false}));
34198 layout.getRegion("center").showPanel("center1");
34199 layout.endUpdate();
34200 </code></pre>
34201
34202 <b>The container the layout is rendered into can be either the body element or any other element.
34203 If it is not the body element, the container needs to either be an absolute positioned element,
34204 or you will need to add "position:relative" to the css of the container.  You will also need to specify
34205 the container size if it is not the body element.</b>
34206
34207 * @constructor
34208 * Create a new BorderLayout
34209 * @param {String/HTMLElement/Element} container The container this layout is bound to
34210 * @param {Object} config Configuration options
34211  */
34212 Roo.BorderLayout = function(container, config){
34213     config = config || {};
34214     Roo.BorderLayout.superclass.constructor.call(this, container, config);
34215     this.factory = config.factory || Roo.BorderLayout.RegionFactory;
34216     for(var i = 0, len = this.factory.validRegions.length; i < len; i++) {
34217         var target = this.factory.validRegions[i];
34218         if(config[target]){
34219             this.addRegion(target, config[target]);
34220         }
34221     }
34222 };
34223
34224 Roo.extend(Roo.BorderLayout, Roo.LayoutManager, {
34225         
34226         /**
34227          * @cfg {Roo.LayoutRegion} east
34228          */
34229         /**
34230          * @cfg {Roo.LayoutRegion} west
34231          */
34232         /**
34233          * @cfg {Roo.LayoutRegion} north
34234          */
34235         /**
34236          * @cfg {Roo.LayoutRegion} south
34237          */
34238         /**
34239          * @cfg {Roo.LayoutRegion} center
34240          */
34241     /**
34242      * Creates and adds a new region if it doesn't already exist.
34243      * @param {String} target The target region key (north, south, east, west or center).
34244      * @param {Object} config The regions config object
34245      * @return {BorderLayoutRegion} The new region
34246      */
34247     addRegion : function(target, config){
34248         if(!this.regions[target]){
34249             var r = this.factory.create(target, this, config);
34250             this.bindRegion(target, r);
34251         }
34252         return this.regions[target];
34253     },
34254
34255     // private (kinda)
34256     bindRegion : function(name, r){
34257         this.regions[name] = r;
34258         r.on("visibilitychange", this.layout, this);
34259         r.on("paneladded", this.layout, this);
34260         r.on("panelremoved", this.layout, this);
34261         r.on("invalidated", this.layout, this);
34262         r.on("resized", this.onRegionResized, this);
34263         r.on("collapsed", this.onRegionCollapsed, this);
34264         r.on("expanded", this.onRegionExpanded, this);
34265     },
34266
34267     /**
34268      * Performs a layout update.
34269      */
34270     layout : function(){
34271         if(this.updating) {
34272             return;
34273         }
34274         var size = this.getViewSize();
34275         var w = size.width;
34276         var h = size.height;
34277         var centerW = w;
34278         var centerH = h;
34279         var centerY = 0;
34280         var centerX = 0;
34281         //var x = 0, y = 0;
34282
34283         var rs = this.regions;
34284         var north = rs["north"];
34285         var south = rs["south"]; 
34286         var west = rs["west"];
34287         var east = rs["east"];
34288         var center = rs["center"];
34289         //if(this.hideOnLayout){ // not supported anymore
34290             //c.el.setStyle("display", "none");
34291         //}
34292         if(north && north.isVisible()){
34293             var b = north.getBox();
34294             var m = north.getMargins();
34295             b.width = w - (m.left+m.right);
34296             b.x = m.left;
34297             b.y = m.top;
34298             centerY = b.height + b.y + m.bottom;
34299             centerH -= centerY;
34300             north.updateBox(this.safeBox(b));
34301         }
34302         if(south && south.isVisible()){
34303             var b = south.getBox();
34304             var m = south.getMargins();
34305             b.width = w - (m.left+m.right);
34306             b.x = m.left;
34307             var totalHeight = (b.height + m.top + m.bottom);
34308             b.y = h - totalHeight + m.top;
34309             centerH -= totalHeight;
34310             south.updateBox(this.safeBox(b));
34311         }
34312         if(west && west.isVisible()){
34313             var b = west.getBox();
34314             var m = west.getMargins();
34315             b.height = centerH - (m.top+m.bottom);
34316             b.x = m.left;
34317             b.y = centerY + m.top;
34318             var totalWidth = (b.width + m.left + m.right);
34319             centerX += totalWidth;
34320             centerW -= totalWidth;
34321             west.updateBox(this.safeBox(b));
34322         }
34323         if(east && east.isVisible()){
34324             var b = east.getBox();
34325             var m = east.getMargins();
34326             b.height = centerH - (m.top+m.bottom);
34327             var totalWidth = (b.width + m.left + m.right);
34328             b.x = w - totalWidth + m.left;
34329             b.y = centerY + m.top;
34330             centerW -= totalWidth;
34331             east.updateBox(this.safeBox(b));
34332         }
34333         if(center){
34334             var m = center.getMargins();
34335             var centerBox = {
34336                 x: centerX + m.left,
34337                 y: centerY + m.top,
34338                 width: centerW - (m.left+m.right),
34339                 height: centerH - (m.top+m.bottom)
34340             };
34341             //if(this.hideOnLayout){
34342                 //center.el.setStyle("display", "block");
34343             //}
34344             center.updateBox(this.safeBox(centerBox));
34345         }
34346         this.el.repaint();
34347         this.fireEvent("layout", this);
34348     },
34349
34350     // private
34351     safeBox : function(box){
34352         box.width = Math.max(0, box.width);
34353         box.height = Math.max(0, box.height);
34354         return box;
34355     },
34356
34357     /**
34358      * Adds a ContentPanel (or subclass) to this layout.
34359      * @param {String} target The target region key (north, south, east, west or center).
34360      * @param {Roo.ContentPanel} panel The panel to add
34361      * @return {Roo.ContentPanel} The added panel
34362      */
34363     add : function(target, panel){
34364          
34365         target = target.toLowerCase();
34366         return this.regions[target].add(panel);
34367     },
34368
34369     /**
34370      * Remove a ContentPanel (or subclass) to this layout.
34371      * @param {String} target The target region key (north, south, east, west or center).
34372      * @param {Number/String/Roo.ContentPanel} panel The index, id or panel to remove
34373      * @return {Roo.ContentPanel} The removed panel
34374      */
34375     remove : function(target, panel){
34376         target = target.toLowerCase();
34377         return this.regions[target].remove(panel);
34378     },
34379
34380     /**
34381      * Searches all regions for a panel with the specified id
34382      * @param {String} panelId
34383      * @return {Roo.ContentPanel} The panel or null if it wasn't found
34384      */
34385     findPanel : function(panelId){
34386         var rs = this.regions;
34387         for(var target in rs){
34388             if(typeof rs[target] != "function"){
34389                 var p = rs[target].getPanel(panelId);
34390                 if(p){
34391                     return p;
34392                 }
34393             }
34394         }
34395         return null;
34396     },
34397
34398     /**
34399      * Searches all regions for a panel with the specified id and activates (shows) it.
34400      * @param {String/ContentPanel} panelId The panels id or the panel itself
34401      * @return {Roo.ContentPanel} The shown panel or null
34402      */
34403     showPanel : function(panelId) {
34404       var rs = this.regions;
34405       for(var target in rs){
34406          var r = rs[target];
34407          if(typeof r != "function"){
34408             if(r.hasPanel(panelId)){
34409                return r.showPanel(panelId);
34410             }
34411          }
34412       }
34413       return null;
34414    },
34415
34416    /**
34417      * Restores this layout's state using Roo.state.Manager or the state provided by the passed provider.
34418      * @param {Roo.state.Provider} provider (optional) An alternate state provider
34419      */
34420     restoreState : function(provider){
34421         if(!provider){
34422             provider = Roo.state.Manager;
34423         }
34424         var sm = new Roo.LayoutStateManager();
34425         sm.init(this, provider);
34426     },
34427
34428     /**
34429      * Adds a batch of multiple ContentPanels dynamically by passing a special regions config object.  This config
34430      * object should contain properties for each region to add ContentPanels to, and each property's value should be
34431      * a valid ContentPanel config object.  Example:
34432      * <pre><code>
34433 // Create the main layout
34434 var layout = new Roo.BorderLayout('main-ct', {
34435     west: {
34436         split:true,
34437         minSize: 175,
34438         titlebar: true
34439     },
34440     center: {
34441         title:'Components'
34442     }
34443 }, 'main-ct');
34444
34445 // Create and add multiple ContentPanels at once via configs
34446 layout.batchAdd({
34447    west: {
34448        id: 'source-files',
34449        autoCreate:true,
34450        title:'Ext Source Files',
34451        autoScroll:true,
34452        fitToFrame:true
34453    },
34454    center : {
34455        el: cview,
34456        autoScroll:true,
34457        fitToFrame:true,
34458        toolbar: tb,
34459        resizeEl:'cbody'
34460    }
34461 });
34462 </code></pre>
34463      * @param {Object} regions An object containing ContentPanel configs by region name
34464      */
34465     batchAdd : function(regions){
34466         this.beginUpdate();
34467         for(var rname in regions){
34468             var lr = this.regions[rname];
34469             if(lr){
34470                 this.addTypedPanels(lr, regions[rname]);
34471             }
34472         }
34473         this.endUpdate();
34474     },
34475
34476     // private
34477     addTypedPanels : function(lr, ps){
34478         if(typeof ps == 'string'){
34479             lr.add(new Roo.ContentPanel(ps));
34480         }
34481         else if(ps instanceof Array){
34482             for(var i =0, len = ps.length; i < len; i++){
34483                 this.addTypedPanels(lr, ps[i]);
34484             }
34485         }
34486         else if(!ps.events){ // raw config?
34487             var el = ps.el;
34488             delete ps.el; // prevent conflict
34489             lr.add(new Roo.ContentPanel(el || Roo.id(), ps));
34490         }
34491         else {  // panel object assumed!
34492             lr.add(ps);
34493         }
34494     },
34495     /**
34496      * Adds a xtype elements to the layout.
34497      * <pre><code>
34498
34499 layout.addxtype({
34500        xtype : 'ContentPanel',
34501        region: 'west',
34502        items: [ .... ]
34503    }
34504 );
34505
34506 layout.addxtype({
34507         xtype : 'NestedLayoutPanel',
34508         region: 'west',
34509         layout: {
34510            center: { },
34511            west: { }   
34512         },
34513         items : [ ... list of content panels or nested layout panels.. ]
34514    }
34515 );
34516 </code></pre>
34517      * @param {Object} cfg Xtype definition of item to add.
34518      */
34519     addxtype : function(cfg)
34520     {
34521         // basically accepts a pannel...
34522         // can accept a layout region..!?!?
34523         //Roo.log('Roo.BorderLayout add ' + cfg.xtype)
34524         
34525         if (!cfg.xtype.match(/Panel$/)) {
34526             return false;
34527         }
34528         var ret = false;
34529         
34530         if (typeof(cfg.region) == 'undefined') {
34531             Roo.log("Failed to add Panel, region was not set");
34532             Roo.log(cfg);
34533             return false;
34534         }
34535         var region = cfg.region;
34536         delete cfg.region;
34537         
34538           
34539         var xitems = [];
34540         if (cfg.items) {
34541             xitems = cfg.items;
34542             delete cfg.items;
34543         }
34544         var nb = false;
34545         
34546         switch(cfg.xtype) 
34547         {
34548             case 'ContentPanel':  // ContentPanel (el, cfg)
34549             case 'ScrollPanel':  // ContentPanel (el, cfg)
34550             case 'ViewPanel': 
34551                 if(cfg.autoCreate) {
34552                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
34553                 } else {
34554                     var el = this.el.createChild();
34555                     ret = new Roo[cfg.xtype](el, cfg); // new panel!!!!!
34556                 }
34557                 
34558                 this.add(region, ret);
34559                 break;
34560             
34561             
34562             case 'TreePanel': // our new panel!
34563                 cfg.el = this.el.createChild();
34564                 ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
34565                 this.add(region, ret);
34566                 break;
34567             
34568             case 'NestedLayoutPanel': 
34569                 // create a new Layout (which is  a Border Layout...
34570                 var el = this.el.createChild();
34571                 var clayout = cfg.layout;
34572                 delete cfg.layout;
34573                 clayout.items   = clayout.items  || [];
34574                 // replace this exitems with the clayout ones..
34575                 xitems = clayout.items;
34576                  
34577                 
34578                 if (region == 'center' && this.active && this.getRegion('center').panels.length < 1) {
34579                     cfg.background = false;
34580                 }
34581                 var layout = new Roo.BorderLayout(el, clayout);
34582                 
34583                 ret = new Roo[cfg.xtype](layout, cfg); // new panel!!!!!
34584                 //console.log('adding nested layout panel '  + cfg.toSource());
34585                 this.add(region, ret);
34586                 nb = {}; /// find first...
34587                 break;
34588                 
34589             case 'GridPanel': 
34590             
34591                 // needs grid and region
34592                 
34593                 //var el = this.getRegion(region).el.createChild();
34594                 var el = this.el.createChild();
34595                 // create the grid first...
34596                 
34597                 var grid = new Roo.grid[cfg.grid.xtype](el, cfg.grid);
34598                 delete cfg.grid;
34599                 if (region == 'center' && this.active ) {
34600                     cfg.background = false;
34601                 }
34602                 ret = new Roo[cfg.xtype](grid, cfg); // new panel!!!!!
34603                 
34604                 this.add(region, ret);
34605                 if (cfg.background) {
34606                     ret.on('activate', function(gp) {
34607                         if (!gp.grid.rendered) {
34608                             gp.grid.render();
34609                         }
34610                     });
34611                 } else {
34612                     grid.render();
34613                 }
34614                 break;
34615            
34616            
34617            
34618                 
34619                 
34620                 
34621             default:
34622                 if (typeof(Roo[cfg.xtype]) != 'undefined') {
34623                     
34624                     ret = new Roo[cfg.xtype](cfg); // new panel!!!!!
34625                     this.add(region, ret);
34626                 } else {
34627                 
34628                     alert("Can not add '" + cfg.xtype + "' to BorderLayout");
34629                     return null;
34630                 }
34631                 
34632              // GridPanel (grid, cfg)
34633             
34634         }
34635         this.beginUpdate();
34636         // add children..
34637         var region = '';
34638         var abn = {};
34639         Roo.each(xitems, function(i)  {
34640             region = nb && i.region ? i.region : false;
34641             
34642             var add = ret.addxtype(i);
34643            
34644             if (region) {
34645                 nb[region] = nb[region] == undefined ? 0 : nb[region]+1;
34646                 if (!i.background) {
34647                     abn[region] = nb[region] ;
34648                 }
34649             }
34650             
34651         });
34652         this.endUpdate();
34653
34654         // make the last non-background panel active..
34655         //if (nb) { Roo.log(abn); }
34656         if (nb) {
34657             
34658             for(var r in abn) {
34659                 region = this.getRegion(r);
34660                 if (region) {
34661                     // tried using nb[r], but it does not work..
34662                      
34663                     region.showPanel(abn[r]);
34664                    
34665                 }
34666             }
34667         }
34668         return ret;
34669         
34670     }
34671 });
34672
34673 /**
34674  * Shortcut for creating a new BorderLayout object and adding one or more ContentPanels to it in a single step, handling
34675  * the beginUpdate and endUpdate calls internally.  The key to this method is the <b>panels</b> property that can be
34676  * provided with each region config, which allows you to add ContentPanel configs in addition to the region configs
34677  * during creation.  The following code is equivalent to the constructor-based example at the beginning of this class:
34678  * <pre><code>
34679 // shorthand
34680 var CP = Roo.ContentPanel;
34681
34682 var layout = Roo.BorderLayout.create({
34683     north: {
34684         initialSize: 25,
34685         titlebar: false,
34686         panels: [new CP("north", "North")]
34687     },
34688     west: {
34689         split:true,
34690         initialSize: 200,
34691         minSize: 175,
34692         maxSize: 400,
34693         titlebar: true,
34694         collapsible: true,
34695         panels: [new CP("west", {title: "West"})]
34696     },
34697     east: {
34698         split:true,
34699         initialSize: 202,
34700         minSize: 175,
34701         maxSize: 400,
34702         titlebar: true,
34703         collapsible: true,
34704         panels: [new CP("autoTabs", {title: "Auto Tabs", closable: true})]
34705     },
34706     south: {
34707         split:true,
34708         initialSize: 100,
34709         minSize: 100,
34710         maxSize: 200,
34711         titlebar: true,
34712         collapsible: true,
34713         panels: [new CP("south", {title: "South", closable: true})]
34714     },
34715     center: {
34716         titlebar: true,
34717         autoScroll:true,
34718         resizeTabs: true,
34719         minTabWidth: 50,
34720         preferredTabWidth: 150,
34721         panels: [
34722             new CP("center1", {title: "Close Me", closable: true}),
34723             new CP("center2", {title: "Center Panel", closable: false})
34724         ]
34725     }
34726 }, document.body);
34727
34728 layout.getRegion("center").showPanel("center1");
34729 </code></pre>
34730  * @param config
34731  * @param targetEl
34732  */
34733 Roo.BorderLayout.create = function(config, targetEl){
34734     var layout = new Roo.BorderLayout(targetEl || document.body, config);
34735     layout.beginUpdate();
34736     var regions = Roo.BorderLayout.RegionFactory.validRegions;
34737     for(var j = 0, jlen = regions.length; j < jlen; j++){
34738         var lr = regions[j];
34739         if(layout.regions[lr] && config[lr].panels){
34740             var r = layout.regions[lr];
34741             var ps = config[lr].panels;
34742             layout.addTypedPanels(r, ps);
34743         }
34744     }
34745     layout.endUpdate();
34746     return layout;
34747 };
34748
34749 // private
34750 Roo.BorderLayout.RegionFactory = {
34751     // private
34752     validRegions : ["north","south","east","west","center"],
34753
34754     // private
34755     create : function(target, mgr, config){
34756         target = target.toLowerCase();
34757         if(config.lightweight || config.basic){
34758             return new Roo.BasicLayoutRegion(mgr, config, target);
34759         }
34760         switch(target){
34761             case "north":
34762                 return new Roo.NorthLayoutRegion(mgr, config);
34763             case "south":
34764                 return new Roo.SouthLayoutRegion(mgr, config);
34765             case "east":
34766                 return new Roo.EastLayoutRegion(mgr, config);
34767             case "west":
34768                 return new Roo.WestLayoutRegion(mgr, config);
34769             case "center":
34770                 return new Roo.CenterLayoutRegion(mgr, config);
34771         }
34772         throw 'Layout region "'+target+'" not supported.';
34773     }
34774 };/*
34775  * Based on:
34776  * Ext JS Library 1.1.1
34777  * Copyright(c) 2006-2007, Ext JS, LLC.
34778  *
34779  * Originally Released Under LGPL - original licence link has changed is not relivant.
34780  *
34781  * Fork - LGPL
34782  * <script type="text/javascript">
34783  */
34784  
34785 /**
34786  * @class Roo.BasicLayoutRegion
34787  * @extends Roo.util.Observable
34788  * This class represents a lightweight region in a layout manager. This region does not move dom nodes
34789  * and does not have a titlebar, tabs or any other features. All it does is size and position 
34790  * panels. To create a BasicLayoutRegion, add lightweight:true or basic:true to your regions config.
34791  */
34792 Roo.BasicLayoutRegion = function(mgr, config, pos, skipConfig){
34793     this.mgr = mgr;
34794     this.position  = pos;
34795     this.events = {
34796         /**
34797          * @scope Roo.BasicLayoutRegion
34798          */
34799         
34800         /**
34801          * @event beforeremove
34802          * Fires before a panel is removed (or closed). To cancel the removal set "e.cancel = true" on the event argument.
34803          * @param {Roo.LayoutRegion} this
34804          * @param {Roo.ContentPanel} panel The panel
34805          * @param {Object} e The cancel event object
34806          */
34807         "beforeremove" : true,
34808         /**
34809          * @event invalidated
34810          * Fires when the layout for this region is changed.
34811          * @param {Roo.LayoutRegion} this
34812          */
34813         "invalidated" : true,
34814         /**
34815          * @event visibilitychange
34816          * Fires when this region is shown or hidden 
34817          * @param {Roo.LayoutRegion} this
34818          * @param {Boolean} visibility true or false
34819          */
34820         "visibilitychange" : true,
34821         /**
34822          * @event paneladded
34823          * Fires when a panel is added. 
34824          * @param {Roo.LayoutRegion} this
34825          * @param {Roo.ContentPanel} panel The panel
34826          */
34827         "paneladded" : true,
34828         /**
34829          * @event panelremoved
34830          * Fires when a panel is removed. 
34831          * @param {Roo.LayoutRegion} this
34832          * @param {Roo.ContentPanel} panel The panel
34833          */
34834         "panelremoved" : true,
34835         /**
34836          * @event beforecollapse
34837          * Fires when this region before collapse.
34838          * @param {Roo.LayoutRegion} this
34839          */
34840         "beforecollapse" : true,
34841         /**
34842          * @event collapsed
34843          * Fires when this region is collapsed.
34844          * @param {Roo.LayoutRegion} this
34845          */
34846         "collapsed" : true,
34847         /**
34848          * @event expanded
34849          * Fires when this region is expanded.
34850          * @param {Roo.LayoutRegion} this
34851          */
34852         "expanded" : true,
34853         /**
34854          * @event slideshow
34855          * Fires when this region is slid into view.
34856          * @param {Roo.LayoutRegion} this
34857          */
34858         "slideshow" : true,
34859         /**
34860          * @event slidehide
34861          * Fires when this region slides out of view. 
34862          * @param {Roo.LayoutRegion} this
34863          */
34864         "slidehide" : true,
34865         /**
34866          * @event panelactivated
34867          * Fires when a panel is activated. 
34868          * @param {Roo.LayoutRegion} this
34869          * @param {Roo.ContentPanel} panel The activated panel
34870          */
34871         "panelactivated" : true,
34872         /**
34873          * @event resized
34874          * Fires when the user resizes this region. 
34875          * @param {Roo.LayoutRegion} this
34876          * @param {Number} newSize The new size (width for east/west, height for north/south)
34877          */
34878         "resized" : true
34879     };
34880     /** A collection of panels in this region. @type Roo.util.MixedCollection */
34881     this.panels = new Roo.util.MixedCollection();
34882     this.panels.getKey = this.getPanelId.createDelegate(this);
34883     this.box = null;
34884     this.activePanel = null;
34885     // ensure listeners are added...
34886     
34887     if (config.listeners || config.events) {
34888         Roo.BasicLayoutRegion.superclass.constructor.call(this, {
34889             listeners : config.listeners || {},
34890             events : config.events || {}
34891         });
34892     }
34893     
34894     if(skipConfig !== true){
34895         this.applyConfig(config);
34896     }
34897 };
34898
34899 Roo.extend(Roo.BasicLayoutRegion, Roo.util.Observable, {
34900     getPanelId : function(p){
34901         return p.getId();
34902     },
34903     
34904     applyConfig : function(config){
34905         this.margins = config.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
34906         this.config = config;
34907         
34908     },
34909     
34910     /**
34911      * Resizes the region to the specified size. For vertical regions (west, east) this adjusts 
34912      * the width, for horizontal (north, south) the height.
34913      * @param {Number} newSize The new width or height
34914      */
34915     resizeTo : function(newSize){
34916         var el = this.el ? this.el :
34917                  (this.activePanel ? this.activePanel.getEl() : null);
34918         if(el){
34919             switch(this.position){
34920                 case "east":
34921                 case "west":
34922                     el.setWidth(newSize);
34923                     this.fireEvent("resized", this, newSize);
34924                 break;
34925                 case "north":
34926                 case "south":
34927                     el.setHeight(newSize);
34928                     this.fireEvent("resized", this, newSize);
34929                 break;                
34930             }
34931         }
34932     },
34933     
34934     getBox : function(){
34935         return this.activePanel ? this.activePanel.getEl().getBox(false, true) : null;
34936     },
34937     
34938     getMargins : function(){
34939         return this.margins;
34940     },
34941     
34942     updateBox : function(box){
34943         this.box = box;
34944         var el = this.activePanel.getEl();
34945         el.dom.style.left = box.x + "px";
34946         el.dom.style.top = box.y + "px";
34947         this.activePanel.setSize(box.width, box.height);
34948     },
34949     
34950     /**
34951      * Returns the container element for this region.
34952      * @return {Roo.Element}
34953      */
34954     getEl : function(){
34955         return this.activePanel;
34956     },
34957     
34958     /**
34959      * Returns true if this region is currently visible.
34960      * @return {Boolean}
34961      */
34962     isVisible : function(){
34963         return this.activePanel ? true : false;
34964     },
34965     
34966     setActivePanel : function(panel){
34967         panel = this.getPanel(panel);
34968         if(this.activePanel && this.activePanel != panel){
34969             this.activePanel.setActiveState(false);
34970             this.activePanel.getEl().setLeftTop(-10000,-10000);
34971         }
34972         this.activePanel = panel;
34973         panel.setActiveState(true);
34974         if(this.box){
34975             panel.setSize(this.box.width, this.box.height);
34976         }
34977         this.fireEvent("panelactivated", this, panel);
34978         this.fireEvent("invalidated");
34979     },
34980     
34981     /**
34982      * Show the specified panel.
34983      * @param {Number/String/ContentPanel} panelId The panels index, id or the panel itself
34984      * @return {Roo.ContentPanel} The shown panel or null
34985      */
34986     showPanel : function(panel){
34987         if(panel = this.getPanel(panel)){
34988             this.setActivePanel(panel);
34989         }
34990         return panel;
34991     },
34992     
34993     /**
34994      * Get the active panel for this region.
34995      * @return {Roo.ContentPanel} The active panel or null
34996      */
34997     getActivePanel : function(){
34998         return this.activePanel;
34999     },
35000     
35001     /**
35002      * Add the passed ContentPanel(s)
35003      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
35004      * @return {Roo.ContentPanel} The panel added (if only one was added)
35005      */
35006     add : function(panel){
35007         if(arguments.length > 1){
35008             for(var i = 0, len = arguments.length; i < len; i++) {
35009                 this.add(arguments[i]);
35010             }
35011             return null;
35012         }
35013         if(this.hasPanel(panel)){
35014             this.showPanel(panel);
35015             return panel;
35016         }
35017         var el = panel.getEl();
35018         if(el.dom.parentNode != this.mgr.el.dom){
35019             this.mgr.el.dom.appendChild(el.dom);
35020         }
35021         if(panel.setRegion){
35022             panel.setRegion(this);
35023         }
35024         this.panels.add(panel);
35025         el.setStyle("position", "absolute");
35026         if(!panel.background){
35027             this.setActivePanel(panel);
35028             if(this.config.initialSize && this.panels.getCount()==1){
35029                 this.resizeTo(this.config.initialSize);
35030             }
35031         }
35032         this.fireEvent("paneladded", this, panel);
35033         return panel;
35034     },
35035     
35036     /**
35037      * Returns true if the panel is in this region.
35038      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
35039      * @return {Boolean}
35040      */
35041     hasPanel : function(panel){
35042         if(typeof panel == "object"){ // must be panel obj
35043             panel = panel.getId();
35044         }
35045         return this.getPanel(panel) ? true : false;
35046     },
35047     
35048     /**
35049      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
35050      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
35051      * @param {Boolean} preservePanel Overrides the config preservePanel option
35052      * @return {Roo.ContentPanel} The panel that was removed
35053      */
35054     remove : function(panel, preservePanel){
35055         panel = this.getPanel(panel);
35056         if(!panel){
35057             return null;
35058         }
35059         var e = {};
35060         this.fireEvent("beforeremove", this, panel, e);
35061         if(e.cancel === true){
35062             return null;
35063         }
35064         var panelId = panel.getId();
35065         this.panels.removeKey(panelId);
35066         return panel;
35067     },
35068     
35069     /**
35070      * Returns the panel specified or null if it's not in this region.
35071      * @param {Number/String/ContentPanel} panel The panels index, id or the panel itself
35072      * @return {Roo.ContentPanel}
35073      */
35074     getPanel : function(id){
35075         if(typeof id == "object"){ // must be panel obj
35076             return id;
35077         }
35078         return this.panels.get(id);
35079     },
35080     
35081     /**
35082      * Returns this regions position (north/south/east/west/center).
35083      * @return {String} 
35084      */
35085     getPosition: function(){
35086         return this.position;    
35087     }
35088 });/*
35089  * Based on:
35090  * Ext JS Library 1.1.1
35091  * Copyright(c) 2006-2007, Ext JS, LLC.
35092  *
35093  * Originally Released Under LGPL - original licence link has changed is not relivant.
35094  *
35095  * Fork - LGPL
35096  * <script type="text/javascript">
35097  */
35098  
35099 /**
35100  * @class Roo.LayoutRegion
35101  * @extends Roo.BasicLayoutRegion
35102  * This class represents a region in a layout manager.
35103  * @cfg {Boolean}   collapsible     False to disable collapsing (defaults to true)
35104  * @cfg {Boolean}   collapsed       True to set the initial display to collapsed (defaults to false)
35105  * @cfg {Boolean}   floatable       False to disable floating (defaults to true)
35106  * @cfg {Object}    margins         Margins for the element (defaults to {top: 0, left: 0, right:0, bottom: 0})
35107  * @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})
35108  * @cfg {String}    tabPosition     (top|bottom) "top" or "bottom" (defaults to "bottom")
35109  * @cfg {String}    collapsedTitle  Optional string message to display in the collapsed block of a north or south region
35110  * @cfg {Boolean}   alwaysShowTabs  True to always display tabs even when there is only 1 panel (defaults to false)
35111  * @cfg {Boolean}   autoScroll      True to enable overflow scrolling (defaults to false)
35112  * @cfg {Boolean}   titlebar        True to display a title bar (defaults to true)
35113  * @cfg {String}    title           The title for the region (overrides panel titles)
35114  * @cfg {Boolean}   animate         True to animate expand/collapse (defaults to false)
35115  * @cfg {Boolean}   autoHide        False to disable auto hiding when the mouse leaves the "floated" region (defaults to true)
35116  * @cfg {Boolean}   preservePanels  True to preserve removed panels so they can be readded later (defaults to false)
35117  * @cfg {Boolean}   closeOnTab      True to place the close icon on the tabs instead of the region titlebar (defaults to false)
35118  * @cfg {Boolean}   hideTabs        True to hide the tab strip (defaults to false)
35119  * @cfg {Boolean}   resizeTabs      True to enable automatic tab resizing. This will resize the tabs so they are all the same size and fit within
35120  *                      the space available, similar to FireFox 1.5 tabs (defaults to false)
35121  * @cfg {Number}    minTabWidth     The minimum tab width (defaults to 40)
35122  * @cfg {Number}    preferredTabWidth The preferred tab width (defaults to 150)
35123  * @cfg {Boolean}   showPin         True to show a pin button
35124  * @cfg {Boolean}   hidden          True to start the region hidden (defaults to false)
35125  * @cfg {Boolean}   hideWhenEmpty   True to hide the region when it has no panels
35126  * @cfg {Boolean}   disableTabTips  True to disable tab tooltips
35127  * @cfg {Number}    width           For East/West panels
35128  * @cfg {Number}    height          For North/South panels
35129  * @cfg {Boolean}   split           To show the splitter
35130  * @cfg {Boolean}   toolbar         xtype configuration for a toolbar - shows on right of tabbar
35131  */
35132 Roo.LayoutRegion = function(mgr, config, pos){
35133     Roo.LayoutRegion.superclass.constructor.call(this, mgr, config, pos, true);
35134     var dh = Roo.DomHelper;
35135     /** This region's container element 
35136     * @type Roo.Element */
35137     this.el = dh.append(mgr.el.dom, {tag: "div", cls: "x-layout-panel x-layout-panel-" + this.position}, true);
35138     /** This region's title element 
35139     * @type Roo.Element */
35140
35141     this.titleEl = dh.append(this.el.dom, {tag: "div", unselectable: "on", cls: "x-unselectable x-layout-panel-hd x-layout-title-"+this.position, children:[
35142         {tag: "span", cls: "x-unselectable x-layout-panel-hd-text", unselectable: "on", html: "&#160;"},
35143         {tag: "div", cls: "x-unselectable x-layout-panel-hd-tools", unselectable: "on"}
35144     ]}, true);
35145     this.titleEl.enableDisplayMode();
35146     /** This region's title text element 
35147     * @type HTMLElement */
35148     this.titleTextEl = this.titleEl.dom.firstChild;
35149     this.tools = Roo.get(this.titleEl.dom.childNodes[1], true);
35150     this.closeBtn = this.createTool(this.tools.dom, "x-layout-close");
35151     this.closeBtn.enableDisplayMode();
35152     this.closeBtn.on("click", this.closeClicked, this);
35153     this.closeBtn.hide();
35154
35155     this.createBody(config);
35156     this.visible = true;
35157     this.collapsed = false;
35158
35159     if(config.hideWhenEmpty){
35160         this.hide();
35161         this.on("paneladded", this.validateVisibility, this);
35162         this.on("panelremoved", this.validateVisibility, this);
35163     }
35164     this.applyConfig(config);
35165 };
35166
35167 Roo.extend(Roo.LayoutRegion, Roo.BasicLayoutRegion, {
35168
35169     createBody : function(){
35170         /** This region's body element 
35171         * @type Roo.Element */
35172         this.bodyEl = this.el.createChild({tag: "div", cls: "x-layout-panel-body"});
35173     },
35174
35175     applyConfig : function(c){
35176         if(c.collapsible && this.position != "center" && !this.collapsedEl){
35177             var dh = Roo.DomHelper;
35178             if(c.titlebar !== false){
35179                 this.collapseBtn = this.createTool(this.tools.dom, "x-layout-collapse-"+this.position);
35180                 this.collapseBtn.on("click", this.collapse, this);
35181                 this.collapseBtn.enableDisplayMode();
35182
35183                 if(c.showPin === true || this.showPin){
35184                     this.stickBtn = this.createTool(this.tools.dom, "x-layout-stick");
35185                     this.stickBtn.enableDisplayMode();
35186                     this.stickBtn.on("click", this.expand, this);
35187                     this.stickBtn.hide();
35188                 }
35189             }
35190             /** This region's collapsed element
35191             * @type Roo.Element */
35192             this.collapsedEl = dh.append(this.mgr.el.dom, {cls: "x-layout-collapsed x-layout-collapsed-"+this.position, children:[
35193                 {cls: "x-layout-collapsed-tools", children:[{cls: "x-layout-ctools-inner"}]}
35194             ]}, true);
35195             if(c.floatable !== false){
35196                this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
35197                this.collapsedEl.on("click", this.collapseClick, this);
35198             }
35199
35200             if(c.collapsedTitle && (this.position == "north" || this.position== "south")) {
35201                 this.collapsedTitleTextEl = dh.append(this.collapsedEl.dom, {tag: "div", cls: "x-unselectable x-layout-panel-hd-text",
35202                    id: "message", unselectable: "on", style:{"float":"left"}});
35203                this.collapsedTitleTextEl.innerHTML = c.collapsedTitle;
35204              }
35205             this.expandBtn = this.createTool(this.collapsedEl.dom.firstChild.firstChild, "x-layout-expand-"+this.position);
35206             this.expandBtn.on("click", this.expand, this);
35207         }
35208         if(this.collapseBtn){
35209             this.collapseBtn.setVisible(c.collapsible == true);
35210         }
35211         this.cmargins = c.cmargins || this.cmargins ||
35212                          (this.position == "west" || this.position == "east" ?
35213                              {top: 0, left: 2, right:2, bottom: 0} :
35214                              {top: 2, left: 0, right:0, bottom: 2});
35215         this.margins = c.margins || this.margins || {top: 0, left: 0, right:0, bottom: 0};
35216         this.bottomTabs = c.tabPosition != "top";
35217         this.autoScroll = c.autoScroll || false;
35218         if(this.autoScroll){
35219             this.bodyEl.setStyle("overflow", "auto");
35220         }else{
35221             this.bodyEl.setStyle("overflow", "hidden");
35222         }
35223         //if(c.titlebar !== false){
35224             if((!c.titlebar && !c.title) || c.titlebar === false){
35225                 this.titleEl.hide();
35226             }else{
35227                 this.titleEl.show();
35228                 if(c.title){
35229                     this.titleTextEl.innerHTML = c.title;
35230                 }
35231             }
35232         //}
35233         this.duration = c.duration || .30;
35234         this.slideDuration = c.slideDuration || .45;
35235         this.config = c;
35236         if(c.collapsed){
35237             this.collapse(true);
35238         }
35239         if(c.hidden){
35240             this.hide();
35241         }
35242     },
35243     /**
35244      * Returns true if this region is currently visible.
35245      * @return {Boolean}
35246      */
35247     isVisible : function(){
35248         return this.visible;
35249     },
35250
35251     /**
35252      * Updates the title for collapsed north/south regions (used with {@link #collapsedTitle} config option)
35253      * @param {String} title (optional) The title text (accepts HTML markup, defaults to the numeric character reference for a non-breaking space, "&amp;#160;")
35254      */
35255     setCollapsedTitle : function(title){
35256         title = title || "&#160;";
35257         if(this.collapsedTitleTextEl){
35258             this.collapsedTitleTextEl.innerHTML = title;
35259         }
35260     },
35261
35262     getBox : function(){
35263         var b;
35264         if(!this.collapsed){
35265             b = this.el.getBox(false, true);
35266         }else{
35267             b = this.collapsedEl.getBox(false, true);
35268         }
35269         return b;
35270     },
35271
35272     getMargins : function(){
35273         return this.collapsed ? this.cmargins : this.margins;
35274     },
35275
35276     highlight : function(){
35277         this.el.addClass("x-layout-panel-dragover");
35278     },
35279
35280     unhighlight : function(){
35281         this.el.removeClass("x-layout-panel-dragover");
35282     },
35283
35284     updateBox : function(box){
35285         this.box = box;
35286         if(!this.collapsed){
35287             this.el.dom.style.left = box.x + "px";
35288             this.el.dom.style.top = box.y + "px";
35289             this.updateBody(box.width, box.height);
35290         }else{
35291             this.collapsedEl.dom.style.left = box.x + "px";
35292             this.collapsedEl.dom.style.top = box.y + "px";
35293             this.collapsedEl.setSize(box.width, box.height);
35294         }
35295         if(this.tabs){
35296             this.tabs.autoSizeTabs();
35297         }
35298     },
35299
35300     updateBody : function(w, h){
35301         if(w !== null){
35302             this.el.setWidth(w);
35303             w -= this.el.getBorderWidth("rl");
35304             if(this.config.adjustments){
35305                 w += this.config.adjustments[0];
35306             }
35307         }
35308         if(h !== null){
35309             this.el.setHeight(h);
35310             h = this.titleEl && this.titleEl.isDisplayed() ? h - (this.titleEl.getHeight()||0) : h;
35311             h -= this.el.getBorderWidth("tb");
35312             if(this.config.adjustments){
35313                 h += this.config.adjustments[1];
35314             }
35315             this.bodyEl.setHeight(h);
35316             if(this.tabs){
35317                 h = this.tabs.syncHeight(h);
35318             }
35319         }
35320         if(this.panelSize){
35321             w = w !== null ? w : this.panelSize.width;
35322             h = h !== null ? h : this.panelSize.height;
35323         }
35324         if(this.activePanel){
35325             var el = this.activePanel.getEl();
35326             w = w !== null ? w : el.getWidth();
35327             h = h !== null ? h : el.getHeight();
35328             this.panelSize = {width: w, height: h};
35329             this.activePanel.setSize(w, h);
35330         }
35331         if(Roo.isIE && this.tabs){
35332             this.tabs.el.repaint();
35333         }
35334     },
35335
35336     /**
35337      * Returns the container element for this region.
35338      * @return {Roo.Element}
35339      */
35340     getEl : function(){
35341         return this.el;
35342     },
35343
35344     /**
35345      * Hides this region.
35346      */
35347     hide : function(){
35348         if(!this.collapsed){
35349             this.el.dom.style.left = "-2000px";
35350             this.el.hide();
35351         }else{
35352             this.collapsedEl.dom.style.left = "-2000px";
35353             this.collapsedEl.hide();
35354         }
35355         this.visible = false;
35356         this.fireEvent("visibilitychange", this, false);
35357     },
35358
35359     /**
35360      * Shows this region if it was previously hidden.
35361      */
35362     show : function(){
35363         if(!this.collapsed){
35364             this.el.show();
35365         }else{
35366             this.collapsedEl.show();
35367         }
35368         this.visible = true;
35369         this.fireEvent("visibilitychange", this, true);
35370     },
35371
35372     closeClicked : function(){
35373         if(this.activePanel){
35374             this.remove(this.activePanel);
35375         }
35376     },
35377
35378     collapseClick : function(e){
35379         if(this.isSlid){
35380            e.stopPropagation();
35381            this.slideIn();
35382         }else{
35383            e.stopPropagation();
35384            this.slideOut();
35385         }
35386     },
35387
35388     /**
35389      * Collapses this region.
35390      * @param {Boolean} skipAnim (optional) true to collapse the element without animation (if animate is true)
35391      */
35392     collapse : function(skipAnim, skipCheck){
35393         if(this.collapsed) {
35394             return;
35395         }
35396         
35397         if(skipCheck || this.fireEvent("beforecollapse", this) != false){
35398             
35399             this.collapsed = true;
35400             if(this.split){
35401                 this.split.el.hide();
35402             }
35403             if(this.config.animate && skipAnim !== true){
35404                 this.fireEvent("invalidated", this);
35405                 this.animateCollapse();
35406             }else{
35407                 this.el.setLocation(-20000,-20000);
35408                 this.el.hide();
35409                 this.collapsedEl.show();
35410                 this.fireEvent("collapsed", this);
35411                 this.fireEvent("invalidated", this);
35412             }
35413         }
35414         
35415     },
35416
35417     animateCollapse : function(){
35418         // overridden
35419     },
35420
35421     /**
35422      * Expands this region if it was previously collapsed.
35423      * @param {Roo.EventObject} e The event that triggered the expand (or null if calling manually)
35424      * @param {Boolean} skipAnim (optional) true to expand the element without animation (if animate is true)
35425      */
35426     expand : function(e, skipAnim){
35427         if(e) {
35428             e.stopPropagation();
35429         }
35430         if(!this.collapsed || this.el.hasActiveFx()) {
35431             return;
35432         }
35433         if(this.isSlid){
35434             this.afterSlideIn();
35435             skipAnim = true;
35436         }
35437         this.collapsed = false;
35438         if(this.config.animate && skipAnim !== true){
35439             this.animateExpand();
35440         }else{
35441             this.el.show();
35442             if(this.split){
35443                 this.split.el.show();
35444             }
35445             this.collapsedEl.setLocation(-2000,-2000);
35446             this.collapsedEl.hide();
35447             this.fireEvent("invalidated", this);
35448             this.fireEvent("expanded", this);
35449         }
35450     },
35451
35452     animateExpand : function(){
35453         // overridden
35454     },
35455
35456     initTabs : function()
35457     {
35458         this.bodyEl.setStyle("overflow", "hidden");
35459         var ts = new Roo.TabPanel(
35460                 this.bodyEl.dom,
35461                 {
35462                     tabPosition: this.bottomTabs ? 'bottom' : 'top',
35463                     disableTooltips: this.config.disableTabTips,
35464                     toolbar : this.config.toolbar
35465                 }
35466         );
35467         if(this.config.hideTabs){
35468             ts.stripWrap.setDisplayed(false);
35469         }
35470         this.tabs = ts;
35471         ts.resizeTabs = this.config.resizeTabs === true;
35472         ts.minTabWidth = this.config.minTabWidth || 40;
35473         ts.maxTabWidth = this.config.maxTabWidth || 250;
35474         ts.preferredTabWidth = this.config.preferredTabWidth || 150;
35475         ts.monitorResize = false;
35476         ts.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
35477         ts.bodyEl.addClass('x-layout-tabs-body');
35478         this.panels.each(this.initPanelAsTab, this);
35479     },
35480
35481     initPanelAsTab : function(panel){
35482         var ti = this.tabs.addTab(panel.getEl().id, panel.getTitle(), null,
35483                     this.config.closeOnTab && panel.isClosable());
35484         if(panel.tabTip !== undefined){
35485             ti.setTooltip(panel.tabTip);
35486         }
35487         ti.on("activate", function(){
35488               this.setActivePanel(panel);
35489         }, this);
35490         if(this.config.closeOnTab){
35491             ti.on("beforeclose", function(t, e){
35492                 e.cancel = true;
35493                 this.remove(panel);
35494             }, this);
35495         }
35496         return ti;
35497     },
35498
35499     updatePanelTitle : function(panel, title){
35500         if(this.activePanel == panel){
35501             this.updateTitle(title);
35502         }
35503         if(this.tabs){
35504             var ti = this.tabs.getTab(panel.getEl().id);
35505             ti.setText(title);
35506             if(panel.tabTip !== undefined){
35507                 ti.setTooltip(panel.tabTip);
35508             }
35509         }
35510     },
35511
35512     updateTitle : function(title){
35513         if(this.titleTextEl && !this.config.title){
35514             this.titleTextEl.innerHTML = (typeof title != "undefined" && title.length > 0 ? title : "&#160;");
35515         }
35516     },
35517
35518     setActivePanel : function(panel){
35519         panel = this.getPanel(panel);
35520         if(this.activePanel && this.activePanel != panel){
35521             this.activePanel.setActiveState(false);
35522         }
35523         this.activePanel = panel;
35524         panel.setActiveState(true);
35525         if(this.panelSize){
35526             panel.setSize(this.panelSize.width, this.panelSize.height);
35527         }
35528         if(this.closeBtn){
35529             this.closeBtn.setVisible(!this.config.closeOnTab && !this.isSlid && panel.isClosable());
35530         }
35531         this.updateTitle(panel.getTitle());
35532         if(this.tabs){
35533             this.fireEvent("invalidated", this);
35534         }
35535         this.fireEvent("panelactivated", this, panel);
35536     },
35537
35538     /**
35539      * Shows the specified panel.
35540      * @param {Number/String/ContentPanel} panelId The panel's index, id or the panel itself
35541      * @return {Roo.ContentPanel} The shown panel, or null if a panel could not be found from panelId
35542      */
35543     showPanel : function(panel)
35544     {
35545         panel = this.getPanel(panel);
35546         if(panel){
35547             if(this.tabs){
35548                 var tab = this.tabs.getTab(panel.getEl().id);
35549                 if(tab.isHidden()){
35550                     this.tabs.unhideTab(tab.id);
35551                 }
35552                 tab.activate();
35553             }else{
35554                 this.setActivePanel(panel);
35555             }
35556         }
35557         return panel;
35558     },
35559
35560     /**
35561      * Get the active panel for this region.
35562      * @return {Roo.ContentPanel} The active panel or null
35563      */
35564     getActivePanel : function(){
35565         return this.activePanel;
35566     },
35567
35568     validateVisibility : function(){
35569         if(this.panels.getCount() < 1){
35570             this.updateTitle("&#160;");
35571             this.closeBtn.hide();
35572             this.hide();
35573         }else{
35574             if(!this.isVisible()){
35575                 this.show();
35576             }
35577         }
35578     },
35579
35580     /**
35581      * Adds the passed ContentPanel(s) to this region.
35582      * @param {ContentPanel...} panel The ContentPanel(s) to add (you can pass more than one)
35583      * @return {Roo.ContentPanel} The panel added (if only one was added; null otherwise)
35584      */
35585     add : function(panel){
35586         if(arguments.length > 1){
35587             for(var i = 0, len = arguments.length; i < len; i++) {
35588                 this.add(arguments[i]);
35589             }
35590             return null;
35591         }
35592         if(this.hasPanel(panel)){
35593             this.showPanel(panel);
35594             return panel;
35595         }
35596         panel.setRegion(this);
35597         this.panels.add(panel);
35598         if(this.panels.getCount() == 1 && !this.config.alwaysShowTabs){
35599             this.bodyEl.dom.appendChild(panel.getEl().dom);
35600             if(panel.background !== true){
35601                 this.setActivePanel(panel);
35602             }
35603             this.fireEvent("paneladded", this, panel);
35604             return panel;
35605         }
35606         if(!this.tabs){
35607             this.initTabs();
35608         }else{
35609             this.initPanelAsTab(panel);
35610         }
35611         if(panel.background !== true){
35612             this.tabs.activate(panel.getEl().id);
35613         }
35614         this.fireEvent("paneladded", this, panel);
35615         return panel;
35616     },
35617
35618     /**
35619      * Hides the tab for the specified panel.
35620      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
35621      */
35622     hidePanel : function(panel){
35623         if(this.tabs && (panel = this.getPanel(panel))){
35624             this.tabs.hideTab(panel.getEl().id);
35625         }
35626     },
35627
35628     /**
35629      * Unhides the tab for a previously hidden panel.
35630      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
35631      */
35632     unhidePanel : function(panel){
35633         if(this.tabs && (panel = this.getPanel(panel))){
35634             this.tabs.unhideTab(panel.getEl().id);
35635         }
35636     },
35637
35638     clearPanels : function(){
35639         while(this.panels.getCount() > 0){
35640              this.remove(this.panels.first());
35641         }
35642     },
35643
35644     /**
35645      * Removes the specified panel. If preservePanel is not true (either here or in the config), the panel is destroyed.
35646      * @param {Number/String/ContentPanel} panel The panel's index, id or the panel itself
35647      * @param {Boolean} preservePanel Overrides the config preservePanel option
35648      * @return {Roo.ContentPanel} The panel that was removed
35649      */
35650     remove : function(panel, preservePanel){
35651         panel = this.getPanel(panel);
35652         if(!panel){
35653             return null;
35654         }
35655         var e = {};
35656         this.fireEvent("beforeremove", this, panel, e);
35657         if(e.cancel === true){
35658             return null;
35659         }
35660         preservePanel = (typeof preservePanel != "undefined" ? preservePanel : (this.config.preservePanels === true || panel.preserve === true));
35661         var panelId = panel.getId();
35662         this.panels.removeKey(panelId);
35663         if(preservePanel){
35664             document.body.appendChild(panel.getEl().dom);
35665         }
35666         if(this.tabs){
35667             this.tabs.removeTab(panel.getEl().id);
35668         }else if (!preservePanel){
35669             this.bodyEl.dom.removeChild(panel.getEl().dom);
35670         }
35671         if(this.panels.getCount() == 1 && this.tabs && !this.config.alwaysShowTabs){
35672             var p = this.panels.first();
35673             var tempEl = document.createElement("div"); // temp holder to keep IE from deleting the node
35674             tempEl.appendChild(p.getEl().dom);
35675             this.bodyEl.update("");
35676             this.bodyEl.dom.appendChild(p.getEl().dom);
35677             tempEl = null;
35678             this.updateTitle(p.getTitle());
35679             this.tabs = null;
35680             this.bodyEl.setStyle("overflow", this.config.autoScroll ? "auto" : "hidden");
35681             this.setActivePanel(p);
35682         }
35683         panel.setRegion(null);
35684         if(this.activePanel == panel){
35685             this.activePanel = null;
35686         }
35687         if(this.config.autoDestroy !== false && preservePanel !== true){
35688             try{panel.destroy();}catch(e){}
35689         }
35690         this.fireEvent("panelremoved", this, panel);
35691         return panel;
35692     },
35693
35694     /**
35695      * Returns the TabPanel component used by this region
35696      * @return {Roo.TabPanel}
35697      */
35698     getTabs : function(){
35699         return this.tabs;
35700     },
35701
35702     createTool : function(parentEl, className){
35703         var btn = Roo.DomHelper.append(parentEl, {tag: "div", cls: "x-layout-tools-button",
35704             children: [{tag: "div", cls: "x-layout-tools-button-inner " + className, html: "&#160;"}]}, true);
35705         btn.addClassOnOver("x-layout-tools-button-over");
35706         return btn;
35707     }
35708 });/*
35709  * Based on:
35710  * Ext JS Library 1.1.1
35711  * Copyright(c) 2006-2007, Ext JS, LLC.
35712  *
35713  * Originally Released Under LGPL - original licence link has changed is not relivant.
35714  *
35715  * Fork - LGPL
35716  * <script type="text/javascript">
35717  */
35718  
35719
35720
35721 /**
35722  * @class Roo.SplitLayoutRegion
35723  * @extends Roo.LayoutRegion
35724  * Adds a splitbar and other (private) useful functionality to a {@link Roo.LayoutRegion}.
35725  */
35726 Roo.SplitLayoutRegion = function(mgr, config, pos, cursor){
35727     this.cursor = cursor;
35728     Roo.SplitLayoutRegion.superclass.constructor.call(this, mgr, config, pos);
35729 };
35730
35731 Roo.extend(Roo.SplitLayoutRegion, Roo.LayoutRegion, {
35732     splitTip : "Drag to resize.",
35733     collapsibleSplitTip : "Drag to resize. Double click to hide.",
35734     useSplitTips : false,
35735
35736     applyConfig : function(config){
35737         Roo.SplitLayoutRegion.superclass.applyConfig.call(this, config);
35738         if(config.split){
35739             if(!this.split){
35740                 var splitEl = Roo.DomHelper.append(this.mgr.el.dom, 
35741                         {tag: "div", id: this.el.id + "-split", cls: "x-layout-split x-layout-split-"+this.position, html: "&#160;"});
35742                 /** The SplitBar for this region 
35743                 * @type Roo.SplitBar */
35744                 this.split = new Roo.SplitBar(splitEl, this.el, this.orientation);
35745                 this.split.on("moved", this.onSplitMove, this);
35746                 this.split.useShim = config.useShim === true;
35747                 this.split.getMaximumSize = this[this.position == 'north' || this.position == 'south' ? 'getVMaxSize' : 'getHMaxSize'].createDelegate(this);
35748                 if(this.useSplitTips){
35749                     this.split.el.dom.title = config.collapsible ? this.collapsibleSplitTip : this.splitTip;
35750                 }
35751                 if(config.collapsible){
35752                     this.split.el.on("dblclick", this.collapse,  this);
35753                 }
35754             }
35755             if(typeof config.minSize != "undefined"){
35756                 this.split.minSize = config.minSize;
35757             }
35758             if(typeof config.maxSize != "undefined"){
35759                 this.split.maxSize = config.maxSize;
35760             }
35761             if(config.hideWhenEmpty || config.hidden || config.collapsed){
35762                 this.hideSplitter();
35763             }
35764         }
35765     },
35766
35767     getHMaxSize : function(){
35768          var cmax = this.config.maxSize || 10000;
35769          var center = this.mgr.getRegion("center");
35770          return Math.min(cmax, (this.el.getWidth()+center.getEl().getWidth())-center.getMinWidth());
35771     },
35772
35773     getVMaxSize : function(){
35774          var cmax = this.config.maxSize || 10000;
35775          var center = this.mgr.getRegion("center");
35776          return Math.min(cmax, (this.el.getHeight()+center.getEl().getHeight())-center.getMinHeight());
35777     },
35778
35779     onSplitMove : function(split, newSize){
35780         this.fireEvent("resized", this, newSize);
35781     },
35782     
35783     /** 
35784      * Returns the {@link Roo.SplitBar} for this region.
35785      * @return {Roo.SplitBar}
35786      */
35787     getSplitBar : function(){
35788         return this.split;
35789     },
35790     
35791     hide : function(){
35792         this.hideSplitter();
35793         Roo.SplitLayoutRegion.superclass.hide.call(this);
35794     },
35795
35796     hideSplitter : function(){
35797         if(this.split){
35798             this.split.el.setLocation(-2000,-2000);
35799             this.split.el.hide();
35800         }
35801     },
35802
35803     show : function(){
35804         if(this.split){
35805             this.split.el.show();
35806         }
35807         Roo.SplitLayoutRegion.superclass.show.call(this);
35808     },
35809     
35810     beforeSlide: function(){
35811         if(Roo.isGecko){// firefox overflow auto bug workaround
35812             this.bodyEl.clip();
35813             if(this.tabs) {
35814                 this.tabs.bodyEl.clip();
35815             }
35816             if(this.activePanel){
35817                 this.activePanel.getEl().clip();
35818                 
35819                 if(this.activePanel.beforeSlide){
35820                     this.activePanel.beforeSlide();
35821                 }
35822             }
35823         }
35824     },
35825     
35826     afterSlide : function(){
35827         if(Roo.isGecko){// firefox overflow auto bug workaround
35828             this.bodyEl.unclip();
35829             if(this.tabs) {
35830                 this.tabs.bodyEl.unclip();
35831             }
35832             if(this.activePanel){
35833                 this.activePanel.getEl().unclip();
35834                 if(this.activePanel.afterSlide){
35835                     this.activePanel.afterSlide();
35836                 }
35837             }
35838         }
35839     },
35840
35841     initAutoHide : function(){
35842         if(this.autoHide !== false){
35843             if(!this.autoHideHd){
35844                 var st = new Roo.util.DelayedTask(this.slideIn, this);
35845                 this.autoHideHd = {
35846                     "mouseout": function(e){
35847                         if(!e.within(this.el, true)){
35848                             st.delay(500);
35849                         }
35850                     },
35851                     "mouseover" : function(e){
35852                         st.cancel();
35853                     },
35854                     scope : this
35855                 };
35856             }
35857             this.el.on(this.autoHideHd);
35858         }
35859     },
35860
35861     clearAutoHide : function(){
35862         if(this.autoHide !== false){
35863             this.el.un("mouseout", this.autoHideHd.mouseout);
35864             this.el.un("mouseover", this.autoHideHd.mouseover);
35865         }
35866     },
35867
35868     clearMonitor : function(){
35869         Roo.get(document).un("click", this.slideInIf, this);
35870     },
35871
35872     // these names are backwards but not changed for compat
35873     slideOut : function(){
35874         if(this.isSlid || this.el.hasActiveFx()){
35875             return;
35876         }
35877         this.isSlid = true;
35878         if(this.collapseBtn){
35879             this.collapseBtn.hide();
35880         }
35881         this.closeBtnState = this.closeBtn.getStyle('display');
35882         this.closeBtn.hide();
35883         if(this.stickBtn){
35884             this.stickBtn.show();
35885         }
35886         this.el.show();
35887         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
35888         this.beforeSlide();
35889         this.el.setStyle("z-index", 10001);
35890         this.el.slideIn(this.getSlideAnchor(), {
35891             callback: function(){
35892                 this.afterSlide();
35893                 this.initAutoHide();
35894                 Roo.get(document).on("click", this.slideInIf, this);
35895                 this.fireEvent("slideshow", this);
35896             },
35897             scope: this,
35898             block: true
35899         });
35900     },
35901
35902     afterSlideIn : function(){
35903         this.clearAutoHide();
35904         this.isSlid = false;
35905         this.clearMonitor();
35906         this.el.setStyle("z-index", "");
35907         if(this.collapseBtn){
35908             this.collapseBtn.show();
35909         }
35910         this.closeBtn.setStyle('display', this.closeBtnState);
35911         if(this.stickBtn){
35912             this.stickBtn.hide();
35913         }
35914         this.fireEvent("slidehide", this);
35915     },
35916
35917     slideIn : function(cb){
35918         if(!this.isSlid || this.el.hasActiveFx()){
35919             Roo.callback(cb);
35920             return;
35921         }
35922         this.isSlid = false;
35923         this.beforeSlide();
35924         this.el.slideOut(this.getSlideAnchor(), {
35925             callback: function(){
35926                 this.el.setLeftTop(-10000, -10000);
35927                 this.afterSlide();
35928                 this.afterSlideIn();
35929                 Roo.callback(cb);
35930             },
35931             scope: this,
35932             block: true
35933         });
35934     },
35935     
35936     slideInIf : function(e){
35937         if(!e.within(this.el)){
35938             this.slideIn();
35939         }
35940     },
35941
35942     animateCollapse : function(){
35943         this.beforeSlide();
35944         this.el.setStyle("z-index", 20000);
35945         var anchor = this.getSlideAnchor();
35946         this.el.slideOut(anchor, {
35947             callback : function(){
35948                 this.el.setStyle("z-index", "");
35949                 this.collapsedEl.slideIn(anchor, {duration:.3});
35950                 this.afterSlide();
35951                 this.el.setLocation(-10000,-10000);
35952                 this.el.hide();
35953                 this.fireEvent("collapsed", this);
35954             },
35955             scope: this,
35956             block: true
35957         });
35958     },
35959
35960     animateExpand : function(){
35961         this.beforeSlide();
35962         this.el.alignTo(this.collapsedEl, this.getCollapseAnchor(), this.getExpandAdj());
35963         this.el.setStyle("z-index", 20000);
35964         this.collapsedEl.hide({
35965             duration:.1
35966         });
35967         this.el.slideIn(this.getSlideAnchor(), {
35968             callback : function(){
35969                 this.el.setStyle("z-index", "");
35970                 this.afterSlide();
35971                 if(this.split){
35972                     this.split.el.show();
35973                 }
35974                 this.fireEvent("invalidated", this);
35975                 this.fireEvent("expanded", this);
35976             },
35977             scope: this,
35978             block: true
35979         });
35980     },
35981
35982     anchors : {
35983         "west" : "left",
35984         "east" : "right",
35985         "north" : "top",
35986         "south" : "bottom"
35987     },
35988
35989     sanchors : {
35990         "west" : "l",
35991         "east" : "r",
35992         "north" : "t",
35993         "south" : "b"
35994     },
35995
35996     canchors : {
35997         "west" : "tl-tr",
35998         "east" : "tr-tl",
35999         "north" : "tl-bl",
36000         "south" : "bl-tl"
36001     },
36002
36003     getAnchor : function(){
36004         return this.anchors[this.position];
36005     },
36006
36007     getCollapseAnchor : function(){
36008         return this.canchors[this.position];
36009     },
36010
36011     getSlideAnchor : function(){
36012         return this.sanchors[this.position];
36013     },
36014
36015     getAlignAdj : function(){
36016         var cm = this.cmargins;
36017         switch(this.position){
36018             case "west":
36019                 return [0, 0];
36020             break;
36021             case "east":
36022                 return [0, 0];
36023             break;
36024             case "north":
36025                 return [0, 0];
36026             break;
36027             case "south":
36028                 return [0, 0];
36029             break;
36030         }
36031     },
36032
36033     getExpandAdj : function(){
36034         var c = this.collapsedEl, cm = this.cmargins;
36035         switch(this.position){
36036             case "west":
36037                 return [-(cm.right+c.getWidth()+cm.left), 0];
36038             break;
36039             case "east":
36040                 return [cm.right+c.getWidth()+cm.left, 0];
36041             break;
36042             case "north":
36043                 return [0, -(cm.top+cm.bottom+c.getHeight())];
36044             break;
36045             case "south":
36046                 return [0, cm.top+cm.bottom+c.getHeight()];
36047             break;
36048         }
36049     }
36050 });/*
36051  * Based on:
36052  * Ext JS Library 1.1.1
36053  * Copyright(c) 2006-2007, Ext JS, LLC.
36054  *
36055  * Originally Released Under LGPL - original licence link has changed is not relivant.
36056  *
36057  * Fork - LGPL
36058  * <script type="text/javascript">
36059  */
36060 /*
36061  * These classes are private internal classes
36062  */
36063 Roo.CenterLayoutRegion = function(mgr, config){
36064     Roo.LayoutRegion.call(this, mgr, config, "center");
36065     this.visible = true;
36066     this.minWidth = config.minWidth || 20;
36067     this.minHeight = config.minHeight || 20;
36068 };
36069
36070 Roo.extend(Roo.CenterLayoutRegion, Roo.LayoutRegion, {
36071     hide : function(){
36072         // center panel can't be hidden
36073     },
36074     
36075     show : function(){
36076         // center panel can't be hidden
36077     },
36078     
36079     getMinWidth: function(){
36080         return this.minWidth;
36081     },
36082     
36083     getMinHeight: function(){
36084         return this.minHeight;
36085     }
36086 });
36087
36088
36089 Roo.NorthLayoutRegion = function(mgr, config){
36090     Roo.LayoutRegion.call(this, mgr, config, "north", "n-resize");
36091     if(this.split){
36092         this.split.placement = Roo.SplitBar.TOP;
36093         this.split.orientation = Roo.SplitBar.VERTICAL;
36094         this.split.el.addClass("x-layout-split-v");
36095     }
36096     var size = config.initialSize || config.height;
36097     if(typeof size != "undefined"){
36098         this.el.setHeight(size);
36099     }
36100 };
36101 Roo.extend(Roo.NorthLayoutRegion, Roo.SplitLayoutRegion, {
36102     orientation: Roo.SplitBar.VERTICAL,
36103     getBox : function(){
36104         if(this.collapsed){
36105             return this.collapsedEl.getBox();
36106         }
36107         var box = this.el.getBox();
36108         if(this.split){
36109             box.height += this.split.el.getHeight();
36110         }
36111         return box;
36112     },
36113     
36114     updateBox : function(box){
36115         if(this.split && !this.collapsed){
36116             box.height -= this.split.el.getHeight();
36117             this.split.el.setLeft(box.x);
36118             this.split.el.setTop(box.y+box.height);
36119             this.split.el.setWidth(box.width);
36120         }
36121         if(this.collapsed){
36122             this.updateBody(box.width, null);
36123         }
36124         Roo.LayoutRegion.prototype.updateBox.call(this, box);
36125     }
36126 });
36127
36128 Roo.SouthLayoutRegion = function(mgr, config){
36129     Roo.SplitLayoutRegion.call(this, mgr, config, "south", "s-resize");
36130     if(this.split){
36131         this.split.placement = Roo.SplitBar.BOTTOM;
36132         this.split.orientation = Roo.SplitBar.VERTICAL;
36133         this.split.el.addClass("x-layout-split-v");
36134     }
36135     var size = config.initialSize || config.height;
36136     if(typeof size != "undefined"){
36137         this.el.setHeight(size);
36138     }
36139 };
36140 Roo.extend(Roo.SouthLayoutRegion, Roo.SplitLayoutRegion, {
36141     orientation: Roo.SplitBar.VERTICAL,
36142     getBox : function(){
36143         if(this.collapsed){
36144             return this.collapsedEl.getBox();
36145         }
36146         var box = this.el.getBox();
36147         if(this.split){
36148             var sh = this.split.el.getHeight();
36149             box.height += sh;
36150             box.y -= sh;
36151         }
36152         return box;
36153     },
36154     
36155     updateBox : function(box){
36156         if(this.split && !this.collapsed){
36157             var sh = this.split.el.getHeight();
36158             box.height -= sh;
36159             box.y += sh;
36160             this.split.el.setLeft(box.x);
36161             this.split.el.setTop(box.y-sh);
36162             this.split.el.setWidth(box.width);
36163         }
36164         if(this.collapsed){
36165             this.updateBody(box.width, null);
36166         }
36167         Roo.LayoutRegion.prototype.updateBox.call(this, box);
36168     }
36169 });
36170
36171 Roo.EastLayoutRegion = function(mgr, config){
36172     Roo.SplitLayoutRegion.call(this, mgr, config, "east", "e-resize");
36173     if(this.split){
36174         this.split.placement = Roo.SplitBar.RIGHT;
36175         this.split.orientation = Roo.SplitBar.HORIZONTAL;
36176         this.split.el.addClass("x-layout-split-h");
36177     }
36178     var size = config.initialSize || config.width;
36179     if(typeof size != "undefined"){
36180         this.el.setWidth(size);
36181     }
36182 };
36183 Roo.extend(Roo.EastLayoutRegion, Roo.SplitLayoutRegion, {
36184     orientation: Roo.SplitBar.HORIZONTAL,
36185     getBox : function(){
36186         if(this.collapsed){
36187             return this.collapsedEl.getBox();
36188         }
36189         var box = this.el.getBox();
36190         if(this.split){
36191             var sw = this.split.el.getWidth();
36192             box.width += sw;
36193             box.x -= sw;
36194         }
36195         return box;
36196     },
36197
36198     updateBox : function(box){
36199         if(this.split && !this.collapsed){
36200             var sw = this.split.el.getWidth();
36201             box.width -= sw;
36202             this.split.el.setLeft(box.x);
36203             this.split.el.setTop(box.y);
36204             this.split.el.setHeight(box.height);
36205             box.x += sw;
36206         }
36207         if(this.collapsed){
36208             this.updateBody(null, box.height);
36209         }
36210         Roo.LayoutRegion.prototype.updateBox.call(this, box);
36211     }
36212 });
36213
36214 Roo.WestLayoutRegion = function(mgr, config){
36215     Roo.SplitLayoutRegion.call(this, mgr, config, "west", "w-resize");
36216     if(this.split){
36217         this.split.placement = Roo.SplitBar.LEFT;
36218         this.split.orientation = Roo.SplitBar.HORIZONTAL;
36219         this.split.el.addClass("x-layout-split-h");
36220     }
36221     var size = config.initialSize || config.width;
36222     if(typeof size != "undefined"){
36223         this.el.setWidth(size);
36224     }
36225 };
36226 Roo.extend(Roo.WestLayoutRegion, Roo.SplitLayoutRegion, {
36227     orientation: Roo.SplitBar.HORIZONTAL,
36228     getBox : function(){
36229         if(this.collapsed){
36230             return this.collapsedEl.getBox();
36231         }
36232         var box = this.el.getBox();
36233         if(this.split){
36234             box.width += this.split.el.getWidth();
36235         }
36236         return box;
36237     },
36238     
36239     updateBox : function(box){
36240         if(this.split && !this.collapsed){
36241             var sw = this.split.el.getWidth();
36242             box.width -= sw;
36243             this.split.el.setLeft(box.x+box.width);
36244             this.split.el.setTop(box.y);
36245             this.split.el.setHeight(box.height);
36246         }
36247         if(this.collapsed){
36248             this.updateBody(null, box.height);
36249         }
36250         Roo.LayoutRegion.prototype.updateBox.call(this, box);
36251     }
36252 });
36253 /*
36254  * Based on:
36255  * Ext JS Library 1.1.1
36256  * Copyright(c) 2006-2007, Ext JS, LLC.
36257  *
36258  * Originally Released Under LGPL - original licence link has changed is not relivant.
36259  *
36260  * Fork - LGPL
36261  * <script type="text/javascript">
36262  */
36263  
36264  
36265 /*
36266  * Private internal class for reading and applying state
36267  */
36268 Roo.LayoutStateManager = function(layout){
36269      // default empty state
36270      this.state = {
36271         north: {},
36272         south: {},
36273         east: {},
36274         west: {}       
36275     };
36276 };
36277
36278 Roo.LayoutStateManager.prototype = {
36279     init : function(layout, provider){
36280         this.provider = provider;
36281         var state = provider.get(layout.id+"-layout-state");
36282         if(state){
36283             var wasUpdating = layout.isUpdating();
36284             if(!wasUpdating){
36285                 layout.beginUpdate();
36286             }
36287             for(var key in state){
36288                 if(typeof state[key] != "function"){
36289                     var rstate = state[key];
36290                     var r = layout.getRegion(key);
36291                     if(r && rstate){
36292                         if(rstate.size){
36293                             r.resizeTo(rstate.size);
36294                         }
36295                         if(rstate.collapsed == true){
36296                             r.collapse(true);
36297                         }else{
36298                             r.expand(null, true);
36299                         }
36300                     }
36301                 }
36302             }
36303             if(!wasUpdating){
36304                 layout.endUpdate();
36305             }
36306             this.state = state; 
36307         }
36308         this.layout = layout;
36309         layout.on("regionresized", this.onRegionResized, this);
36310         layout.on("regioncollapsed", this.onRegionCollapsed, this);
36311         layout.on("regionexpanded", this.onRegionExpanded, this);
36312     },
36313     
36314     storeState : function(){
36315         this.provider.set(this.layout.id+"-layout-state", this.state);
36316     },
36317     
36318     onRegionResized : function(region, newSize){
36319         this.state[region.getPosition()].size = newSize;
36320         this.storeState();
36321     },
36322     
36323     onRegionCollapsed : function(region){
36324         this.state[region.getPosition()].collapsed = true;
36325         this.storeState();
36326     },
36327     
36328     onRegionExpanded : function(region){
36329         this.state[region.getPosition()].collapsed = false;
36330         this.storeState();
36331     }
36332 };/*
36333  * Based on:
36334  * Ext JS Library 1.1.1
36335  * Copyright(c) 2006-2007, Ext JS, LLC.
36336  *
36337  * Originally Released Under LGPL - original licence link has changed is not relivant.
36338  *
36339  * Fork - LGPL
36340  * <script type="text/javascript">
36341  */
36342 /**
36343  * @class Roo.ContentPanel
36344  * @extends Roo.util.Observable
36345  * @children Roo.form.Form Roo.JsonView Roo.View
36346  * @parent Roo.BorderLayout Roo.LayoutDialog builder
36347  * A basic ContentPanel element.
36348  * @cfg {Boolean}   fitToFrame    True for this panel to adjust its size to fit when the region resizes  (defaults to false)
36349  * @cfg {Boolean}   fitContainer   When using {@link #fitToFrame} and {@link #resizeEl}, you can also fit the parent container  (defaults to false)
36350  * @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
36351  * @cfg {Boolean}   closable      True if the panel can be closed/removed
36352  * @cfg {Boolean}   background    True if the panel should not be activated when it is added (defaults to false)
36353  * @cfg {String|HTMLElement|Element} resizeEl An element to resize if {@link #fitToFrame} is true (instead of this panel's element)
36354  * @cfg {Roo.Toolbar}   toolbar       A toolbar for this panel
36355  * @cfg {Boolean} autoScroll    True to scroll overflow in this panel (use with {@link #fitToFrame})
36356  * @cfg {String} title          The title for this panel
36357  * @cfg {Array} adjustments     Values to <b>add</b> to the width/height when doing a {@link #fitToFrame} (default is [0, 0])
36358  * @cfg {String} url            Calls {@link #setUrl} with this value
36359  * @cfg {String} region (center|north|south|east|west) [required] which region to put this panel on (when used with xtype constructors)
36360  * @cfg {String|Object} params  When used with {@link #url}, calls {@link #setUrl} with this value
36361  * @cfg {Boolean} loadOnce      When used with {@link #url}, calls {@link #setUrl} with this value
36362  * @cfg {String}    content        Raw content to fill content panel with (uses setContent on construction.)
36363  * @cfg {String}    style  Extra style to add to the content panel
36364  * @cfg {Roo.menu.Menu} menu  popup menu
36365
36366  * @constructor
36367  * Create a new ContentPanel.
36368  * @param {String/HTMLElement/Roo.Element} el The container element for this panel
36369  * @param {String/Object} config A string to set only the title or a config object
36370  * @param {String} content (optional) Set the HTML content for this panel
36371  * @param {String} region (optional) Used by xtype constructors to add to regions. (values center,east,west,south,north)
36372  */
36373 Roo.ContentPanel = function(el, config, content){
36374     
36375     /*
36376     if(el.autoCreate || el.xtype){ // xtype is available if this is called from factory
36377         config = el;
36378         el = Roo.id();
36379     }
36380     if (config && config.parentLayout) { 
36381         el = config.parentLayout.el.createChild(); 
36382     }
36383     */
36384     if(el.autoCreate){ // xtype is available if this is called from factory
36385         config = el;
36386         el = Roo.id();
36387     }
36388     this.el = Roo.get(el);
36389     if(!this.el && config && config.autoCreate){
36390         if(typeof config.autoCreate == "object"){
36391             if(!config.autoCreate.id){
36392                 config.autoCreate.id = config.id||el;
36393             }
36394             this.el = Roo.DomHelper.append(document.body,
36395                         config.autoCreate, true);
36396         }else{
36397             this.el = Roo.DomHelper.append(document.body,
36398                         {tag: "div", cls: "x-layout-inactive-content", id: config.id||el}, true);
36399         }
36400     }
36401     
36402     
36403     this.closable = false;
36404     this.loaded = false;
36405     this.active = false;
36406     if(typeof config == "string"){
36407         this.title = config;
36408     }else{
36409         Roo.apply(this, config);
36410     }
36411     
36412     if (this.toolbar && !this.toolbar.el && this.toolbar.xtype) {
36413         this.wrapEl = this.el.wrap();
36414         this.toolbar.container = this.el.insertSibling(false, 'before');
36415         this.toolbar = new Roo.Toolbar(this.toolbar);
36416     }
36417     
36418     // xtype created footer. - not sure if will work as we normally have to render first..
36419     if (this.footer && !this.footer.el && this.footer.xtype) {
36420         if (!this.wrapEl) {
36421             this.wrapEl = this.el.wrap();
36422         }
36423     
36424         this.footer.container = this.wrapEl.createChild();
36425          
36426         this.footer = Roo.factory(this.footer, Roo);
36427         
36428     }
36429     
36430     if(this.resizeEl){
36431         this.resizeEl = Roo.get(this.resizeEl, true);
36432     }else{
36433         this.resizeEl = this.el;
36434     }
36435     // handle view.xtype
36436     
36437  
36438     
36439     
36440     this.addEvents({
36441         /**
36442          * @event activate
36443          * Fires when this panel is activated. 
36444          * @param {Roo.ContentPanel} this
36445          */
36446         "activate" : true,
36447         /**
36448          * @event deactivate
36449          * Fires when this panel is activated. 
36450          * @param {Roo.ContentPanel} this
36451          */
36452         "deactivate" : true,
36453
36454         /**
36455          * @event resize
36456          * Fires when this panel is resized if fitToFrame is true.
36457          * @param {Roo.ContentPanel} this
36458          * @param {Number} width The width after any component adjustments
36459          * @param {Number} height The height after any component adjustments
36460          */
36461         "resize" : true,
36462         
36463          /**
36464          * @event render
36465          * Fires when this tab is created
36466          * @param {Roo.ContentPanel} this
36467          */
36468         "render" : true
36469          
36470         
36471     });
36472     
36473
36474     
36475     
36476     if(this.autoScroll){
36477         this.resizeEl.setStyle("overflow", "auto");
36478     } else {
36479         // fix randome scrolling
36480         this.el.on('scroll', function() {
36481             Roo.log('fix random scolling');
36482             this.scrollTo('top',0); 
36483         });
36484     }
36485     content = content || this.content;
36486     if(content){
36487         this.setContent(content);
36488     }
36489     if(config && config.url){
36490         this.setUrl(this.url, this.params, this.loadOnce);
36491     }
36492     
36493     
36494     
36495     Roo.ContentPanel.superclass.constructor.call(this);
36496     
36497     if (this.view && typeof(this.view.xtype) != 'undefined') {
36498         this.view.el = this.el.appendChild(document.createElement("div"));
36499         this.view = Roo.factory(this.view); 
36500         this.view.render  &&  this.view.render(false, '');  
36501     }
36502     
36503     
36504     this.fireEvent('render', this);
36505 };
36506
36507 Roo.extend(Roo.ContentPanel, Roo.util.Observable, {
36508     tabTip:'',
36509     setRegion : function(region){
36510         this.region = region;
36511         if(region){
36512            this.el.replaceClass("x-layout-inactive-content", "x-layout-active-content");
36513         }else{
36514            this.el.replaceClass("x-layout-active-content", "x-layout-inactive-content");
36515         } 
36516     },
36517     
36518     /**
36519      * Returns the toolbar for this Panel if one was configured. 
36520      * @return {Roo.Toolbar} 
36521      */
36522     getToolbar : function(){
36523         return this.toolbar;
36524     },
36525     
36526     setActiveState : function(active){
36527         this.active = active;
36528         if(!active){
36529             this.fireEvent("deactivate", this);
36530         }else{
36531             this.fireEvent("activate", this);
36532         }
36533     },
36534     /**
36535      * Updates this panel's element
36536      * @param {String} content The new content
36537      * @param {Boolean} loadScripts (optional) true to look for and process scripts
36538     */
36539     setContent : function(content, loadScripts){
36540         this.el.update(content, loadScripts);
36541     },
36542
36543     ignoreResize : function(w, h){
36544         if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
36545             return true;
36546         }else{
36547             this.lastSize = {width: w, height: h};
36548             return false;
36549         }
36550     },
36551     /**
36552      * Get the {@link Roo.UpdateManager} for this panel. Enables you to perform Ajax updates.
36553      * @return {Roo.UpdateManager} The UpdateManager
36554      */
36555     getUpdateManager : function(){
36556         return this.el.getUpdateManager();
36557     },
36558      /**
36559      * Loads this content panel immediately with content from XHR. Note: to delay loading until the panel is activated, use {@link #setUrl}.
36560      * @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:
36561 <pre><code>
36562 panel.load({
36563     url: "your-url.php",
36564     params: {param1: "foo", param2: "bar"}, // or a URL encoded string
36565     callback: yourFunction,
36566     scope: yourObject, //(optional scope)
36567     discardUrl: false,
36568     nocache: false,
36569     text: "Loading...",
36570     timeout: 30,
36571     scripts: false
36572 });
36573 </code></pre>
36574      * The only required property is <i>url</i>. The optional properties <i>nocache</i>, <i>text</i> and <i>scripts</i>
36575      * 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.
36576      * @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}
36577      * @param {Function} callback (optional) Callback when transaction is complete -- called with signature (oElement, bSuccess, oResponse)
36578      * @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.
36579      * @return {Roo.ContentPanel} this
36580      */
36581     load : function(){
36582         var um = this.el.getUpdateManager();
36583         um.update.apply(um, arguments);
36584         return this;
36585     },
36586
36587
36588     /**
36589      * 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.
36590      * @param {String/Function} url The URL to load the content from or a function to call to get the URL
36591      * @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)
36592      * @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)
36593      * @return {Roo.UpdateManager} The UpdateManager
36594      */
36595     setUrl : function(url, params, loadOnce){
36596         if(this.refreshDelegate){
36597             this.removeListener("activate", this.refreshDelegate);
36598         }
36599         this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
36600         this.on("activate", this.refreshDelegate);
36601         return this.el.getUpdateManager();
36602     },
36603     
36604     _handleRefresh : function(url, params, loadOnce){
36605         if(!loadOnce || !this.loaded){
36606             var updater = this.el.getUpdateManager();
36607             updater.update(url, params, this._setLoaded.createDelegate(this));
36608         }
36609     },
36610     
36611     _setLoaded : function(){
36612         this.loaded = true;
36613     }, 
36614     
36615     /**
36616      * Returns this panel's id
36617      * @return {String} 
36618      */
36619     getId : function(){
36620         return this.el.id;
36621     },
36622     
36623     /** 
36624      * Returns this panel's element - used by regiosn to add.
36625      * @return {Roo.Element} 
36626      */
36627     getEl : function(){
36628         return this.wrapEl || this.el;
36629     },
36630     
36631     adjustForComponents : function(width, height)
36632     {
36633         //Roo.log('adjustForComponents ');
36634         if(this.resizeEl != this.el){
36635             width -= this.el.getFrameWidth('lr');
36636             height -= this.el.getFrameWidth('tb');
36637         }
36638         if(this.toolbar){
36639             var te = this.toolbar.getEl();
36640             height -= te.getHeight();
36641             te.setWidth(width);
36642         }
36643         if(this.footer){
36644             var te = this.footer.getEl();
36645             //Roo.log("footer:" + te.getHeight());
36646             
36647             height -= te.getHeight();
36648             te.setWidth(width);
36649         }
36650         
36651         
36652         if(this.adjustments){
36653             width += this.adjustments[0];
36654             height += this.adjustments[1];
36655         }
36656         return {"width": width, "height": height};
36657     },
36658     
36659     setSize : function(width, height){
36660         if(this.fitToFrame && !this.ignoreResize(width, height)){
36661             if(this.fitContainer && this.resizeEl != this.el){
36662                 this.el.setSize(width, height);
36663             }
36664             var size = this.adjustForComponents(width, height);
36665             this.resizeEl.setSize(this.autoWidth ? "auto" : size.width, this.autoHeight ? "auto" : size.height);
36666             this.fireEvent('resize', this, size.width, size.height);
36667         }
36668     },
36669     
36670     /**
36671      * Returns this panel's title
36672      * @return {String} 
36673      */
36674     getTitle : function(){
36675         return this.title;
36676     },
36677     
36678     /**
36679      * Set this panel's title
36680      * @param {String} title
36681      */
36682     setTitle : function(title){
36683         this.title = title;
36684         if(this.region){
36685             this.region.updatePanelTitle(this, title);
36686         }
36687     },
36688     
36689     /**
36690      * Returns true is this panel was configured to be closable
36691      * @return {Boolean} 
36692      */
36693     isClosable : function(){
36694         return this.closable;
36695     },
36696     
36697     beforeSlide : function(){
36698         this.el.clip();
36699         this.resizeEl.clip();
36700     },
36701     
36702     afterSlide : function(){
36703         this.el.unclip();
36704         this.resizeEl.unclip();
36705     },
36706     
36707     /**
36708      *   Force a content refresh from the URL specified in the {@link #setUrl} method.
36709      *   Will fail silently if the {@link #setUrl} method has not been called.
36710      *   This does not activate the panel, just updates its content.
36711      */
36712     refresh : function(){
36713         if(this.refreshDelegate){
36714            this.loaded = false;
36715            this.refreshDelegate();
36716         }
36717     },
36718     
36719     /**
36720      * Destroys this panel
36721      */
36722     destroy : function(){
36723         this.el.removeAllListeners();
36724         var tempEl = document.createElement("span");
36725         tempEl.appendChild(this.el.dom);
36726         tempEl.innerHTML = "";
36727         this.el.remove();
36728         this.el = null;
36729     },
36730     
36731     /**
36732      * form - if the content panel contains a form - this is a reference to it.
36733      * @type {Roo.form.Form}
36734      */
36735     form : false,
36736     /**
36737      * view - if the content panel contains a view (Roo.DatePicker / Roo.View / Roo.JsonView)
36738      *    This contains a reference to it.
36739      * @type {Roo.View}
36740      */
36741     view : false,
36742     
36743       /**
36744      * Adds a xtype elements to the panel - currently only supports Forms, View, JsonView.
36745      * <pre><code>
36746
36747 layout.addxtype({
36748        xtype : 'Form',
36749        items: [ .... ]
36750    }
36751 );
36752
36753 </code></pre>
36754      * @param {Object} cfg Xtype definition of item to add.
36755      */
36756     
36757     addxtype : function(cfg) {
36758         if(cfg.xtype.match(/^UploadCropbox$/)) {
36759
36760             this.cropbox = new Roo.factory(cfg);
36761
36762             this.cropbox.render(this.el);
36763
36764             return this.cropbox;
36765         }
36766         // add form..
36767         if (cfg.xtype.match(/^Form$/)) {
36768             
36769             var el;
36770             //if (this.footer) {
36771             //    el = this.footer.container.insertSibling(false, 'before');
36772             //} else {
36773                 el = this.el.createChild();
36774             //}
36775
36776             this.form = new  Roo.form.Form(cfg);
36777             
36778             
36779             if ( this.form.allItems.length) {
36780                 this.form.render(el.dom);
36781             }
36782             return this.form;
36783         }
36784         // should only have one of theses..
36785         if ([ 'View', 'JsonView', 'DatePicker'].indexOf(cfg.xtype) > -1) {
36786             // views.. should not be just added - used named prop 'view''
36787             
36788             cfg.el = this.el.appendChild(document.createElement("div"));
36789             // factory?
36790             
36791             var ret = new Roo.factory(cfg);
36792              
36793              ret.render && ret.render(false, ''); // render blank..
36794             this.view = ret;
36795             return ret;
36796         }
36797         return false;
36798     }
36799 });
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812 /**
36813  * @class Roo.GridPanel
36814  * @extends Roo.ContentPanel
36815  * @parent Roo.BorderLayout Roo.LayoutDialog builder
36816  * @constructor
36817  * Create a new GridPanel.
36818  * @cfg {Roo.grid.Grid} grid The grid for this panel
36819  */
36820 Roo.GridPanel = function(grid, config){
36821     
36822     // universal ctor...
36823     if (typeof(grid.grid) != 'undefined') {
36824         config = grid;
36825         grid = config.grid;
36826     }
36827     this.wrapper = Roo.DomHelper.append(document.body, // wrapper for IE7 strict & safari scroll issue
36828         {tag: "div", cls: "x-layout-grid-wrapper x-layout-inactive-content"}, true);
36829         
36830     this.wrapper.dom.appendChild(grid.getGridEl().dom);
36831     
36832     Roo.GridPanel.superclass.constructor.call(this, this.wrapper, config);
36833     
36834     if(this.toolbar){
36835         this.toolbar.el.insertBefore(this.wrapper.dom.firstChild);
36836     }
36837     // xtype created footer. - not sure if will work as we normally have to render first..
36838     if (this.footer && !this.footer.el && this.footer.xtype) {
36839         
36840         this.footer.container = this.grid.getView().getFooterPanel(true);
36841         this.footer.dataSource = this.grid.dataSource;
36842         this.footer = Roo.factory(this.footer, Roo);
36843         
36844     }
36845     
36846     grid.monitorWindowResize = false; // turn off autosizing
36847     grid.autoHeight = false;
36848     grid.autoWidth = false;
36849     this.grid = grid;
36850     this.grid.getGridEl().replaceClass("x-layout-inactive-content", "x-layout-component-panel");
36851 };
36852
36853 Roo.extend(Roo.GridPanel, Roo.ContentPanel, {
36854     getId : function(){
36855         return this.grid.id;
36856     },
36857     
36858     /**
36859      * Returns the grid for this panel
36860      * @return {Roo.grid.Grid} 
36861      */
36862     getGrid : function(){
36863         return this.grid;    
36864     },
36865     
36866     setSize : function(width, height){
36867         if(!this.ignoreResize(width, height)){
36868             var grid = this.grid;
36869             var size = this.adjustForComponents(width, height);
36870             grid.getGridEl().setSize(size.width, size.height);
36871             grid.autoSize();
36872         }
36873     },
36874     
36875     beforeSlide : function(){
36876         this.grid.getView().scroller.clip();
36877     },
36878     
36879     afterSlide : function(){
36880         this.grid.getView().scroller.unclip();
36881     },
36882     
36883     destroy : function(){
36884         this.grid.destroy();
36885         delete this.grid;
36886         Roo.GridPanel.superclass.destroy.call(this); 
36887     }
36888 });
36889
36890
36891 /**
36892  * @class Roo.NestedLayoutPanel
36893  * @extends Roo.ContentPanel
36894  * @parent Roo.BorderLayout Roo.LayoutDialog builder
36895  * @cfg {Roo.BorderLayout} layout   [required] The layout for this panel
36896  *
36897  * 
36898  * @constructor
36899  * Create a new NestedLayoutPanel.
36900  * 
36901  * 
36902  * @param {Roo.BorderLayout} layout [required] The layout for this panel
36903  * @param {String/Object} config A string to set only the title or a config object
36904  */
36905 Roo.NestedLayoutPanel = function(layout, config)
36906 {
36907     // construct with only one argument..
36908     /* FIXME - implement nicer consturctors
36909     if (layout.layout) {
36910         config = layout;
36911         layout = config.layout;
36912         delete config.layout;
36913     }
36914     if (layout.xtype && !layout.getEl) {
36915         // then layout needs constructing..
36916         layout = Roo.factory(layout, Roo);
36917     }
36918     */
36919     
36920     
36921     Roo.NestedLayoutPanel.superclass.constructor.call(this, layout.getEl(), config);
36922     
36923     layout.monitorWindowResize = false; // turn off autosizing
36924     this.layout = layout;
36925     this.layout.getEl().addClass("x-layout-nested-layout");
36926     
36927     
36928     
36929     
36930 };
36931
36932 Roo.extend(Roo.NestedLayoutPanel, Roo.ContentPanel, {
36933
36934     layout : false,
36935
36936     setSize : function(width, height){
36937         if(!this.ignoreResize(width, height)){
36938             var size = this.adjustForComponents(width, height);
36939             var el = this.layout.getEl();
36940             el.setSize(size.width, size.height);
36941             var touch = el.dom.offsetWidth;
36942             this.layout.layout();
36943             // ie requires a double layout on the first pass
36944             if(Roo.isIE && !this.initialized){
36945                 this.initialized = true;
36946                 this.layout.layout();
36947             }
36948         }
36949     },
36950     
36951     // activate all subpanels if not currently active..
36952     
36953     setActiveState : function(active){
36954         this.active = active;
36955         if(!active){
36956             this.fireEvent("deactivate", this);
36957             return;
36958         }
36959         
36960         this.fireEvent("activate", this);
36961         // not sure if this should happen before or after..
36962         if (!this.layout) {
36963             return; // should not happen..
36964         }
36965         var reg = false;
36966         for (var r in this.layout.regions) {
36967             reg = this.layout.getRegion(r);
36968             if (reg.getActivePanel()) {
36969                 //reg.showPanel(reg.getActivePanel()); // force it to activate.. 
36970                 reg.setActivePanel(reg.getActivePanel());
36971                 continue;
36972             }
36973             if (!reg.panels.length) {
36974                 continue;
36975             }
36976             reg.showPanel(reg.getPanel(0));
36977         }
36978         
36979         
36980         
36981         
36982     },
36983     
36984     /**
36985      * Returns the nested BorderLayout for this panel
36986      * @return {Roo.BorderLayout}
36987      */
36988     getLayout : function(){
36989         return this.layout;
36990     },
36991     
36992      /**
36993      * Adds a xtype elements to the layout of the nested panel
36994      * <pre><code>
36995
36996 panel.addxtype({
36997        xtype : 'ContentPanel',
36998        region: 'west',
36999        items: [ .... ]
37000    }
37001 );
37002
37003 panel.addxtype({
37004         xtype : 'NestedLayoutPanel',
37005         region: 'west',
37006         layout: {
37007            center: { },
37008            west: { }   
37009         },
37010         items : [ ... list of content panels or nested layout panels.. ]
37011    }
37012 );
37013 </code></pre>
37014      * @param {Object} cfg Xtype definition of item to add.
37015      */
37016     addxtype : function(cfg) {
37017         return this.layout.addxtype(cfg);
37018     
37019     }
37020 });
37021
37022 Roo.ScrollPanel = function(el, config, content){
37023     config = config || {};
37024     config.fitToFrame = true;
37025     Roo.ScrollPanel.superclass.constructor.call(this, el, config, content);
37026     
37027     this.el.dom.style.overflow = "hidden";
37028     var wrap = this.el.wrap({cls: "x-scroller x-layout-inactive-content"});
37029     this.el.removeClass("x-layout-inactive-content");
37030     this.el.on("mousewheel", this.onWheel, this);
37031
37032     var up = wrap.createChild({cls: "x-scroller-up", html: "&#160;"}, this.el.dom);
37033     var down = wrap.createChild({cls: "x-scroller-down", html: "&#160;"});
37034     up.unselectable(); down.unselectable();
37035     up.on("click", this.scrollUp, this);
37036     down.on("click", this.scrollDown, this);
37037     up.addClassOnOver("x-scroller-btn-over");
37038     down.addClassOnOver("x-scroller-btn-over");
37039     up.addClassOnClick("x-scroller-btn-click");
37040     down.addClassOnClick("x-scroller-btn-click");
37041     this.adjustments = [0, -(up.getHeight() + down.getHeight())];
37042
37043     this.resizeEl = this.el;
37044     this.el = wrap; this.up = up; this.down = down;
37045 };
37046
37047 Roo.extend(Roo.ScrollPanel, Roo.ContentPanel, {
37048     increment : 100,
37049     wheelIncrement : 5,
37050     scrollUp : function(){
37051         this.resizeEl.scroll("up", this.increment, {callback: this.afterScroll, scope: this});
37052     },
37053
37054     scrollDown : function(){
37055         this.resizeEl.scroll("down", this.increment, {callback: this.afterScroll, scope: this});
37056     },
37057
37058     afterScroll : function(){
37059         var el = this.resizeEl;
37060         var t = el.dom.scrollTop, h = el.dom.scrollHeight, ch = el.dom.clientHeight;
37061         this.up[t == 0 ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
37062         this.down[h - t <= ch ? "addClass" : "removeClass"]("x-scroller-btn-disabled");
37063     },
37064
37065     setSize : function(){
37066         Roo.ScrollPanel.superclass.setSize.apply(this, arguments);
37067         this.afterScroll();
37068     },
37069
37070     onWheel : function(e){
37071         var d = e.getWheelDelta();
37072         this.resizeEl.dom.scrollTop -= (d*this.wheelIncrement);
37073         this.afterScroll();
37074         e.stopEvent();
37075     },
37076
37077     setContent : function(content, loadScripts){
37078         this.resizeEl.update(content, loadScripts);
37079     }
37080
37081 });
37082
37083
37084
37085 /**
37086  * @class Roo.TreePanel
37087  * @extends Roo.ContentPanel
37088  * @parent Roo.BorderLayout Roo.LayoutDialog builder
37089  * Treepanel component
37090  * 
37091  * @constructor
37092  * Create a new TreePanel. - defaults to fit/scoll contents.
37093  * @param {String/Object} config A string to set only the panel's title, or a config object
37094  */
37095 Roo.TreePanel = function(config){
37096     var el = config.el;
37097     var tree = config.tree;
37098     delete config.tree; 
37099     delete config.el; // hopefull!
37100     
37101     // wrapper for IE7 strict & safari scroll issue
37102     
37103     var treeEl = el.createChild();
37104     config.resizeEl = treeEl;
37105     
37106     
37107     
37108     Roo.TreePanel.superclass.constructor.call(this, el, config);
37109  
37110  
37111     this.tree = new Roo.tree.TreePanel(treeEl , tree);
37112     //console.log(tree);
37113     this.on('activate', function()
37114     {
37115         if (this.tree.rendered) {
37116             return;
37117         }
37118         //console.log('render tree');
37119         this.tree.render();
37120     });
37121     // this should not be needed.. - it's actually the 'el' that resizes?
37122     // actuall it breaks the containerScroll - dragging nodes auto scroll at top
37123     
37124     //this.on('resize',  function (cp, w, h) {
37125     //        this.tree.innerCt.setWidth(w);
37126     //        this.tree.innerCt.setHeight(h);
37127     //        //this.tree.innerCt.setStyle('overflow-y', 'auto');
37128     //});
37129
37130         
37131     
37132 };
37133
37134 Roo.extend(Roo.TreePanel, Roo.ContentPanel, {   
37135     fitToFrame : true,
37136     autoScroll : true,
37137     /*
37138      * @cfg {Roo.tree.TreePanel} tree [required] The tree TreePanel, with config etc.
37139      */
37140     tree : false
37141
37142 });
37143 /*
37144  * Based on:
37145  * Ext JS Library 1.1.1
37146  * Copyright(c) 2006-2007, Ext JS, LLC.
37147  *
37148  * Originally Released Under LGPL - original licence link has changed is not relivant.
37149  *
37150  * Fork - LGPL
37151  * <script type="text/javascript">
37152  */
37153  
37154
37155 /**
37156  * @class Roo.ReaderLayout
37157  * @extends Roo.BorderLayout
37158  * This is a pre-built layout that represents a classic, 5-pane application.  It consists of a header, a primary
37159  * center region containing two nested regions (a top one for a list view and one for item preview below),
37160  * and regions on either side that can be used for navigation, application commands, informational displays, etc.
37161  * The setup and configuration work exactly the same as it does for a {@link Roo.BorderLayout} - this class simply
37162  * expedites the setup of the overall layout and regions for this common application style.
37163  * Example:
37164  <pre><code>
37165 var reader = new Roo.ReaderLayout();
37166 var CP = Roo.ContentPanel;  // shortcut for adding
37167
37168 reader.beginUpdate();
37169 reader.add("north", new CP("north", "North"));
37170 reader.add("west", new CP("west", {title: "West"}));
37171 reader.add("east", new CP("east", {title: "East"}));
37172
37173 reader.regions.listView.add(new CP("listView", "List"));
37174 reader.regions.preview.add(new CP("preview", "Preview"));
37175 reader.endUpdate();
37176 </code></pre>
37177 * @constructor
37178 * Create a new ReaderLayout
37179 * @param {Object} config Configuration options
37180 * @param {String/HTMLElement/Element} container (optional) The container this layout is bound to (defaults to
37181 * document.body if omitted)
37182 */
37183 Roo.ReaderLayout = function(config, renderTo){
37184     var c = config || {size:{}};
37185     Roo.ReaderLayout.superclass.constructor.call(this, renderTo || document.body, {
37186         north: c.north !== false ? Roo.apply({
37187             split:false,
37188             initialSize: 32,
37189             titlebar: false
37190         }, c.north) : false,
37191         west: c.west !== false ? Roo.apply({
37192             split:true,
37193             initialSize: 200,
37194             minSize: 175,
37195             maxSize: 400,
37196             titlebar: true,
37197             collapsible: true,
37198             animate: true,
37199             margins:{left:5,right:0,bottom:5,top:5},
37200             cmargins:{left:5,right:5,bottom:5,top:5}
37201         }, c.west) : false,
37202         east: c.east !== false ? Roo.apply({
37203             split:true,
37204             initialSize: 200,
37205             minSize: 175,
37206             maxSize: 400,
37207             titlebar: true,
37208             collapsible: true,
37209             animate: true,
37210             margins:{left:0,right:5,bottom:5,top:5},
37211             cmargins:{left:5,right:5,bottom:5,top:5}
37212         }, c.east) : false,
37213         center: Roo.apply({
37214             tabPosition: 'top',
37215             autoScroll:false,
37216             closeOnTab: true,
37217             titlebar:false,
37218             margins:{left:c.west!==false ? 0 : 5,right:c.east!==false ? 0 : 5,bottom:5,top:2}
37219         }, c.center)
37220     });
37221
37222     this.el.addClass('x-reader');
37223
37224     this.beginUpdate();
37225
37226     var inner = new Roo.BorderLayout(Roo.get(document.body).createChild(), {
37227         south: c.preview !== false ? Roo.apply({
37228             split:true,
37229             initialSize: 200,
37230             minSize: 100,
37231             autoScroll:true,
37232             collapsible:true,
37233             titlebar: true,
37234             cmargins:{top:5,left:0, right:0, bottom:0}
37235         }, c.preview) : false,
37236         center: Roo.apply({
37237             autoScroll:false,
37238             titlebar:false,
37239             minHeight:200
37240         }, c.listView)
37241     });
37242     this.add('center', new Roo.NestedLayoutPanel(inner,
37243             Roo.apply({title: c.mainTitle || '',tabTip:''},c.innerPanelCfg)));
37244
37245     this.endUpdate();
37246
37247     this.regions.preview = inner.getRegion('south');
37248     this.regions.listView = inner.getRegion('center');
37249 };
37250
37251 Roo.extend(Roo.ReaderLayout, Roo.BorderLayout);/*
37252  * Based on:
37253  * Ext JS Library 1.1.1
37254  * Copyright(c) 2006-2007, Ext JS, LLC.
37255  *
37256  * Originally Released Under LGPL - original licence link has changed is not relivant.
37257  *
37258  * Fork - LGPL
37259  * <script type="text/javascript">
37260  */
37261  
37262 /**
37263  * @class Roo.grid.Grid
37264  * @extends Roo.util.Observable
37265  * This class represents the primary interface of a component based grid control.
37266  * <br><br>Usage:<pre><code>
37267  var grid = new Roo.grid.Grid("my-container-id", {
37268      ds: myDataStore,
37269      cm: myColModel,
37270      selModel: mySelectionModel,
37271      autoSizeColumns: true,
37272      monitorWindowResize: false,
37273      trackMouseOver: true
37274  });
37275  // set any options
37276  grid.render();
37277  * </code></pre>
37278  * <b>Common Problems:</b><br/>
37279  * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
37280  * element will correct this<br/>
37281  * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
37282  * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
37283  * are unpredictable.<br/>
37284  * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
37285  * grid to calculate dimensions/offsets.<br/>
37286   * @constructor
37287  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
37288  * The container MUST have some type of size defined for the grid to fill. The container will be
37289  * automatically set to position relative if it isn't already.
37290  * @param {Object} config A config object that sets properties on this grid.
37291  */
37292 Roo.grid.Grid = function(container, config){
37293         // initialize the container
37294         this.container = Roo.get(container);
37295         this.container.update("");
37296         this.container.setStyle("overflow", "hidden");
37297     this.container.addClass('x-grid-container');
37298
37299     this.id = this.container.id;
37300
37301     Roo.apply(this, config);
37302     // check and correct shorthanded configs
37303     if(this.ds){
37304         this.dataSource = this.ds;
37305         delete this.ds;
37306     }
37307     if(this.cm){
37308         this.colModel = this.cm;
37309         delete this.cm;
37310     }
37311     if(this.sm){
37312         this.selModel = this.sm;
37313         delete this.sm;
37314     }
37315
37316     if (this.selModel) {
37317         this.selModel = Roo.factory(this.selModel, Roo.grid);
37318         this.sm = this.selModel;
37319         this.sm.xmodule = this.xmodule || false;
37320     }
37321     if (typeof(this.colModel.config) == 'undefined') {
37322         this.colModel = new Roo.grid.ColumnModel(this.colModel);
37323         this.cm = this.colModel;
37324         this.cm.xmodule = this.xmodule || false;
37325     }
37326     if (this.dataSource) {
37327         this.dataSource= Roo.factory(this.dataSource, Roo.data);
37328         this.ds = this.dataSource;
37329         this.ds.xmodule = this.xmodule || false;
37330          
37331     }
37332     
37333     
37334     
37335     if(this.width){
37336         this.container.setWidth(this.width);
37337     }
37338
37339     if(this.height){
37340         this.container.setHeight(this.height);
37341     }
37342     /** @private */
37343         this.addEvents({
37344         // raw events
37345         /**
37346          * @event click
37347          * The raw click event for the entire grid.
37348          * @param {Roo.EventObject} e
37349          */
37350         "click" : true,
37351         /**
37352          * @event dblclick
37353          * The raw dblclick event for the entire grid.
37354          * @param {Roo.EventObject} e
37355          */
37356         "dblclick" : true,
37357         /**
37358          * @event contextmenu
37359          * The raw contextmenu event for the entire grid.
37360          * @param {Roo.EventObject} e
37361          */
37362         "contextmenu" : true,
37363         /**
37364          * @event mousedown
37365          * The raw mousedown event for the entire grid.
37366          * @param {Roo.EventObject} e
37367          */
37368         "mousedown" : true,
37369         /**
37370          * @event mouseup
37371          * The raw mouseup event for the entire grid.
37372          * @param {Roo.EventObject} e
37373          */
37374         "mouseup" : true,
37375         /**
37376          * @event mouseover
37377          * The raw mouseover event for the entire grid.
37378          * @param {Roo.EventObject} e
37379          */
37380         "mouseover" : true,
37381         /**
37382          * @event mouseout
37383          * The raw mouseout event for the entire grid.
37384          * @param {Roo.EventObject} e
37385          */
37386         "mouseout" : true,
37387         /**
37388          * @event keypress
37389          * The raw keypress event for the entire grid.
37390          * @param {Roo.EventObject} e
37391          */
37392         "keypress" : true,
37393         /**
37394          * @event keydown
37395          * The raw keydown event for the entire grid.
37396          * @param {Roo.EventObject} e
37397          */
37398         "keydown" : true,
37399
37400         // custom events
37401
37402         /**
37403          * @event cellclick
37404          * Fires when a cell is clicked
37405          * @param {Grid} this
37406          * @param {Number} rowIndex
37407          * @param {Number} columnIndex
37408          * @param {Roo.EventObject} e
37409          */
37410         "cellclick" : true,
37411         /**
37412          * @event celldblclick
37413          * Fires when a cell is double clicked
37414          * @param {Grid} this
37415          * @param {Number} rowIndex
37416          * @param {Number} columnIndex
37417          * @param {Roo.EventObject} e
37418          */
37419         "celldblclick" : true,
37420         /**
37421          * @event rowclick
37422          * Fires when a row is clicked
37423          * @param {Grid} this
37424          * @param {Number} rowIndex
37425          * @param {Roo.EventObject} e
37426          */
37427         "rowclick" : true,
37428         /**
37429          * @event rowdblclick
37430          * Fires when a row is double clicked
37431          * @param {Grid} this
37432          * @param {Number} rowIndex
37433          * @param {Roo.EventObject} e
37434          */
37435         "rowdblclick" : true,
37436         /**
37437          * @event headerclick
37438          * Fires when a header is clicked
37439          * @param {Grid} this
37440          * @param {Number} columnIndex
37441          * @param {Roo.EventObject} e
37442          */
37443         "headerclick" : true,
37444         /**
37445          * @event headerdblclick
37446          * Fires when a header cell is double clicked
37447          * @param {Grid} this
37448          * @param {Number} columnIndex
37449          * @param {Roo.EventObject} e
37450          */
37451         "headerdblclick" : true,
37452         /**
37453          * @event rowcontextmenu
37454          * Fires when a row is right clicked
37455          * @param {Grid} this
37456          * @param {Number} rowIndex
37457          * @param {Roo.EventObject} e
37458          */
37459         "rowcontextmenu" : true,
37460         /**
37461          * @event cellcontextmenu
37462          * Fires when a cell is right clicked
37463          * @param {Grid} this
37464          * @param {Number} rowIndex
37465          * @param {Number} cellIndex
37466          * @param {Roo.EventObject} e
37467          */
37468          "cellcontextmenu" : true,
37469         /**
37470          * @event headercontextmenu
37471          * Fires when a header is right clicked
37472          * @param {Grid} this
37473          * @param {Number} columnIndex
37474          * @param {Roo.EventObject} e
37475          */
37476         "headercontextmenu" : true,
37477         /**
37478          * @event bodyscroll
37479          * Fires when the body element is scrolled
37480          * @param {Number} scrollLeft
37481          * @param {Number} scrollTop
37482          */
37483         "bodyscroll" : true,
37484         /**
37485          * @event columnresize
37486          * Fires when the user resizes a column
37487          * @param {Number} columnIndex
37488          * @param {Number} newSize
37489          */
37490         "columnresize" : true,
37491         /**
37492          * @event columnmove
37493          * Fires when the user moves a column
37494          * @param {Number} oldIndex
37495          * @param {Number} newIndex
37496          */
37497         "columnmove" : true,
37498         /**
37499          * @event startdrag
37500          * Fires when row(s) start being dragged
37501          * @param {Grid} this
37502          * @param {Roo.GridDD} dd The drag drop object
37503          * @param {event} e The raw browser event
37504          */
37505         "startdrag" : true,
37506         /**
37507          * @event enddrag
37508          * Fires when a drag operation is complete
37509          * @param {Grid} this
37510          * @param {Roo.GridDD} dd The drag drop object
37511          * @param {event} e The raw browser event
37512          */
37513         "enddrag" : true,
37514         /**
37515          * @event dragdrop
37516          * Fires when dragged row(s) are dropped on a valid DD target
37517          * @param {Grid} this
37518          * @param {Roo.GridDD} dd The drag drop object
37519          * @param {String} targetId The target drag drop object
37520          * @param {event} e The raw browser event
37521          */
37522         "dragdrop" : true,
37523         /**
37524          * @event dragover
37525          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
37526          * @param {Grid} this
37527          * @param {Roo.GridDD} dd The drag drop object
37528          * @param {String} targetId The target drag drop object
37529          * @param {event} e The raw browser event
37530          */
37531         "dragover" : true,
37532         /**
37533          * @event dragenter
37534          *  Fires when the dragged row(s) first cross another DD target while being dragged
37535          * @param {Grid} this
37536          * @param {Roo.GridDD} dd The drag drop object
37537          * @param {String} targetId The target drag drop object
37538          * @param {event} e The raw browser event
37539          */
37540         "dragenter" : true,
37541         /**
37542          * @event dragout
37543          * Fires when the dragged row(s) leave another DD target while being dragged
37544          * @param {Grid} this
37545          * @param {Roo.GridDD} dd The drag drop object
37546          * @param {String} targetId The target drag drop object
37547          * @param {event} e The raw browser event
37548          */
37549         "dragout" : true,
37550         /**
37551          * @event rowclass
37552          * Fires when a row is rendered, so you can change add a style to it.
37553          * @param {GridView} gridview   The grid view
37554          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
37555          */
37556         'rowclass' : true,
37557
37558         /**
37559          * @event render
37560          * Fires when the grid is rendered
37561          * @param {Grid} grid
37562          */
37563         'render' : true
37564     });
37565
37566     Roo.grid.Grid.superclass.constructor.call(this);
37567 };
37568 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
37569     
37570     /**
37571          * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
37572          */
37573         /**
37574          * @cfg {Roo.grid.GridView} view  The view that renders the grid (default = Roo.grid.GridView)
37575          */
37576         /**
37577          * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
37578          */
37579         /**
37580          * @cfg {Roo.data.Store} ds The data store for the grid
37581          */
37582         /**
37583          * @cfg {Roo.Toolbar} toolbar a toolbar for buttons etc.
37584          */
37585          
37586          /**
37587          * @cfg {Roo.PagingToolbar} footer the paging toolbar
37588          */
37589         
37590         /**
37591      * @cfg {String} ddGroup - drag drop group.
37592      */
37593       /**
37594      * @cfg {String} dragGroup - drag group (?? not sure if needed.)
37595      */
37596
37597     /**
37598      * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
37599      */
37600     minColumnWidth : 25,
37601
37602     /**
37603      * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
37604      * <b>on initial render.</b> It is more efficient to explicitly size the columns
37605      * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option.  Default is false.
37606      */
37607     autoSizeColumns : false,
37608
37609     /**
37610      * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
37611      */
37612     autoSizeHeaders : true,
37613
37614     /**
37615      * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
37616      */
37617     monitorWindowResize : true,
37618
37619     /**
37620      * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
37621      * rows measured to get a columns size. Default is 0 (all rows).
37622      */
37623     maxRowsToMeasure : 0,
37624
37625     /**
37626      * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
37627      */
37628     trackMouseOver : true,
37629
37630     /**
37631     * @cfg {Boolean} enableDrag  True to enable drag of rows. Default is false. (double check if this is needed?)
37632     */
37633       /**
37634     * @cfg {Boolean} enableDrop  True to enable drop of elements. Default is false. (double check if this is needed?)
37635     */
37636     
37637     /**
37638     * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
37639     */
37640     enableDragDrop : false,
37641     
37642     /**
37643     * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
37644     */
37645     enableColumnMove : true,
37646     
37647     /**
37648     * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
37649     */
37650     enableColumnHide : true,
37651     
37652     /**
37653     * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
37654     */
37655     enableRowHeightSync : false,
37656     
37657     /**
37658     * @cfg {Boolean} stripeRows True to stripe the rows.  Default is true.
37659     */
37660     stripeRows : true,
37661     
37662     /**
37663     * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
37664     */
37665     autoHeight : false,
37666
37667     /**
37668      * @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.
37669      */
37670     autoExpandColumn : false,
37671
37672     /**
37673     * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
37674     * Default is 50.
37675     */
37676     autoExpandMin : 50,
37677
37678     /**
37679     * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
37680     */
37681     autoExpandMax : 1000,
37682
37683     /**
37684     * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
37685     */
37686     view : null,
37687
37688     /**
37689     * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
37690     */
37691     loadMask : false,
37692     /**
37693     * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
37694     */
37695     dropTarget: false,
37696      /**
37697     * @cfg {boolean} sortColMenu Sort the column order menu when it shows (usefull for long lists..) default false
37698     */ 
37699     sortColMenu : false,
37700     
37701     // private
37702     rendered : false,
37703
37704     /**
37705     * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
37706     * of a fixed width. Default is false.
37707     */
37708     /**
37709     * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
37710     */
37711     
37712     
37713     /**
37714     * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
37715     * %0 is replaced with the number of selected rows.
37716     */
37717     ddText : "{0} selected row{1}",
37718     
37719     
37720     /**
37721      * Called once after all setup has been completed and the grid is ready to be rendered.
37722      * @return {Roo.grid.Grid} this
37723      */
37724     render : function()
37725     {
37726         var c = this.container;
37727         // try to detect autoHeight/width mode
37728         if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
37729             this.autoHeight = true;
37730         }
37731         var view = this.getView();
37732         view.init(this);
37733
37734         c.on("click", this.onClick, this);
37735         c.on("dblclick", this.onDblClick, this);
37736         c.on("contextmenu", this.onContextMenu, this);
37737         c.on("keydown", this.onKeyDown, this);
37738         if (Roo.isTouch) {
37739             c.on("touchstart", this.onTouchStart, this);
37740         }
37741
37742         this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
37743
37744         this.getSelectionModel().init(this);
37745
37746         view.render();
37747
37748         if(this.loadMask){
37749             this.loadMask = new Roo.LoadMask(this.container,
37750                     Roo.apply({store:this.dataSource}, this.loadMask));
37751         }
37752         
37753         
37754         if (this.toolbar && this.toolbar.xtype) {
37755             this.toolbar.container = this.getView().getHeaderPanel(true);
37756             this.toolbar = new Roo.Toolbar(this.toolbar);
37757         }
37758         if (this.footer && this.footer.xtype) {
37759             this.footer.dataSource = this.getDataSource();
37760             this.footer.container = this.getView().getFooterPanel(true);
37761             this.footer = Roo.factory(this.footer, Roo);
37762         }
37763         if (this.dropTarget && this.dropTarget.xtype) {
37764             delete this.dropTarget.xtype;
37765             this.dropTarget =  new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
37766         }
37767         
37768         
37769         this.rendered = true;
37770         this.fireEvent('render', this);
37771         return this;
37772     },
37773
37774     /**
37775      * Reconfigures the grid to use a different Store and Column Model.
37776      * The View will be bound to the new objects and refreshed.
37777      * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
37778      * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
37779      */
37780     reconfigure : function(dataSource, colModel){
37781         if(this.loadMask){
37782             this.loadMask.destroy();
37783             this.loadMask = new Roo.LoadMask(this.container,
37784                     Roo.apply({store:dataSource}, this.loadMask));
37785         }
37786         this.view.bind(dataSource, colModel);
37787         this.dataSource = dataSource;
37788         this.colModel = colModel;
37789         this.view.refresh(true);
37790     },
37791     /**
37792      * addColumns
37793      * Add's a column, default at the end..
37794      
37795      * @param {int} position to add (default end)
37796      * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel} 
37797      */
37798     addColumns : function(pos, ar)
37799     {
37800         
37801         for (var i =0;i< ar.length;i++) {
37802             var cfg = ar[i];
37803             cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
37804             this.cm.lookup[cfg.id] = cfg;
37805         }
37806         
37807         
37808         if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
37809             pos = this.cm.config.length; //this.cm.config.push(cfg);
37810         } 
37811         pos = Math.max(0,pos);
37812         ar.unshift(0);
37813         ar.unshift(pos);
37814         this.cm.config.splice.apply(this.cm.config, ar);
37815         
37816         
37817         
37818         this.view.generateRules(this.cm);
37819         this.view.refresh(true);
37820         
37821     },
37822     
37823     
37824     
37825     
37826     // private
37827     onKeyDown : function(e){
37828         this.fireEvent("keydown", e);
37829     },
37830
37831     /**
37832      * Destroy this grid.
37833      * @param {Boolean} removeEl True to remove the element
37834      */
37835     destroy : function(removeEl, keepListeners){
37836         if(this.loadMask){
37837             this.loadMask.destroy();
37838         }
37839         var c = this.container;
37840         c.removeAllListeners();
37841         this.view.destroy();
37842         this.colModel.purgeListeners();
37843         if(!keepListeners){
37844             this.purgeListeners();
37845         }
37846         c.update("");
37847         if(removeEl === true){
37848             c.remove();
37849         }
37850     },
37851
37852     // private
37853     processEvent : function(name, e){
37854         // does this fire select???
37855         //Roo.log('grid:processEvent '  + name);
37856         
37857         if (name != 'touchstart' ) {
37858             this.fireEvent(name, e);    
37859         }
37860         
37861         var t = e.getTarget();
37862         var v = this.view;
37863         var header = v.findHeaderIndex(t);
37864         if(header !== false){
37865             var ename = name == 'touchstart' ? 'click' : name;
37866              
37867             this.fireEvent("header" + ename, this, header, e);
37868         }else{
37869             var row = v.findRowIndex(t);
37870             var cell = v.findCellIndex(t);
37871             if (name == 'touchstart') {
37872                 // first touch is always a click.
37873                 // hopefull this happens after selection is updated.?
37874                 name = false;
37875                 
37876                 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
37877                     var cs = this.selModel.getSelectedCell();
37878                     if (row == cs[0] && cell == cs[1]){
37879                         name = 'dblclick';
37880                     }
37881                 }
37882                 if (typeof(this.selModel.getSelections) != 'undefined') {
37883                     var cs = this.selModel.getSelections();
37884                     var ds = this.dataSource;
37885                     if (cs.length == 1 && ds.getAt(row) == cs[0]){
37886                         name = 'dblclick';
37887                     }
37888                 }
37889                 if (!name) {
37890                     return;
37891                 }
37892             }
37893             
37894             
37895             if(row !== false){
37896                 this.fireEvent("row" + name, this, row, e);
37897                 if(cell !== false){
37898                     this.fireEvent("cell" + name, this, row, cell, e);
37899                 }
37900             }
37901         }
37902     },
37903
37904     // private
37905     onClick : function(e){
37906         this.processEvent("click", e);
37907     },
37908    // private
37909     onTouchStart : function(e){
37910         this.processEvent("touchstart", e);
37911     },
37912
37913     // private
37914     onContextMenu : function(e, t){
37915         this.processEvent("contextmenu", e);
37916     },
37917
37918     // private
37919     onDblClick : function(e){
37920         this.processEvent("dblclick", e);
37921     },
37922
37923     // private
37924     walkCells : function(row, col, step, fn, scope){
37925         var cm = this.colModel, clen = cm.getColumnCount();
37926         var ds = this.dataSource, rlen = ds.getCount(), first = true;
37927         if(step < 0){
37928             if(col < 0){
37929                 row--;
37930                 first = false;
37931             }
37932             while(row >= 0){
37933                 if(!first){
37934                     col = clen-1;
37935                 }
37936                 first = false;
37937                 while(col >= 0){
37938                     if(fn.call(scope || this, row, col, cm) === true){
37939                         return [row, col];
37940                     }
37941                     col--;
37942                 }
37943                 row--;
37944             }
37945         } else {
37946             if(col >= clen){
37947                 row++;
37948                 first = false;
37949             }
37950             while(row < rlen){
37951                 if(!first){
37952                     col = 0;
37953                 }
37954                 first = false;
37955                 while(col < clen){
37956                     if(fn.call(scope || this, row, col, cm) === true){
37957                         return [row, col];
37958                     }
37959                     col++;
37960                 }
37961                 row++;
37962             }
37963         }
37964         return null;
37965     },
37966
37967     // private
37968     getSelections : function(){
37969         return this.selModel.getSelections();
37970     },
37971
37972     /**
37973      * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
37974      * but if manual update is required this method will initiate it.
37975      */
37976     autoSize : function(){
37977         if(this.rendered){
37978             this.view.layout();
37979             if(this.view.adjustForScroll){
37980                 this.view.adjustForScroll();
37981             }
37982         }
37983     },
37984
37985     /**
37986      * Returns the grid's underlying element.
37987      * @return {Element} The element
37988      */
37989     getGridEl : function(){
37990         return this.container;
37991     },
37992
37993     // private for compatibility, overridden by editor grid
37994     stopEditing : function(){},
37995
37996     /**
37997      * Returns the grid's SelectionModel.
37998      * @return {SelectionModel}
37999      */
38000     getSelectionModel : function(){
38001         if(!this.selModel){
38002             this.selModel = new Roo.grid.RowSelectionModel();
38003         }
38004         return this.selModel;
38005     },
38006
38007     /**
38008      * Returns the grid's DataSource.
38009      * @return {DataSource}
38010      */
38011     getDataSource : function(){
38012         return this.dataSource;
38013     },
38014
38015     /**
38016      * Returns the grid's ColumnModel.
38017      * @return {ColumnModel}
38018      */
38019     getColumnModel : function(){
38020         return this.colModel;
38021     },
38022
38023     /**
38024      * Returns the grid's GridView object.
38025      * @return {GridView}
38026      */
38027     getView : function(){
38028         if(!this.view){
38029             this.view = new Roo.grid.GridView(this.viewConfig);
38030             this.relayEvents(this.view, [
38031                 "beforerowremoved", "beforerowsinserted",
38032                 "beforerefresh", "rowremoved",
38033                 "rowsinserted", "rowupdated" ,"refresh"
38034             ]);
38035         }
38036         return this.view;
38037     },
38038     /**
38039      * Called to get grid's drag proxy text, by default returns this.ddText.
38040      * Override this to put something different in the dragged text.
38041      * @return {String}
38042      */
38043     getDragDropText : function(){
38044         var count = this.selModel.getCount();
38045         return String.format(this.ddText, count, count == 1 ? '' : 's');
38046     }
38047 });
38048 /*
38049  * Based on:
38050  * Ext JS Library 1.1.1
38051  * Copyright(c) 2006-2007, Ext JS, LLC.
38052  *
38053  * Originally Released Under LGPL - original licence link has changed is not relivant.
38054  *
38055  * Fork - LGPL
38056  * <script type="text/javascript">
38057  */
38058  /**
38059  * @class Roo.grid.AbstractGridView
38060  * @extends Roo.util.Observable
38061  * @abstract
38062  * Abstract base class for grid Views
38063  * @constructor
38064  */
38065 Roo.grid.AbstractGridView = function(){
38066         this.grid = null;
38067         
38068         this.events = {
38069             "beforerowremoved" : true,
38070             "beforerowsinserted" : true,
38071             "beforerefresh" : true,
38072             "rowremoved" : true,
38073             "rowsinserted" : true,
38074             "rowupdated" : true,
38075             "refresh" : true
38076         };
38077     Roo.grid.AbstractGridView.superclass.constructor.call(this);
38078 };
38079
38080 Roo.extend(Roo.grid.AbstractGridView, Roo.util.Observable, {
38081     rowClass : "x-grid-row",
38082     cellClass : "x-grid-cell",
38083     tdClass : "x-grid-td",
38084     hdClass : "x-grid-hd",
38085     splitClass : "x-grid-hd-split",
38086     
38087     init: function(grid){
38088         this.grid = grid;
38089                 var cid = this.grid.getGridEl().id;
38090         this.colSelector = "#" + cid + " ." + this.cellClass + "-";
38091         this.tdSelector = "#" + cid + " ." + this.tdClass + "-";
38092         this.hdSelector = "#" + cid + " ." + this.hdClass + "-";
38093         this.splitSelector = "#" + cid + " ." + this.splitClass + "-";
38094         },
38095         
38096     getColumnRenderers : function(){
38097         var renderers = [];
38098         var cm = this.grid.colModel;
38099         var colCount = cm.getColumnCount();
38100         for(var i = 0; i < colCount; i++){
38101             renderers[i] = cm.getRenderer(i);
38102         }
38103         return renderers;
38104     },
38105     
38106     getColumnIds : function(){
38107         var ids = [];
38108         var cm = this.grid.colModel;
38109         var colCount = cm.getColumnCount();
38110         for(var i = 0; i < colCount; i++){
38111             ids[i] = cm.getColumnId(i);
38112         }
38113         return ids;
38114     },
38115     
38116     getDataIndexes : function(){
38117         if(!this.indexMap){
38118             this.indexMap = this.buildIndexMap();
38119         }
38120         return this.indexMap.colToData;
38121     },
38122     
38123     getColumnIndexByDataIndex : function(dataIndex){
38124         if(!this.indexMap){
38125             this.indexMap = this.buildIndexMap();
38126         }
38127         return this.indexMap.dataToCol[dataIndex];
38128     },
38129     
38130     /**
38131      * Set a css style for a column dynamically. 
38132      * @param {Number} colIndex The index of the column
38133      * @param {String} name The css property name
38134      * @param {String} value The css value
38135      */
38136     setCSSStyle : function(colIndex, name, value){
38137         var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex;
38138         Roo.util.CSS.updateRule(selector, name, value);
38139     },
38140     
38141     generateRules : function(cm){
38142         var ruleBuf = [], rulesId = this.grid.id + '-cssrules';
38143         Roo.util.CSS.removeStyleSheet(rulesId);
38144         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
38145             var cid = cm.getColumnId(i);
38146             ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n",
38147                          this.tdSelector, cid, " {\n}\n",
38148                          this.hdSelector, cid, " {\n}\n",
38149                          this.splitSelector, cid, " {\n}\n");
38150         }
38151         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
38152     }
38153 });/*
38154  * Based on:
38155  * Ext JS Library 1.1.1
38156  * Copyright(c) 2006-2007, Ext JS, LLC.
38157  *
38158  * Originally Released Under LGPL - original licence link has changed is not relivant.
38159  *
38160  * Fork - LGPL
38161  * <script type="text/javascript">
38162  */
38163
38164 // private
38165 // This is a support class used internally by the Grid components
38166 Roo.grid.HeaderDragZone = function(grid, hd, hd2){
38167     this.grid = grid;
38168     this.view = grid.getView();
38169     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
38170     Roo.grid.HeaderDragZone.superclass.constructor.call(this, hd);
38171     if(hd2){
38172         this.setHandleElId(Roo.id(hd));
38173         this.setOuterHandleElId(Roo.id(hd2));
38174     }
38175     this.scroll = false;
38176 };
38177 Roo.extend(Roo.grid.HeaderDragZone, Roo.dd.DragZone, {
38178     maxDragWidth: 120,
38179     getDragData : function(e){
38180         var t = Roo.lib.Event.getTarget(e);
38181         var h = this.view.findHeaderCell(t);
38182         if(h){
38183             return {ddel: h.firstChild, header:h};
38184         }
38185         return false;
38186     },
38187
38188     onInitDrag : function(e){
38189         this.view.headersDisabled = true;
38190         var clone = this.dragData.ddel.cloneNode(true);
38191         clone.id = Roo.id();
38192         clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
38193         this.proxy.update(clone);
38194         return true;
38195     },
38196
38197     afterValidDrop : function(){
38198         var v = this.view;
38199         setTimeout(function(){
38200             v.headersDisabled = false;
38201         }, 50);
38202     },
38203
38204     afterInvalidDrop : function(){
38205         var v = this.view;
38206         setTimeout(function(){
38207             v.headersDisabled = false;
38208         }, 50);
38209     }
38210 });
38211 /*
38212  * Based on:
38213  * Ext JS Library 1.1.1
38214  * Copyright(c) 2006-2007, Ext JS, LLC.
38215  *
38216  * Originally Released Under LGPL - original licence link has changed is not relivant.
38217  *
38218  * Fork - LGPL
38219  * <script type="text/javascript">
38220  */
38221 // private
38222 // This is a support class used internally by the Grid components
38223 Roo.grid.HeaderDropZone = function(grid, hd, hd2){
38224     this.grid = grid;
38225     this.view = grid.getView();
38226     // split the proxies so they don't interfere with mouse events
38227     this.proxyTop = Roo.DomHelper.append(document.body, {
38228         cls:"col-move-top", html:"&#160;"
38229     }, true);
38230     this.proxyBottom = Roo.DomHelper.append(document.body, {
38231         cls:"col-move-bottom", html:"&#160;"
38232     }, true);
38233     this.proxyTop.hide = this.proxyBottom.hide = function(){
38234         this.setLeftTop(-100,-100);
38235         this.setStyle("visibility", "hidden");
38236     };
38237     this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
38238     // temporarily disabled
38239     //Roo.dd.ScrollManager.register(this.view.scroller.dom);
38240     Roo.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
38241 };
38242 Roo.extend(Roo.grid.HeaderDropZone, Roo.dd.DropZone, {
38243     proxyOffsets : [-4, -9],
38244     fly: Roo.Element.fly,
38245
38246     getTargetFromEvent : function(e){
38247         var t = Roo.lib.Event.getTarget(e);
38248         var cindex = this.view.findCellIndex(t);
38249         if(cindex !== false){
38250             return this.view.getHeaderCell(cindex);
38251         }
38252         return null;
38253     },
38254
38255     nextVisible : function(h){
38256         var v = this.view, cm = this.grid.colModel;
38257         h = h.nextSibling;
38258         while(h){
38259             if(!cm.isHidden(v.getCellIndex(h))){
38260                 return h;
38261             }
38262             h = h.nextSibling;
38263         }
38264         return null;
38265     },
38266
38267     prevVisible : function(h){
38268         var v = this.view, cm = this.grid.colModel;
38269         h = h.prevSibling;
38270         while(h){
38271             if(!cm.isHidden(v.getCellIndex(h))){
38272                 return h;
38273             }
38274             h = h.prevSibling;
38275         }
38276         return null;
38277     },
38278
38279     positionIndicator : function(h, n, e){
38280         var x = Roo.lib.Event.getPageX(e);
38281         var r = Roo.lib.Dom.getRegion(n.firstChild);
38282         var px, pt, py = r.top + this.proxyOffsets[1];
38283         if((r.right - x) <= (r.right-r.left)/2){
38284             px = r.right+this.view.borderWidth;
38285             pt = "after";
38286         }else{
38287             px = r.left;
38288             pt = "before";
38289         }
38290         var oldIndex = this.view.getCellIndex(h);
38291         var newIndex = this.view.getCellIndex(n);
38292
38293         if(this.grid.colModel.isFixed(newIndex)){
38294             return false;
38295         }
38296
38297         var locked = this.grid.colModel.isLocked(newIndex);
38298
38299         if(pt == "after"){
38300             newIndex++;
38301         }
38302         if(oldIndex < newIndex){
38303             newIndex--;
38304         }
38305         if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
38306             return false;
38307         }
38308         px +=  this.proxyOffsets[0];
38309         this.proxyTop.setLeftTop(px, py);
38310         this.proxyTop.show();
38311         if(!this.bottomOffset){
38312             this.bottomOffset = this.view.mainHd.getHeight();
38313         }
38314         this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
38315         this.proxyBottom.show();
38316         return pt;
38317     },
38318
38319     onNodeEnter : function(n, dd, e, data){
38320         if(data.header != n){
38321             this.positionIndicator(data.header, n, e);
38322         }
38323     },
38324
38325     onNodeOver : function(n, dd, e, data){
38326         var result = false;
38327         if(data.header != n){
38328             result = this.positionIndicator(data.header, n, e);
38329         }
38330         if(!result){
38331             this.proxyTop.hide();
38332             this.proxyBottom.hide();
38333         }
38334         return result ? this.dropAllowed : this.dropNotAllowed;
38335     },
38336
38337     onNodeOut : function(n, dd, e, data){
38338         this.proxyTop.hide();
38339         this.proxyBottom.hide();
38340     },
38341
38342     onNodeDrop : function(n, dd, e, data){
38343         var h = data.header;
38344         if(h != n){
38345             var cm = this.grid.colModel;
38346             var x = Roo.lib.Event.getPageX(e);
38347             var r = Roo.lib.Dom.getRegion(n.firstChild);
38348             var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
38349             var oldIndex = this.view.getCellIndex(h);
38350             var newIndex = this.view.getCellIndex(n);
38351             var locked = cm.isLocked(newIndex);
38352             if(pt == "after"){
38353                 newIndex++;
38354             }
38355             if(oldIndex < newIndex){
38356                 newIndex--;
38357             }
38358             if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
38359                 return false;
38360             }
38361             cm.setLocked(oldIndex, locked, true);
38362             cm.moveColumn(oldIndex, newIndex);
38363             this.grid.fireEvent("columnmove", oldIndex, newIndex);
38364             return true;
38365         }
38366         return false;
38367     }
38368 });
38369 /*
38370  * Based on:
38371  * Ext JS Library 1.1.1
38372  * Copyright(c) 2006-2007, Ext JS, LLC.
38373  *
38374  * Originally Released Under LGPL - original licence link has changed is not relivant.
38375  *
38376  * Fork - LGPL
38377  * <script type="text/javascript">
38378  */
38379   
38380 /**
38381  * @class Roo.grid.GridView
38382  * @extends Roo.util.Observable
38383  *
38384  * @constructor
38385  * @param {Object} config
38386  */
38387 Roo.grid.GridView = function(config){
38388     Roo.grid.GridView.superclass.constructor.call(this);
38389     this.el = null;
38390
38391     Roo.apply(this, config);
38392 };
38393
38394 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
38395
38396     unselectable :  'unselectable="on"',
38397     unselectableCls :  'x-unselectable',
38398     
38399     
38400     rowClass : "x-grid-row",
38401
38402     cellClass : "x-grid-col",
38403
38404     tdClass : "x-grid-td",
38405
38406     hdClass : "x-grid-hd",
38407
38408     splitClass : "x-grid-split",
38409
38410     sortClasses : ["sort-asc", "sort-desc"],
38411
38412     enableMoveAnim : false,
38413
38414     hlColor: "C3DAF9",
38415
38416     dh : Roo.DomHelper,
38417
38418     fly : Roo.Element.fly,
38419
38420     css : Roo.util.CSS,
38421
38422     borderWidth: 1,
38423
38424     splitOffset: 3,
38425
38426     scrollIncrement : 22,
38427
38428     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
38429
38430     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
38431
38432     bind : function(ds, cm){
38433         if(this.ds){
38434             this.ds.un("load", this.onLoad, this);
38435             this.ds.un("datachanged", this.onDataChange, this);
38436             this.ds.un("add", this.onAdd, this);
38437             this.ds.un("remove", this.onRemove, this);
38438             this.ds.un("update", this.onUpdate, this);
38439             this.ds.un("clear", this.onClear, this);
38440         }
38441         if(ds){
38442             ds.on("load", this.onLoad, this);
38443             ds.on("datachanged", this.onDataChange, this);
38444             ds.on("add", this.onAdd, this);
38445             ds.on("remove", this.onRemove, this);
38446             ds.on("update", this.onUpdate, this);
38447             ds.on("clear", this.onClear, this);
38448         }
38449         this.ds = ds;
38450
38451         if(this.cm){
38452             this.cm.un("widthchange", this.onColWidthChange, this);
38453             this.cm.un("headerchange", this.onHeaderChange, this);
38454             this.cm.un("hiddenchange", this.onHiddenChange, this);
38455             this.cm.un("columnmoved", this.onColumnMove, this);
38456             this.cm.un("columnlockchange", this.onColumnLock, this);
38457         }
38458         if(cm){
38459             this.generateRules(cm);
38460             cm.on("widthchange", this.onColWidthChange, this);
38461             cm.on("headerchange", this.onHeaderChange, this);
38462             cm.on("hiddenchange", this.onHiddenChange, this);
38463             cm.on("columnmoved", this.onColumnMove, this);
38464             cm.on("columnlockchange", this.onColumnLock, this);
38465         }
38466         this.cm = cm;
38467     },
38468
38469     init: function(grid){
38470         Roo.grid.GridView.superclass.init.call(this, grid);
38471
38472         this.bind(grid.dataSource, grid.colModel);
38473
38474         grid.on("headerclick", this.handleHeaderClick, this);
38475
38476         if(grid.trackMouseOver){
38477             grid.on("mouseover", this.onRowOver, this);
38478             grid.on("mouseout", this.onRowOut, this);
38479         }
38480         grid.cancelTextSelection = function(){};
38481         this.gridId = grid.id;
38482
38483         var tpls = this.templates || {};
38484
38485         if(!tpls.master){
38486             tpls.master = new Roo.Template(
38487                '<div class="x-grid" hidefocus="true">',
38488                 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
38489                   '<div class="x-grid-topbar"></div>',
38490                   '<div class="x-grid-scroller"><div></div></div>',
38491                   '<div class="x-grid-locked">',
38492                       '<div class="x-grid-header">{lockedHeader}</div>',
38493                       '<div class="x-grid-body">{lockedBody}</div>',
38494                   "</div>",
38495                   '<div class="x-grid-viewport">',
38496                       '<div class="x-grid-header">{header}</div>',
38497                       '<div class="x-grid-body">{body}</div>',
38498                   "</div>",
38499                   '<div class="x-grid-bottombar"></div>',
38500                  
38501                   '<div class="x-grid-resize-proxy">&#160;</div>',
38502                "</div>"
38503             );
38504             tpls.master.disableformats = true;
38505         }
38506
38507         if(!tpls.header){
38508             tpls.header = new Roo.Template(
38509                '<table border="0" cellspacing="0" cellpadding="0">',
38510                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
38511                "</table>{splits}"
38512             );
38513             tpls.header.disableformats = true;
38514         }
38515         tpls.header.compile();
38516
38517         if(!tpls.hcell){
38518             tpls.hcell = new Roo.Template(
38519                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
38520                 '<div class="x-grid-hd-text ' + this.unselectableCls +  '" ' + this.unselectable +'>{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
38521                 "</div></td>"
38522              );
38523              tpls.hcell.disableFormats = true;
38524         }
38525         tpls.hcell.compile();
38526
38527         if(!tpls.hsplit){
38528             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style} ' +
38529                                             this.unselectableCls +  '" ' + this.unselectable +'>&#160;</div>');
38530             tpls.hsplit.disableFormats = true;
38531         }
38532         tpls.hsplit.compile();
38533
38534         if(!tpls.body){
38535             tpls.body = new Roo.Template(
38536                '<table border="0" cellspacing="0" cellpadding="0">',
38537                "<tbody>{rows}</tbody>",
38538                "</table>"
38539             );
38540             tpls.body.disableFormats = true;
38541         }
38542         tpls.body.compile();
38543
38544         if(!tpls.row){
38545             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
38546             tpls.row.disableFormats = true;
38547         }
38548         tpls.row.compile();
38549
38550         if(!tpls.cell){
38551             tpls.cell = new Roo.Template(
38552                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
38553                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text ' +
38554                     this.unselectableCls +  '" ' + this.unselectable +'" {attr}>{value}</div></div>',
38555                 "</td>"
38556             );
38557             tpls.cell.disableFormats = true;
38558         }
38559         tpls.cell.compile();
38560
38561         this.templates = tpls;
38562     },
38563
38564     // remap these for backwards compat
38565     onColWidthChange : function(){
38566         this.updateColumns.apply(this, arguments);
38567     },
38568     onHeaderChange : function(){
38569         this.updateHeaders.apply(this, arguments);
38570     }, 
38571     onHiddenChange : function(){
38572         this.handleHiddenChange.apply(this, arguments);
38573     },
38574     onColumnMove : function(){
38575         this.handleColumnMove.apply(this, arguments);
38576     },
38577     onColumnLock : function(){
38578         this.handleLockChange.apply(this, arguments);
38579     },
38580
38581     onDataChange : function(){
38582         this.refresh();
38583         this.updateHeaderSortState();
38584     },
38585
38586     onClear : function(){
38587         this.refresh();
38588     },
38589
38590     onUpdate : function(ds, record){
38591         this.refreshRow(record);
38592     },
38593
38594     refreshRow : function(record){
38595         var ds = this.ds, index;
38596         if(typeof record == 'number'){
38597             index = record;
38598             record = ds.getAt(index);
38599         }else{
38600             index = ds.indexOf(record);
38601         }
38602         this.insertRows(ds, index, index, true);
38603         this.onRemove(ds, record, index+1, true);
38604         this.syncRowHeights(index, index);
38605         this.layout();
38606         this.fireEvent("rowupdated", this, index, record);
38607     },
38608
38609     onAdd : function(ds, records, index){
38610         this.insertRows(ds, index, index + (records.length-1));
38611     },
38612
38613     onRemove : function(ds, record, index, isUpdate){
38614         if(isUpdate !== true){
38615             this.fireEvent("beforerowremoved", this, index, record);
38616         }
38617         var bt = this.getBodyTable(), lt = this.getLockedTable();
38618         if(bt.rows[index]){
38619             bt.firstChild.removeChild(bt.rows[index]);
38620         }
38621         if(lt.rows[index]){
38622             lt.firstChild.removeChild(lt.rows[index]);
38623         }
38624         if(isUpdate !== true){
38625             this.stripeRows(index);
38626             this.syncRowHeights(index, index);
38627             this.layout();
38628             this.fireEvent("rowremoved", this, index, record);
38629         }
38630     },
38631
38632     onLoad : function(){
38633         this.scrollToTop();
38634     },
38635
38636     /**
38637      * Scrolls the grid to the top
38638      */
38639     scrollToTop : function(){
38640         if(this.scroller){
38641             this.scroller.dom.scrollTop = 0;
38642             this.syncScroll();
38643         }
38644     },
38645
38646     /**
38647      * Gets a panel in the header of the grid that can be used for toolbars etc.
38648      * After modifying the contents of this panel a call to grid.autoSize() may be
38649      * required to register any changes in size.
38650      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
38651      * @return Roo.Element
38652      */
38653     getHeaderPanel : function(doShow){
38654         if(doShow){
38655             this.headerPanel.show();
38656         }
38657         return this.headerPanel;
38658     },
38659
38660     /**
38661      * Gets a panel in the footer of the grid that can be used for toolbars etc.
38662      * After modifying the contents of this panel a call to grid.autoSize() may be
38663      * required to register any changes in size.
38664      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
38665      * @return Roo.Element
38666      */
38667     getFooterPanel : function(doShow){
38668         if(doShow){
38669             this.footerPanel.show();
38670         }
38671         return this.footerPanel;
38672     },
38673
38674     initElements : function(){
38675         var E = Roo.Element;
38676         var el = this.grid.getGridEl().dom.firstChild;
38677         var cs = el.childNodes;
38678
38679         this.el = new E(el);
38680         
38681          this.focusEl = new E(el.firstChild);
38682         this.focusEl.swallowEvent("click", true);
38683         
38684         this.headerPanel = new E(cs[1]);
38685         this.headerPanel.enableDisplayMode("block");
38686
38687         this.scroller = new E(cs[2]);
38688         this.scrollSizer = new E(this.scroller.dom.firstChild);
38689
38690         this.lockedWrap = new E(cs[3]);
38691         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
38692         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
38693
38694         this.mainWrap = new E(cs[4]);
38695         this.mainHd = new E(this.mainWrap.dom.firstChild);
38696         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
38697
38698         this.footerPanel = new E(cs[5]);
38699         this.footerPanel.enableDisplayMode("block");
38700
38701         this.resizeProxy = new E(cs[6]);
38702
38703         this.headerSelector = String.format(
38704            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
38705            this.lockedHd.id, this.mainHd.id
38706         );
38707
38708         this.splitterSelector = String.format(
38709            '#{0} div.x-grid-split, #{1} div.x-grid-split',
38710            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
38711         );
38712     },
38713     idToCssName : function(s)
38714     {
38715         return s.replace(/[^a-z0-9]+/ig, '-');
38716     },
38717
38718     getHeaderCell : function(index){
38719         return Roo.DomQuery.select(this.headerSelector)[index];
38720     },
38721
38722     getHeaderCellMeasure : function(index){
38723         return this.getHeaderCell(index).firstChild;
38724     },
38725
38726     getHeaderCellText : function(index){
38727         return this.getHeaderCell(index).firstChild.firstChild;
38728     },
38729
38730     getLockedTable : function(){
38731         return this.lockedBody.dom.firstChild;
38732     },
38733
38734     getBodyTable : function(){
38735         return this.mainBody.dom.firstChild;
38736     },
38737
38738     getLockedRow : function(index){
38739         return this.getLockedTable().rows[index];
38740     },
38741
38742     getRow : function(index){
38743         return this.getBodyTable().rows[index];
38744     },
38745
38746     getRowComposite : function(index){
38747         if(!this.rowEl){
38748             this.rowEl = new Roo.CompositeElementLite();
38749         }
38750         var els = [], lrow, mrow;
38751         if(lrow = this.getLockedRow(index)){
38752             els.push(lrow);
38753         }
38754         if(mrow = this.getRow(index)){
38755             els.push(mrow);
38756         }
38757         this.rowEl.elements = els;
38758         return this.rowEl;
38759     },
38760     /**
38761      * Gets the 'td' of the cell
38762      * 
38763      * @param {Integer} rowIndex row to select
38764      * @param {Integer} colIndex column to select
38765      * 
38766      * @return {Object} 
38767      */
38768     getCell : function(rowIndex, colIndex){
38769         var locked = this.cm.getLockedCount();
38770         var source;
38771         if(colIndex < locked){
38772             source = this.lockedBody.dom.firstChild;
38773         }else{
38774             source = this.mainBody.dom.firstChild;
38775             colIndex -= locked;
38776         }
38777         return source.rows[rowIndex].childNodes[colIndex];
38778     },
38779
38780     getCellText : function(rowIndex, colIndex){
38781         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
38782     },
38783
38784     getCellBox : function(cell){
38785         var b = this.fly(cell).getBox();
38786         if(Roo.isOpera){ // opera fails to report the Y
38787             b.y = cell.offsetTop + this.mainBody.getY();
38788         }
38789         return b;
38790     },
38791
38792     getCellIndex : function(cell){
38793         var id = String(cell.className).match(this.cellRE);
38794         if(id){
38795             return parseInt(id[1], 10);
38796         }
38797         return 0;
38798     },
38799
38800     findHeaderIndex : function(n){
38801         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
38802         return r ? this.getCellIndex(r) : false;
38803     },
38804
38805     findHeaderCell : function(n){
38806         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
38807         return r ? r : false;
38808     },
38809
38810     findRowIndex : function(n){
38811         if(!n){
38812             return false;
38813         }
38814         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
38815         return r ? r.rowIndex : false;
38816     },
38817
38818     findCellIndex : function(node){
38819         var stop = this.el.dom;
38820         while(node && node != stop){
38821             if(this.findRE.test(node.className)){
38822                 return this.getCellIndex(node);
38823             }
38824             node = node.parentNode;
38825         }
38826         return false;
38827     },
38828
38829     getColumnId : function(index){
38830         return this.cm.getColumnId(index);
38831     },
38832
38833     getSplitters : function()
38834     {
38835         if(this.splitterSelector){
38836            return Roo.DomQuery.select(this.splitterSelector);
38837         }else{
38838             return null;
38839       }
38840     },
38841
38842     getSplitter : function(index){
38843         return this.getSplitters()[index];
38844     },
38845
38846     onRowOver : function(e, t){
38847         var row;
38848         if((row = this.findRowIndex(t)) !== false){
38849             this.getRowComposite(row).addClass("x-grid-row-over");
38850         }
38851     },
38852
38853     onRowOut : function(e, t){
38854         var row;
38855         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
38856             this.getRowComposite(row).removeClass("x-grid-row-over");
38857         }
38858     },
38859
38860     renderHeaders : function(){
38861         var cm = this.cm;
38862         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
38863         var cb = [], lb = [], sb = [], lsb = [], p = {};
38864         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
38865             p.cellId = "x-grid-hd-0-" + i;
38866             p.splitId = "x-grid-csplit-0-" + i;
38867             p.id = cm.getColumnId(i);
38868             p.value = cm.getColumnHeader(i) || "";
38869             p.title = cm.getColumnTooltip(i) || (''+p.value).match(/\</)  ? '' :  p.value  || "";
38870             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
38871             if(!cm.isLocked(i)){
38872                 cb[cb.length] = ct.apply(p);
38873                 sb[sb.length] = st.apply(p);
38874             }else{
38875                 lb[lb.length] = ct.apply(p);
38876                 lsb[lsb.length] = st.apply(p);
38877             }
38878         }
38879         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
38880                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
38881     },
38882
38883     updateHeaders : function(){
38884         var html = this.renderHeaders();
38885         this.lockedHd.update(html[0]);
38886         this.mainHd.update(html[1]);
38887     },
38888
38889     /**
38890      * Focuses the specified row.
38891      * @param {Number} row The row index
38892      */
38893     focusRow : function(row)
38894     {
38895         //Roo.log('GridView.focusRow');
38896         var x = this.scroller.dom.scrollLeft;
38897         this.focusCell(row, 0, false);
38898         this.scroller.dom.scrollLeft = x;
38899     },
38900
38901     /**
38902      * Focuses the specified cell.
38903      * @param {Number} row The row index
38904      * @param {Number} col The column index
38905      * @param {Boolean} hscroll false to disable horizontal scrolling
38906      */
38907     focusCell : function(row, col, hscroll)
38908     {
38909         //Roo.log('GridView.focusCell');
38910         var el = this.ensureVisible(row, col, hscroll);
38911         this.focusEl.alignTo(el, "tl-tl");
38912         if(Roo.isGecko){
38913             this.focusEl.focus();
38914         }else{
38915             this.focusEl.focus.defer(1, this.focusEl);
38916         }
38917     },
38918
38919     /**
38920      * Scrolls the specified cell into view
38921      * @param {Number} row The row index
38922      * @param {Number} col The column index
38923      * @param {Boolean} hscroll false to disable horizontal scrolling
38924      */
38925     ensureVisible : function(row, col, hscroll)
38926     {
38927         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
38928         //return null; //disable for testing.
38929         if(typeof row != "number"){
38930             row = row.rowIndex;
38931         }
38932         if(row < 0 && row >= this.ds.getCount()){
38933             return  null;
38934         }
38935         col = (col !== undefined ? col : 0);
38936         var cm = this.grid.colModel;
38937         while(cm.isHidden(col)){
38938             col++;
38939         }
38940
38941         var el = this.getCell(row, col);
38942         if(!el){
38943             return null;
38944         }
38945         var c = this.scroller.dom;
38946
38947         var ctop = parseInt(el.offsetTop, 10);
38948         var cleft = parseInt(el.offsetLeft, 10);
38949         var cbot = ctop + el.offsetHeight;
38950         var cright = cleft + el.offsetWidth;
38951         
38952         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
38953         var stop = parseInt(c.scrollTop, 10);
38954         var sleft = parseInt(c.scrollLeft, 10);
38955         var sbot = stop + ch;
38956         var sright = sleft + c.clientWidth;
38957         /*
38958         Roo.log('GridView.ensureVisible:' +
38959                 ' ctop:' + ctop +
38960                 ' c.clientHeight:' + c.clientHeight +
38961                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
38962                 ' stop:' + stop +
38963                 ' cbot:' + cbot +
38964                 ' sbot:' + sbot +
38965                 ' ch:' + ch  
38966                 );
38967         */
38968         if(ctop < stop){
38969             c.scrollTop = ctop;
38970             //Roo.log("set scrolltop to ctop DISABLE?");
38971         }else if(cbot > sbot){
38972             //Roo.log("set scrolltop to cbot-ch");
38973             c.scrollTop = cbot-ch;
38974         }
38975         
38976         if(hscroll !== false){
38977             if(cleft < sleft){
38978                 c.scrollLeft = cleft;
38979             }else if(cright > sright){
38980                 c.scrollLeft = cright-c.clientWidth;
38981             }
38982         }
38983          
38984         return el;
38985     },
38986
38987     updateColumns : function(){
38988         this.grid.stopEditing();
38989         var cm = this.grid.colModel, colIds = this.getColumnIds();
38990         //var totalWidth = cm.getTotalWidth();
38991         var pos = 0;
38992         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
38993             //if(cm.isHidden(i)) continue;
38994             var w = cm.getColumnWidth(i);
38995             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
38996             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
38997         }
38998         this.updateSplitters();
38999     },
39000
39001     generateRules : function(cm){
39002         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
39003         Roo.util.CSS.removeStyleSheet(rulesId);
39004         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
39005             var cid = cm.getColumnId(i);
39006             var align = '';
39007             if(cm.config[i].align){
39008                 align = 'text-align:'+cm.config[i].align+';';
39009             }
39010             var hidden = '';
39011             if(cm.isHidden(i)){
39012                 hidden = 'display:none;';
39013             }
39014             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
39015             ruleBuf.push(
39016                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
39017                     this.hdSelector, cid, " {\n", align, width, "}\n",
39018                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
39019                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
39020         }
39021         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
39022     },
39023
39024     updateSplitters : function(){
39025         var cm = this.cm, s = this.getSplitters();
39026         if(s){ // splitters not created yet
39027             var pos = 0, locked = true;
39028             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
39029                 if(cm.isHidden(i)) {
39030                     continue;
39031                 }
39032                 var w = cm.getColumnWidth(i); // make sure it's a number
39033                 if(!cm.isLocked(i) && locked){
39034                     pos = 0;
39035                     locked = false;
39036                 }
39037                 pos += w;
39038                 s[i].style.left = (pos-this.splitOffset) + "px";
39039             }
39040         }
39041     },
39042
39043     handleHiddenChange : function(colModel, colIndex, hidden){
39044         if(hidden){
39045             this.hideColumn(colIndex);
39046         }else{
39047             this.unhideColumn(colIndex);
39048         }
39049     },
39050
39051     hideColumn : function(colIndex){
39052         var cid = this.getColumnId(colIndex);
39053         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
39054         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
39055         if(Roo.isSafari){
39056             this.updateHeaders();
39057         }
39058         this.updateSplitters();
39059         this.layout();
39060     },
39061
39062     unhideColumn : function(colIndex){
39063         var cid = this.getColumnId(colIndex);
39064         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
39065         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
39066
39067         if(Roo.isSafari){
39068             this.updateHeaders();
39069         }
39070         this.updateSplitters();
39071         this.layout();
39072     },
39073
39074     insertRows : function(dm, firstRow, lastRow, isUpdate){
39075         if(firstRow == 0 && lastRow == dm.getCount()-1){
39076             this.refresh();
39077         }else{
39078             if(!isUpdate){
39079                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
39080             }
39081             var s = this.getScrollState();
39082             var markup = this.renderRows(firstRow, lastRow);
39083             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
39084             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
39085             this.restoreScroll(s);
39086             if(!isUpdate){
39087                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
39088                 this.syncRowHeights(firstRow, lastRow);
39089                 this.stripeRows(firstRow);
39090                 this.layout();
39091             }
39092         }
39093     },
39094
39095     bufferRows : function(markup, target, index){
39096         var before = null, trows = target.rows, tbody = target.tBodies[0];
39097         if(index < trows.length){
39098             before = trows[index];
39099         }
39100         var b = document.createElement("div");
39101         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
39102         var rows = b.firstChild.rows;
39103         for(var i = 0, len = rows.length; i < len; i++){
39104             if(before){
39105                 tbody.insertBefore(rows[0], before);
39106             }else{
39107                 tbody.appendChild(rows[0]);
39108             }
39109         }
39110         b.innerHTML = "";
39111         b = null;
39112     },
39113
39114     deleteRows : function(dm, firstRow, lastRow){
39115         if(dm.getRowCount()<1){
39116             this.fireEvent("beforerefresh", this);
39117             this.mainBody.update("");
39118             this.lockedBody.update("");
39119             this.fireEvent("refresh", this);
39120         }else{
39121             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
39122             var bt = this.getBodyTable();
39123             var tbody = bt.firstChild;
39124             var rows = bt.rows;
39125             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
39126                 tbody.removeChild(rows[firstRow]);
39127             }
39128             this.stripeRows(firstRow);
39129             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
39130         }
39131     },
39132
39133     updateRows : function(dataSource, firstRow, lastRow){
39134         var s = this.getScrollState();
39135         this.refresh();
39136         this.restoreScroll(s);
39137     },
39138
39139     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
39140         if(!noRefresh){
39141            this.refresh();
39142         }
39143         this.updateHeaderSortState();
39144     },
39145
39146     getScrollState : function(){
39147         
39148         var sb = this.scroller.dom;
39149         return {left: sb.scrollLeft, top: sb.scrollTop};
39150     },
39151
39152     stripeRows : function(startRow){
39153         if(!this.grid.stripeRows || this.ds.getCount() < 1){
39154             return;
39155         }
39156         startRow = startRow || 0;
39157         var rows = this.getBodyTable().rows;
39158         var lrows = this.getLockedTable().rows;
39159         var cls = ' x-grid-row-alt ';
39160         for(var i = startRow, len = rows.length; i < len; i++){
39161             var row = rows[i], lrow = lrows[i];
39162             var isAlt = ((i+1) % 2 == 0);
39163             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
39164             if(isAlt == hasAlt){
39165                 continue;
39166             }
39167             if(isAlt){
39168                 row.className += " x-grid-row-alt";
39169             }else{
39170                 row.className = row.className.replace("x-grid-row-alt", "");
39171             }
39172             if(lrow){
39173                 lrow.className = row.className;
39174             }
39175         }
39176     },
39177
39178     restoreScroll : function(state){
39179         //Roo.log('GridView.restoreScroll');
39180         var sb = this.scroller.dom;
39181         sb.scrollLeft = state.left;
39182         sb.scrollTop = state.top;
39183         this.syncScroll();
39184     },
39185
39186     syncScroll : function(){
39187         //Roo.log('GridView.syncScroll');
39188         var sb = this.scroller.dom;
39189         var sh = this.mainHd.dom;
39190         var bs = this.mainBody.dom;
39191         var lv = this.lockedBody.dom;
39192         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
39193         lv.scrollTop = bs.scrollTop = sb.scrollTop;
39194     },
39195
39196     handleScroll : function(e){
39197         this.syncScroll();
39198         var sb = this.scroller.dom;
39199         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
39200         e.stopEvent();
39201     },
39202
39203     handleWheel : function(e){
39204         var d = e.getWheelDelta();
39205         this.scroller.dom.scrollTop -= d*22;
39206         // set this here to prevent jumpy scrolling on large tables
39207         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
39208         e.stopEvent();
39209     },
39210
39211     renderRows : function(startRow, endRow){
39212         // pull in all the crap needed to render rows
39213         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
39214         var colCount = cm.getColumnCount();
39215
39216         if(ds.getCount() < 1){
39217             return ["", ""];
39218         }
39219
39220         // build a map for all the columns
39221         var cs = [];
39222         for(var i = 0; i < colCount; i++){
39223             var name = cm.getDataIndex(i);
39224             cs[i] = {
39225                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
39226                 renderer : cm.getRenderer(i),
39227                 id : cm.getColumnId(i),
39228                 locked : cm.isLocked(i),
39229                 has_editor : cm.isCellEditable(i)
39230             };
39231         }
39232
39233         startRow = startRow || 0;
39234         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
39235
39236         // records to render
39237         var rs = ds.getRange(startRow, endRow);
39238
39239         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
39240     },
39241
39242     // As much as I hate to duplicate code, this was branched because FireFox really hates
39243     // [].join("") on strings. The performance difference was substantial enough to
39244     // branch this function
39245     doRender : Roo.isGecko ?
39246             function(cs, rs, ds, startRow, colCount, stripe){
39247                 var ts = this.templates, ct = ts.cell, rt = ts.row;
39248                 // buffers
39249                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
39250                 
39251                 var hasListener = this.grid.hasListener('rowclass');
39252                 var rowcfg = {};
39253                 for(var j = 0, len = rs.length; j < len; j++){
39254                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
39255                     for(var i = 0; i < colCount; i++){
39256                         c = cs[i];
39257                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
39258                         p.id = c.id;
39259                         p.css = p.attr = "";
39260                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
39261                         if(p.value == undefined || p.value === "") {
39262                             p.value = "&#160;";
39263                         }
39264                         if(c.has_editor){
39265                             p.css += ' x-grid-editable-cell';
39266                         }
39267                         if(c.dirty && typeof r.modified[c.name] !== 'undefined'){
39268                             p.css +=  ' x-grid-dirty-cell';
39269                         }
39270                         var markup = ct.apply(p);
39271                         if(!c.locked){
39272                             cb+= markup;
39273                         }else{
39274                             lcb+= markup;
39275                         }
39276                     }
39277                     var alt = [];
39278                     if(stripe && ((rowIndex+1) % 2 == 0)){
39279                         alt.push("x-grid-row-alt")
39280                     }
39281                     if(r.dirty){
39282                         alt.push(  " x-grid-dirty-row");
39283                     }
39284                     rp.cells = lcb;
39285                     if(this.getRowClass){
39286                         alt.push(this.getRowClass(r, rowIndex));
39287                     }
39288                     if (hasListener) {
39289                         rowcfg = {
39290                              
39291                             record: r,
39292                             rowIndex : rowIndex,
39293                             rowClass : ''
39294                         };
39295                         this.grid.fireEvent('rowclass', this, rowcfg);
39296                         alt.push(rowcfg.rowClass);
39297                     }
39298                     rp.alt = alt.join(" ");
39299                     lbuf+= rt.apply(rp);
39300                     rp.cells = cb;
39301                     buf+=  rt.apply(rp);
39302                 }
39303                 return [lbuf, buf];
39304             } :
39305             function(cs, rs, ds, startRow, colCount, stripe){
39306                 var ts = this.templates, ct = ts.cell, rt = ts.row;
39307                 // buffers
39308                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
39309                 var hasListener = this.grid.hasListener('rowclass');
39310  
39311                 var rowcfg = {};
39312                 for(var j = 0, len = rs.length; j < len; j++){
39313                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
39314                     for(var i = 0; i < colCount; i++){
39315                         c = cs[i];
39316                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
39317                         p.id = c.id;
39318                         p.css = p.attr = "";
39319                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
39320                         if(p.value == undefined || p.value === "") {
39321                             p.value = "&#160;";
39322                         }
39323                         //Roo.log(c);
39324                          if(c.has_editor){
39325                             p.css += ' x-grid-editable-cell';
39326                         }
39327                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
39328                             p.css += ' x-grid-dirty-cell' 
39329                         }
39330                         
39331                         var markup = ct.apply(p);
39332                         if(!c.locked){
39333                             cb[cb.length] = markup;
39334                         }else{
39335                             lcb[lcb.length] = markup;
39336                         }
39337                     }
39338                     var alt = [];
39339                     if(stripe && ((rowIndex+1) % 2 == 0)){
39340                         alt.push( "x-grid-row-alt");
39341                     }
39342                     if(r.dirty){
39343                         alt.push(" x-grid-dirty-row");
39344                     }
39345                     rp.cells = lcb;
39346                     if(this.getRowClass){
39347                         alt.push( this.getRowClass(r, rowIndex));
39348                     }
39349                     if (hasListener) {
39350                         rowcfg = {
39351                              
39352                             record: r,
39353                             rowIndex : rowIndex,
39354                             rowClass : ''
39355                         };
39356                         this.grid.fireEvent('rowclass', this, rowcfg);
39357                         alt.push(rowcfg.rowClass);
39358                     }
39359                     
39360                     rp.alt = alt.join(" ");
39361                     rp.cells = lcb.join("");
39362                     lbuf[lbuf.length] = rt.apply(rp);
39363                     rp.cells = cb.join("");
39364                     buf[buf.length] =  rt.apply(rp);
39365                 }
39366                 return [lbuf.join(""), buf.join("")];
39367             },
39368
39369     renderBody : function(){
39370         var markup = this.renderRows();
39371         var bt = this.templates.body;
39372         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
39373     },
39374
39375     /**
39376      * Refreshes the grid
39377      * @param {Boolean} headersToo
39378      */
39379     refresh : function(headersToo){
39380         this.fireEvent("beforerefresh", this);
39381         this.grid.stopEditing();
39382         var result = this.renderBody();
39383         this.lockedBody.update(result[0]);
39384         this.mainBody.update(result[1]);
39385         if(headersToo === true){
39386             this.updateHeaders();
39387             this.updateColumns();
39388             this.updateSplitters();
39389             this.updateHeaderSortState();
39390         }
39391         this.syncRowHeights();
39392         this.layout();
39393         this.fireEvent("refresh", this);
39394     },
39395
39396     handleColumnMove : function(cm, oldIndex, newIndex){
39397         this.indexMap = null;
39398         var s = this.getScrollState();
39399         this.refresh(true);
39400         this.restoreScroll(s);
39401         this.afterMove(newIndex);
39402     },
39403
39404     afterMove : function(colIndex){
39405         if(this.enableMoveAnim && Roo.enableFx){
39406             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
39407         }
39408         // if multisort - fix sortOrder, and reload..
39409         if (this.grid.dataSource.multiSort) {
39410             // the we can call sort again..
39411             var dm = this.grid.dataSource;
39412             var cm = this.grid.colModel;
39413             var so = [];
39414             for(var i = 0; i < cm.config.length; i++ ) {
39415                 
39416                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
39417                     continue; // dont' bother, it's not in sort list or being set.
39418                 }
39419                 
39420                 so.push(cm.config[i].dataIndex);
39421             };
39422             dm.sortOrder = so;
39423             dm.load(dm.lastOptions);
39424             
39425             
39426         }
39427         
39428     },
39429
39430     updateCell : function(dm, rowIndex, dataIndex){
39431         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
39432         if(typeof colIndex == "undefined"){ // not present in grid
39433             return;
39434         }
39435         var cm = this.grid.colModel;
39436         var cell = this.getCell(rowIndex, colIndex);
39437         var cellText = this.getCellText(rowIndex, colIndex);
39438
39439         var p = {
39440             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
39441             id : cm.getColumnId(colIndex),
39442             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
39443         };
39444         var renderer = cm.getRenderer(colIndex);
39445         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
39446         if(typeof val == "undefined" || val === "") {
39447             val = "&#160;";
39448         }
39449         cellText.innerHTML = val;
39450         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
39451         this.syncRowHeights(rowIndex, rowIndex);
39452     },
39453
39454     calcColumnWidth : function(colIndex, maxRowsToMeasure){
39455         var maxWidth = 0;
39456         if(this.grid.autoSizeHeaders){
39457             var h = this.getHeaderCellMeasure(colIndex);
39458             maxWidth = Math.max(maxWidth, h.scrollWidth);
39459         }
39460         var tb, index;
39461         if(this.cm.isLocked(colIndex)){
39462             tb = this.getLockedTable();
39463             index = colIndex;
39464         }else{
39465             tb = this.getBodyTable();
39466             index = colIndex - this.cm.getLockedCount();
39467         }
39468         if(tb && tb.rows){
39469             var rows = tb.rows;
39470             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
39471             for(var i = 0; i < stopIndex; i++){
39472                 var cell = rows[i].childNodes[index].firstChild;
39473                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
39474             }
39475         }
39476         return maxWidth + /*margin for error in IE*/ 5;
39477     },
39478     /**
39479      * Autofit a column to its content.
39480      * @param {Number} colIndex
39481      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
39482      */
39483      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
39484          if(this.cm.isHidden(colIndex)){
39485              return; // can't calc a hidden column
39486          }
39487         if(forceMinSize){
39488             var cid = this.cm.getColumnId(colIndex);
39489             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
39490            if(this.grid.autoSizeHeaders){
39491                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
39492            }
39493         }
39494         var newWidth = this.calcColumnWidth(colIndex);
39495         this.cm.setColumnWidth(colIndex,
39496             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
39497         if(!suppressEvent){
39498             this.grid.fireEvent("columnresize", colIndex, newWidth);
39499         }
39500     },
39501
39502     /**
39503      * Autofits all columns to their content and then expands to fit any extra space in the grid
39504      */
39505      autoSizeColumns : function(){
39506         var cm = this.grid.colModel;
39507         var colCount = cm.getColumnCount();
39508         for(var i = 0; i < colCount; i++){
39509             this.autoSizeColumn(i, true, true);
39510         }
39511         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
39512             this.fitColumns();
39513         }else{
39514             this.updateColumns();
39515             this.layout();
39516         }
39517     },
39518
39519     /**
39520      * Autofits all columns to the grid's width proportionate with their current size
39521      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
39522      */
39523     fitColumns : function(reserveScrollSpace){
39524         var cm = this.grid.colModel;
39525         var colCount = cm.getColumnCount();
39526         var cols = [];
39527         var width = 0;
39528         var i, w;
39529         for (i = 0; i < colCount; i++){
39530             if(!cm.isHidden(i) && !cm.isFixed(i)){
39531                 w = cm.getColumnWidth(i);
39532                 cols.push(i);
39533                 cols.push(w);
39534                 width += w;
39535             }
39536         }
39537         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
39538         if(reserveScrollSpace){
39539             avail -= 17;
39540         }
39541         var frac = (avail - cm.getTotalWidth())/width;
39542         while (cols.length){
39543             w = cols.pop();
39544             i = cols.pop();
39545             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
39546         }
39547         this.updateColumns();
39548         this.layout();
39549     },
39550
39551     onRowSelect : function(rowIndex){
39552         var row = this.getRowComposite(rowIndex);
39553         row.addClass("x-grid-row-selected");
39554     },
39555
39556     onRowDeselect : function(rowIndex){
39557         var row = this.getRowComposite(rowIndex);
39558         row.removeClass("x-grid-row-selected");
39559     },
39560
39561     onCellSelect : function(row, col){
39562         var cell = this.getCell(row, col);
39563         if(cell){
39564             Roo.fly(cell).addClass("x-grid-cell-selected");
39565         }
39566     },
39567
39568     onCellDeselect : function(row, col){
39569         var cell = this.getCell(row, col);
39570         if(cell){
39571             Roo.fly(cell).removeClass("x-grid-cell-selected");
39572         }
39573     },
39574
39575     updateHeaderSortState : function(){
39576         
39577         // sort state can be single { field: xxx, direction : yyy}
39578         // or   { xxx=>ASC , yyy : DESC ..... }
39579         
39580         var mstate = {};
39581         if (!this.ds.multiSort) { 
39582             var state = this.ds.getSortState();
39583             if(!state){
39584                 return;
39585             }
39586             mstate[state.field] = state.direction;
39587             // FIXME... - this is not used here.. but might be elsewhere..
39588             this.sortState = state;
39589             
39590         } else {
39591             mstate = this.ds.sortToggle;
39592         }
39593         //remove existing sort classes..
39594         
39595         var sc = this.sortClasses;
39596         var hds = this.el.select(this.headerSelector).removeClass(sc);
39597         
39598         for(var f in mstate) {
39599         
39600             var sortColumn = this.cm.findColumnIndex(f);
39601             
39602             if(sortColumn != -1){
39603                 var sortDir = mstate[f];        
39604                 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
39605             }
39606         }
39607         
39608          
39609         
39610     },
39611
39612
39613     handleHeaderClick : function(g, index,e){
39614         
39615         Roo.log("header click");
39616         
39617         if (Roo.isTouch) {
39618             // touch events on header are handled by context
39619             this.handleHdCtx(g,index,e);
39620             return;
39621         }
39622         
39623         
39624         if(this.headersDisabled){
39625             return;
39626         }
39627         var dm = g.dataSource, cm = g.colModel;
39628         if(!cm.isSortable(index)){
39629             return;
39630         }
39631         g.stopEditing();
39632         
39633         if (dm.multiSort) {
39634             // update the sortOrder
39635             var so = [];
39636             for(var i = 0; i < cm.config.length; i++ ) {
39637                 
39638                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
39639                     continue; // dont' bother, it's not in sort list or being set.
39640                 }
39641                 
39642                 so.push(cm.config[i].dataIndex);
39643             };
39644             dm.sortOrder = so;
39645         }
39646         
39647         
39648         dm.sort(cm.getDataIndex(index));
39649     },
39650
39651
39652     destroy : function(){
39653         if(this.colMenu){
39654             this.colMenu.removeAll();
39655             Roo.menu.MenuMgr.unregister(this.colMenu);
39656             this.colMenu.getEl().remove();
39657             delete this.colMenu;
39658         }
39659         if(this.hmenu){
39660             this.hmenu.removeAll();
39661             Roo.menu.MenuMgr.unregister(this.hmenu);
39662             this.hmenu.getEl().remove();
39663             delete this.hmenu;
39664         }
39665         if(this.grid.enableColumnMove){
39666             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
39667             if(dds){
39668                 for(var dd in dds){
39669                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
39670                         var elid = dds[dd].dragElId;
39671                         dds[dd].unreg();
39672                         Roo.get(elid).remove();
39673                     } else if(dds[dd].config.isTarget){
39674                         dds[dd].proxyTop.remove();
39675                         dds[dd].proxyBottom.remove();
39676                         dds[dd].unreg();
39677                     }
39678                     if(Roo.dd.DDM.locationCache[dd]){
39679                         delete Roo.dd.DDM.locationCache[dd];
39680                     }
39681                 }
39682                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
39683             }
39684         }
39685         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
39686         this.bind(null, null);
39687         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
39688     },
39689
39690     handleLockChange : function(){
39691         this.refresh(true);
39692     },
39693
39694     onDenyColumnLock : function(){
39695
39696     },
39697
39698     onDenyColumnHide : function(){
39699
39700     },
39701
39702     handleHdMenuClick : function(item){
39703         var index = this.hdCtxIndex;
39704         var cm = this.cm, ds = this.ds;
39705         switch(item.id){
39706             case "asc":
39707                 ds.sort(cm.getDataIndex(index), "ASC");
39708                 break;
39709             case "desc":
39710                 ds.sort(cm.getDataIndex(index), "DESC");
39711                 break;
39712             case "lock":
39713                 var lc = cm.getLockedCount();
39714                 if(cm.getColumnCount(true) <= lc+1){
39715                     this.onDenyColumnLock();
39716                     return;
39717                 }
39718                 if(lc != index){
39719                     cm.setLocked(index, true, true);
39720                     cm.moveColumn(index, lc);
39721                     this.grid.fireEvent("columnmove", index, lc);
39722                 }else{
39723                     cm.setLocked(index, true);
39724                 }
39725             break;
39726             case "unlock":
39727                 var lc = cm.getLockedCount();
39728                 if((lc-1) != index){
39729                     cm.setLocked(index, false, true);
39730                     cm.moveColumn(index, lc-1);
39731                     this.grid.fireEvent("columnmove", index, lc-1);
39732                 }else{
39733                     cm.setLocked(index, false);
39734                 }
39735             break;
39736             case 'wider': // used to expand cols on touch..
39737             case 'narrow':
39738                 var cw = cm.getColumnWidth(index);
39739                 cw += (item.id == 'wider' ? 1 : -1) * 50;
39740                 cw = Math.max(0, cw);
39741                 cw = Math.min(cw,4000);
39742                 cm.setColumnWidth(index, cw);
39743                 break;
39744                 
39745             default:
39746                 index = cm.getIndexById(item.id.substr(4));
39747                 if(index != -1){
39748                     if(item.checked && cm.getColumnCount(true) <= 1){
39749                         this.onDenyColumnHide();
39750                         return false;
39751                     }
39752                     cm.setHidden(index, item.checked);
39753                 }
39754         }
39755         return true;
39756     },
39757
39758     beforeColMenuShow : function(){
39759         var cm = this.cm,  colCount = cm.getColumnCount();
39760         this.colMenu.removeAll();
39761         
39762         var items = [];
39763         for(var i = 0; i < colCount; i++){
39764             items.push({
39765                 id: "col-"+cm.getColumnId(i),
39766                 text: cm.getColumnHeader(i),
39767                 checked: !cm.isHidden(i),
39768                 hideOnClick:false
39769             });
39770         }
39771         
39772         if (this.grid.sortColMenu) {
39773             items.sort(function(a,b) {
39774                 if (a.text == b.text) {
39775                     return 0;
39776                 }
39777                 return a.text.toUpperCase() > b.text.toUpperCase() ? 1 : -1;
39778             });
39779         }
39780         
39781         for(var i = 0; i < colCount; i++){
39782             this.colMenu.add(new Roo.menu.CheckItem(items[i]));
39783         }
39784     },
39785
39786     handleHdCtx : function(g, index, e){
39787         e.stopEvent();
39788         var hd = this.getHeaderCell(index);
39789         this.hdCtxIndex = index;
39790         var ms = this.hmenu.items, cm = this.cm;
39791         ms.get("asc").setDisabled(!cm.isSortable(index));
39792         ms.get("desc").setDisabled(!cm.isSortable(index));
39793         if(this.grid.enableColLock !== false){
39794             ms.get("lock").setDisabled(cm.isLocked(index));
39795             ms.get("unlock").setDisabled(!cm.isLocked(index));
39796         }
39797         this.hmenu.show(hd, "tl-bl");
39798     },
39799
39800     handleHdOver : function(e){
39801         var hd = this.findHeaderCell(e.getTarget());
39802         if(hd && !this.headersDisabled){
39803             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
39804                this.fly(hd).addClass("x-grid-hd-over");
39805             }
39806         }
39807     },
39808
39809     handleHdOut : function(e){
39810         var hd = this.findHeaderCell(e.getTarget());
39811         if(hd){
39812             this.fly(hd).removeClass("x-grid-hd-over");
39813         }
39814     },
39815
39816     handleSplitDblClick : function(e, t){
39817         var i = this.getCellIndex(t);
39818         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
39819             this.autoSizeColumn(i, true);
39820             this.layout();
39821         }
39822     },
39823
39824     render : function(){
39825
39826         var cm = this.cm;
39827         var colCount = cm.getColumnCount();
39828
39829         if(this.grid.monitorWindowResize === true){
39830             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
39831         }
39832         var header = this.renderHeaders();
39833         var body = this.templates.body.apply({rows:""});
39834         var html = this.templates.master.apply({
39835             lockedBody: body,
39836             body: body,
39837             lockedHeader: header[0],
39838             header: header[1]
39839         });
39840
39841         //this.updateColumns();
39842
39843         this.grid.getGridEl().dom.innerHTML = html;
39844
39845         this.initElements();
39846         
39847         // a kludge to fix the random scolling effect in webkit
39848         this.el.on("scroll", function() {
39849             this.el.dom.scrollTop=0; // hopefully not recursive..
39850         },this);
39851
39852         this.scroller.on("scroll", this.handleScroll, this);
39853         this.lockedBody.on("mousewheel", this.handleWheel, this);
39854         this.mainBody.on("mousewheel", this.handleWheel, this);
39855
39856         this.mainHd.on("mouseover", this.handleHdOver, this);
39857         this.mainHd.on("mouseout", this.handleHdOut, this);
39858         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
39859                 {delegate: "."+this.splitClass});
39860
39861         this.lockedHd.on("mouseover", this.handleHdOver, this);
39862         this.lockedHd.on("mouseout", this.handleHdOut, this);
39863         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
39864                 {delegate: "."+this.splitClass});
39865
39866         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
39867             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
39868         }
39869
39870         this.updateSplitters();
39871
39872         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
39873             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
39874             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
39875         }
39876
39877         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
39878             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
39879             this.hmenu.add(
39880                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
39881                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
39882             );
39883             if(this.grid.enableColLock !== false){
39884                 this.hmenu.add('-',
39885                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
39886                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
39887                 );
39888             }
39889             if (Roo.isTouch) {
39890                  this.hmenu.add('-',
39891                     {id:"wider", text: this.columnsWiderText},
39892                     {id:"narrow", text: this.columnsNarrowText }
39893                 );
39894                 
39895                  
39896             }
39897             
39898             if(this.grid.enableColumnHide !== false){
39899
39900                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
39901                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
39902                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
39903
39904                 this.hmenu.add('-',
39905                     {id:"columns", text: this.columnsText, menu: this.colMenu}
39906                 );
39907             }
39908             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
39909
39910             this.grid.on("headercontextmenu", this.handleHdCtx, this);
39911         }
39912
39913         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
39914             this.dd = new Roo.grid.GridDragZone(this.grid, {
39915                 ddGroup : this.grid.ddGroup || 'GridDD'
39916             });
39917             
39918         }
39919
39920         /*
39921         for(var i = 0; i < colCount; i++){
39922             if(cm.isHidden(i)){
39923                 this.hideColumn(i);
39924             }
39925             if(cm.config[i].align){
39926                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
39927                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
39928             }
39929         }*/
39930         
39931         this.updateHeaderSortState();
39932
39933         this.beforeInitialResize();
39934         this.layout(true);
39935
39936         // two part rendering gives faster view to the user
39937         this.renderPhase2.defer(1, this);
39938     },
39939
39940     renderPhase2 : function(){
39941         // render the rows now
39942         this.refresh();
39943         if(this.grid.autoSizeColumns){
39944             this.autoSizeColumns();
39945         }
39946     },
39947
39948     beforeInitialResize : function(){
39949
39950     },
39951
39952     onColumnSplitterMoved : function(i, w){
39953         this.userResized = true;
39954         var cm = this.grid.colModel;
39955         cm.setColumnWidth(i, w, true);
39956         var cid = cm.getColumnId(i);
39957         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
39958         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
39959         this.updateSplitters();
39960         this.layout();
39961         this.grid.fireEvent("columnresize", i, w);
39962     },
39963
39964     syncRowHeights : function(startIndex, endIndex){
39965         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
39966             startIndex = startIndex || 0;
39967             var mrows = this.getBodyTable().rows;
39968             var lrows = this.getLockedTable().rows;
39969             var len = mrows.length-1;
39970             endIndex = Math.min(endIndex || len, len);
39971             for(var i = startIndex; i <= endIndex; i++){
39972                 var m = mrows[i], l = lrows[i];
39973                 var h = Math.max(m.offsetHeight, l.offsetHeight);
39974                 m.style.height = l.style.height = h + "px";
39975             }
39976         }
39977     },
39978
39979     layout : function(initialRender, is2ndPass)
39980     {
39981         var g = this.grid;
39982         var auto = g.autoHeight;
39983         var scrollOffset = 16;
39984         var c = g.getGridEl(), cm = this.cm,
39985                 expandCol = g.autoExpandColumn,
39986                 gv = this;
39987         //c.beginMeasure();
39988
39989         if(!c.dom.offsetWidth){ // display:none?
39990             if(initialRender){
39991                 this.lockedWrap.show();
39992                 this.mainWrap.show();
39993             }
39994             return;
39995         }
39996
39997         var hasLock = this.cm.isLocked(0);
39998
39999         var tbh = this.headerPanel.getHeight();
40000         var bbh = this.footerPanel.getHeight();
40001
40002         if(auto){
40003             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
40004             var newHeight = ch + c.getBorderWidth("tb");
40005             if(g.maxHeight){
40006                 newHeight = Math.min(g.maxHeight, newHeight);
40007             }
40008             c.setHeight(newHeight);
40009         }
40010
40011         if(g.autoWidth){
40012             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
40013         }
40014
40015         var s = this.scroller;
40016
40017         var csize = c.getSize(true);
40018
40019         this.el.setSize(csize.width, csize.height);
40020
40021         this.headerPanel.setWidth(csize.width);
40022         this.footerPanel.setWidth(csize.width);
40023
40024         var hdHeight = this.mainHd.getHeight();
40025         var vw = csize.width;
40026         var vh = csize.height - (tbh + bbh);
40027
40028         s.setSize(vw, vh);
40029
40030         var bt = this.getBodyTable();
40031         
40032         if(cm.getLockedCount() == cm.config.length){
40033             bt = this.getLockedTable();
40034         }
40035         
40036         var ltWidth = hasLock ?
40037                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
40038
40039         var scrollHeight = bt.offsetHeight;
40040         var scrollWidth = ltWidth + bt.offsetWidth;
40041         var vscroll = false, hscroll = false;
40042
40043         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
40044
40045         var lw = this.lockedWrap, mw = this.mainWrap;
40046         var lb = this.lockedBody, mb = this.mainBody;
40047
40048         setTimeout(function(){
40049             var t = s.dom.offsetTop;
40050             var w = s.dom.clientWidth,
40051                 h = s.dom.clientHeight;
40052
40053             lw.setTop(t);
40054             lw.setSize(ltWidth, h);
40055
40056             mw.setLeftTop(ltWidth, t);
40057             mw.setSize(w-ltWidth, h);
40058
40059             lb.setHeight(h-hdHeight);
40060             mb.setHeight(h-hdHeight);
40061
40062             if(is2ndPass !== true && !gv.userResized && expandCol){
40063                 // high speed resize without full column calculation
40064                 
40065                 var ci = cm.getIndexById(expandCol);
40066                 if (ci < 0) {
40067                     ci = cm.findColumnIndex(expandCol);
40068                 }
40069                 ci = Math.max(0, ci); // make sure it's got at least the first col.
40070                 var expandId = cm.getColumnId(ci);
40071                 var  tw = cm.getTotalWidth(false);
40072                 var currentWidth = cm.getColumnWidth(ci);
40073                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
40074                 if(currentWidth != cw){
40075                     cm.setColumnWidth(ci, cw, true);
40076                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
40077                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
40078                     gv.updateSplitters();
40079                     gv.layout(false, true);
40080                 }
40081             }
40082
40083             if(initialRender){
40084                 lw.show();
40085                 mw.show();
40086             }
40087             //c.endMeasure();
40088         }, 10);
40089     },
40090
40091     onWindowResize : function(){
40092         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
40093             return;
40094         }
40095         this.layout();
40096     },
40097
40098     appendFooter : function(parentEl){
40099         return null;
40100     },
40101
40102     sortAscText : "Sort Ascending",
40103     sortDescText : "Sort Descending",
40104     lockText : "Lock Column",
40105     unlockText : "Unlock Column",
40106     columnsText : "Columns",
40107  
40108     columnsWiderText : "Wider",
40109     columnsNarrowText : "Thinner"
40110 });
40111
40112
40113 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
40114     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
40115     this.proxy.el.addClass('x-grid3-col-dd');
40116 };
40117
40118 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
40119     handleMouseDown : function(e){
40120
40121     },
40122
40123     callHandleMouseDown : function(e){
40124         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
40125     }
40126 });
40127 /*
40128  * Based on:
40129  * Ext JS Library 1.1.1
40130  * Copyright(c) 2006-2007, Ext JS, LLC.
40131  *
40132  * Originally Released Under LGPL - original licence link has changed is not relivant.
40133  *
40134  * Fork - LGPL
40135  * <script type="text/javascript">
40136  */
40137  /**
40138  * @extends Roo.dd.DDProxy
40139  * @class Roo.grid.SplitDragZone
40140  * Support for Column Header resizing
40141  * @constructor
40142  * @param {Object} config
40143  */
40144 // private
40145 // This is a support class used internally by the Grid components
40146 Roo.grid.SplitDragZone = function(grid, hd, hd2){
40147     this.grid = grid;
40148     this.view = grid.getView();
40149     this.proxy = this.view.resizeProxy;
40150     Roo.grid.SplitDragZone.superclass.constructor.call(
40151         this,
40152         hd, // ID
40153         "gridSplitters" + this.grid.getGridEl().id, // SGROUP
40154         {  // CONFIG
40155             dragElId : Roo.id(this.proxy.dom),
40156             resizeFrame:false
40157         }
40158     );
40159     
40160     this.setHandleElId(Roo.id(hd));
40161     if (hd2 !== false) {
40162         this.setOuterHandleElId(Roo.id(hd2));
40163     }
40164     
40165     this.scroll = false;
40166 };
40167 Roo.extend(Roo.grid.SplitDragZone, Roo.dd.DDProxy, {
40168     fly: Roo.Element.fly,
40169
40170     b4StartDrag : function(x, y){
40171         this.view.headersDisabled = true;
40172         var h = this.view.mainWrap ? this.view.mainWrap.getHeight() : (
40173                     this.view.headEl.getHeight() + this.view.bodyEl.getHeight()
40174         );
40175         this.proxy.setHeight(h);
40176         
40177         // for old system colWidth really stored the actual width?
40178         // in bootstrap we tried using xs/ms/etc.. to do % sizing?
40179         // which in reality did not work.. - it worked only for fixed sizes
40180         // for resizable we need to use actual sizes.
40181         var w = this.cm.getColumnWidth(this.cellIndex);
40182         if (!this.view.mainWrap) {
40183             // bootstrap.
40184             w = this.view.getHeaderIndex(this.cellIndex).getWidth();
40185         }
40186         
40187         
40188         
40189         // this was w-this.grid.minColumnWidth;
40190         // doesnt really make sense? - w = thie curren width or the rendered one?
40191         var minw = Math.max(w-this.grid.minColumnWidth, 0);
40192         this.resetConstraints();
40193         this.setXConstraint(minw, 1000);
40194         this.setYConstraint(0, 0);
40195         this.minX = x - minw;
40196         this.maxX = x + 1000;
40197         this.startPos = x;
40198         if (!this.view.mainWrap) { // this is Bootstrap code..
40199             this.getDragEl().style.display='block';
40200         }
40201         
40202         Roo.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
40203     },
40204
40205
40206     handleMouseDown : function(e){
40207         ev = Roo.EventObject.setEvent(e);
40208         var t = this.fly(ev.getTarget());
40209         if(t.hasClass("x-grid-split")){
40210             this.cellIndex = this.view.getCellIndex(t.dom);
40211             this.split = t.dom;
40212             this.cm = this.grid.colModel;
40213             if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
40214                 Roo.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
40215             }
40216         }
40217     },
40218
40219     endDrag : function(e){
40220         this.view.headersDisabled = false;
40221         var endX = Math.max(this.minX, Roo.lib.Event.getPageX(e));
40222         var diff = endX - this.startPos;
40223         // 
40224         var w = this.cm.getColumnWidth(this.cellIndex);
40225         if (!this.view.mainWrap) {
40226             w = 0;
40227         }
40228         this.view.onColumnSplitterMoved(this.cellIndex, w+diff);
40229     },
40230
40231     autoOffset : function(){
40232         this.setDelta(0,0);
40233     }
40234 });/*
40235  * Based on:
40236  * Ext JS Library 1.1.1
40237  * Copyright(c) 2006-2007, Ext JS, LLC.
40238  *
40239  * Originally Released Under LGPL - original licence link has changed is not relivant.
40240  *
40241  * Fork - LGPL
40242  * <script type="text/javascript">
40243  */
40244  
40245 // private
40246 // This is a support class used internally by the Grid components
40247 Roo.grid.GridDragZone = function(grid, config){
40248     this.view = grid.getView();
40249     Roo.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
40250     if(this.view.lockedBody){
40251         this.setHandleElId(Roo.id(this.view.mainBody.dom));
40252         this.setOuterHandleElId(Roo.id(this.view.lockedBody.dom));
40253     }
40254     this.scroll = false;
40255     this.grid = grid;
40256     this.ddel = document.createElement('div');
40257     this.ddel.className = 'x-grid-dd-wrap';
40258 };
40259
40260 Roo.extend(Roo.grid.GridDragZone, Roo.dd.DragZone, {
40261     ddGroup : "GridDD",
40262
40263     getDragData : function(e){
40264         var t = Roo.lib.Event.getTarget(e);
40265         var rowIndex = this.view.findRowIndex(t);
40266         var sm = this.grid.selModel;
40267             
40268         //Roo.log(rowIndex);
40269         
40270         if (sm.getSelectedCell) {
40271             // cell selection..
40272             if (!sm.getSelectedCell()) {
40273                 return false;
40274             }
40275             if (rowIndex != sm.getSelectedCell()[0]) {
40276                 return false;
40277             }
40278         
40279         }
40280         if (sm.getSelections && sm.getSelections().length < 1) {
40281             return false;
40282         }
40283         
40284         
40285         // before it used to all dragging of unseleted... - now we dont do that.
40286         if(rowIndex !== false){
40287             
40288             // if editorgrid.. 
40289             
40290             
40291             //Roo.log([ sm.getSelectedCell() ? sm.getSelectedCell()[0] : 'NO' , rowIndex ]);
40292                
40293             //if(!sm.isSelected(rowIndex) || e.hasModifier()){
40294               //  
40295             //}
40296             if (e.hasModifier()){
40297                 sm.handleMouseDown(e, t); // non modifier buttons are handled by row select.
40298             }
40299             
40300             Roo.log("getDragData");
40301             
40302             return {
40303                 grid: this.grid,
40304                 ddel: this.ddel,
40305                 rowIndex: rowIndex,
40306                 selections: sm.getSelections ? sm.getSelections() : (
40307                     sm.getSelectedCell() ? [ this.grid.ds.getAt(sm.getSelectedCell()[0]) ] : [])
40308             };
40309         }
40310         return false;
40311     },
40312     
40313     
40314     onInitDrag : function(e){
40315         var data = this.dragData;
40316         this.ddel.innerHTML = this.grid.getDragDropText();
40317         this.proxy.update(this.ddel);
40318         // fire start drag?
40319     },
40320
40321     afterRepair : function(){
40322         this.dragging = false;
40323     },
40324
40325     getRepairXY : function(e, data){
40326         return false;
40327     },
40328
40329     onEndDrag : function(data, e){
40330         // fire end drag?
40331     },
40332
40333     onValidDrop : function(dd, e, id){
40334         // fire drag drop?
40335         this.hideProxy();
40336     },
40337
40338     beforeInvalidDrop : function(e, id){
40339
40340     }
40341 });/*
40342  * Based on:
40343  * Ext JS Library 1.1.1
40344  * Copyright(c) 2006-2007, Ext JS, LLC.
40345  *
40346  * Originally Released Under LGPL - original licence link has changed is not relivant.
40347  *
40348  * Fork - LGPL
40349  * <script type="text/javascript">
40350  */
40351  
40352
40353 /**
40354  * @class Roo.grid.ColumnModel
40355  * @extends Roo.util.Observable
40356  * This is the default implementation of a ColumnModel used by the Grid. It defines
40357  * the columns in the grid.
40358  * <br>Usage:<br>
40359  <pre><code>
40360  var colModel = new Roo.grid.ColumnModel([
40361         {header: "Ticker", width: 60, sortable: true, locked: true},
40362         {header: "Company Name", width: 150, sortable: true},
40363         {header: "Market Cap.", width: 100, sortable: true},
40364         {header: "$ Sales", width: 100, sortable: true, renderer: money},
40365         {header: "Employees", width: 100, sortable: true, resizable: false}
40366  ]);
40367  </code></pre>
40368  * <p>
40369  
40370  * The config options listed for this class are options which may appear in each
40371  * individual column definition.
40372  * <br/>RooJS Fix - column id's are not sequential but use Roo.id() - fixes bugs with layouts.
40373  * @constructor
40374  * @param {Object} config An Array of column config objects. See this class's
40375  * config objects for details.
40376 */
40377 Roo.grid.ColumnModel = function(config){
40378         /**
40379      * The config passed into the constructor
40380      */
40381     this.config = []; //config;
40382     this.lookup = {};
40383
40384     // if no id, create one
40385     // if the column does not have a dataIndex mapping,
40386     // map it to the order it is in the config
40387     for(var i = 0, len = config.length; i < len; i++){
40388         this.addColumn(config[i]);
40389         
40390     }
40391
40392     /**
40393      * The width of columns which have no width specified (defaults to 100)
40394      * @type Number
40395      */
40396     this.defaultWidth = 100;
40397
40398     /**
40399      * Default sortable of columns which have no sortable specified (defaults to false)
40400      * @type Boolean
40401      */
40402     this.defaultSortable = false;
40403
40404     this.addEvents({
40405         /**
40406              * @event widthchange
40407              * Fires when the width of a column changes.
40408              * @param {ColumnModel} this
40409              * @param {Number} columnIndex The column index
40410              * @param {Number} newWidth The new width
40411              */
40412             "widthchange": true,
40413         /**
40414              * @event headerchange
40415              * Fires when the text of a header changes.
40416              * @param {ColumnModel} this
40417              * @param {Number} columnIndex The column index
40418              * @param {Number} newText The new header text
40419              */
40420             "headerchange": true,
40421         /**
40422              * @event hiddenchange
40423              * Fires when a column is hidden or "unhidden".
40424              * @param {ColumnModel} this
40425              * @param {Number} columnIndex The column index
40426              * @param {Boolean} hidden true if hidden, false otherwise
40427              */
40428             "hiddenchange": true,
40429             /**
40430          * @event columnmoved
40431          * Fires when a column is moved.
40432          * @param {ColumnModel} this
40433          * @param {Number} oldIndex
40434          * @param {Number} newIndex
40435          */
40436         "columnmoved" : true,
40437         /**
40438          * @event columlockchange
40439          * Fires when a column's locked state is changed
40440          * @param {ColumnModel} this
40441          * @param {Number} colIndex
40442          * @param {Boolean} locked true if locked
40443          */
40444         "columnlockchange" : true
40445     });
40446     Roo.grid.ColumnModel.superclass.constructor.call(this);
40447 };
40448 Roo.extend(Roo.grid.ColumnModel, Roo.util.Observable, {
40449     /**
40450      * @cfg {String} header [required] The header text to display in the Grid view.
40451      */
40452         /**
40453      * @cfg {String} xsHeader Header at Bootsrap Extra Small width (default for all)
40454      */
40455         /**
40456      * @cfg {String} smHeader Header at Bootsrap Small width
40457      */
40458         /**
40459      * @cfg {String} mdHeader Header at Bootsrap Medium width
40460      */
40461         /**
40462      * @cfg {String} lgHeader Header at Bootsrap Large width
40463      */
40464         /**
40465      * @cfg {String} xlHeader Header at Bootsrap extra Large width
40466      */
40467     /**
40468      * @cfg {String} dataIndex  The name of the field in the grid's {@link Roo.data.Store}'s
40469      * {@link Roo.data.Record} definition from which to draw the column's value. If not
40470      * specified, the column's index is used as an index into the Record's data Array.
40471      */
40472     /**
40473      * @cfg {Number} width  The initial width in pixels of the column. Using this
40474      * instead of {@link Roo.grid.Grid#autoSizeColumns} is more efficient.
40475      */
40476     /**
40477      * @cfg {Boolean} sortable True if sorting is to be allowed on this column.
40478      * Defaults to the value of the {@link #defaultSortable} property.
40479      * Whether local/remote sorting is used is specified in {@link Roo.data.Store#remoteSort}.
40480      */
40481     /**
40482      * @cfg {Boolean} locked  True to lock the column in place while scrolling the Grid.  Defaults to false.
40483      */
40484     /**
40485      * @cfg {Boolean} fixed  True if the column width cannot be changed.  Defaults to false.
40486      */
40487     /**
40488      * @cfg {Boolean} resizable  False to disable column resizing. Defaults to true.
40489      */
40490     /**
40491      * @cfg {Boolean} hidden  True to hide the column. Defaults to false.
40492      */
40493     /**
40494      * @cfg {Function} renderer A function used to generate HTML markup for a cell
40495      * given the cell's data value. See {@link #setRenderer}. If not specified, the
40496      * default renderer returns the escaped data value. If an object is returned (bootstrap only)
40497      * then it is treated as a Roo Component object instance, and it is rendered after the initial row is rendered
40498      */
40499        /**
40500      * @cfg {Roo.grid.GridEditor} editor  For grid editors - returns the grid editor 
40501      */
40502     /**
40503      * @cfg {String} align (left|right) Set the CSS text-align property of the column.  Defaults to undefined (left).
40504      */
40505     /**
40506      * @cfg {String} valign (top|bottom|middle) Set the CSS vertical-align property of the column (eg. middle, top, bottom etc).  Defaults to undefined (middle)
40507      */
40508     /**
40509      * @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)
40510      */
40511     /**
40512      * @cfg {String} tooltip mouse over tooltip text
40513      */
40514     /**
40515      * @cfg {Number} xs  can be '0' for hidden at this size (number less than 12)
40516      */
40517     /**
40518      * @cfg {Number} sm can be '0' for hidden at this size (number less than 12)
40519      */
40520     /**
40521      * @cfg {Number} md can be '0' for hidden at this size (number less than 12)
40522      */
40523     /**
40524      * @cfg {Number} lg   can be '0' for hidden at this size (number less than 12)
40525      */
40526         /**
40527      * @cfg {Number} xl   can be '0' for hidden at this size (number less than 12)
40528      */
40529     /**
40530      * Returns the id of the column at the specified index.
40531      * @param {Number} index The column index
40532      * @return {String} the id
40533      */
40534     getColumnId : function(index){
40535         return this.config[index].id;
40536     },
40537
40538     /**
40539      * Returns the column for a specified id.
40540      * @param {String} id The column id
40541      * @return {Object} the column
40542      */
40543     getColumnById : function(id){
40544         return this.lookup[id];
40545     },
40546
40547     
40548     /**
40549      * Returns the column Object for a specified dataIndex.
40550      * @param {String} dataIndex The column dataIndex
40551      * @return {Object|Boolean} the column or false if not found
40552      */
40553     getColumnByDataIndex: function(dataIndex){
40554         var index = this.findColumnIndex(dataIndex);
40555         return index > -1 ? this.config[index] : false;
40556     },
40557     
40558     /**
40559      * Returns the index for a specified column id.
40560      * @param {String} id The column id
40561      * @return {Number} the index, or -1 if not found
40562      */
40563     getIndexById : function(id){
40564         for(var i = 0, len = this.config.length; i < len; i++){
40565             if(this.config[i].id == id){
40566                 return i;
40567             }
40568         }
40569         return -1;
40570     },
40571     
40572     /**
40573      * Returns the index for a specified column dataIndex.
40574      * @param {String} dataIndex The column dataIndex
40575      * @return {Number} the index, or -1 if not found
40576      */
40577     
40578     findColumnIndex : function(dataIndex){
40579         for(var i = 0, len = this.config.length; i < len; i++){
40580             if(this.config[i].dataIndex == dataIndex){
40581                 return i;
40582             }
40583         }
40584         return -1;
40585     },
40586     
40587     
40588     moveColumn : function(oldIndex, newIndex){
40589         var c = this.config[oldIndex];
40590         this.config.splice(oldIndex, 1);
40591         this.config.splice(newIndex, 0, c);
40592         this.dataMap = null;
40593         this.fireEvent("columnmoved", this, oldIndex, newIndex);
40594     },
40595
40596     isLocked : function(colIndex){
40597         return this.config[colIndex].locked === true;
40598     },
40599
40600     setLocked : function(colIndex, value, suppressEvent){
40601         if(this.isLocked(colIndex) == value){
40602             return;
40603         }
40604         this.config[colIndex].locked = value;
40605         if(!suppressEvent){
40606             this.fireEvent("columnlockchange", this, colIndex, value);
40607         }
40608     },
40609
40610     getTotalLockedWidth : function(){
40611         var totalWidth = 0;
40612         for(var i = 0; i < this.config.length; i++){
40613             if(this.isLocked(i) && !this.isHidden(i)){
40614                 this.totalWidth += this.getColumnWidth(i);
40615             }
40616         }
40617         return totalWidth;
40618     },
40619
40620     getLockedCount : function(){
40621         for(var i = 0, len = this.config.length; i < len; i++){
40622             if(!this.isLocked(i)){
40623                 return i;
40624             }
40625         }
40626         
40627         return this.config.length;
40628     },
40629
40630     /**
40631      * Returns the number of columns.
40632      * @return {Number}
40633      */
40634     getColumnCount : function(visibleOnly){
40635         if(visibleOnly === true){
40636             var c = 0;
40637             for(var i = 0, len = this.config.length; i < len; i++){
40638                 if(!this.isHidden(i)){
40639                     c++;
40640                 }
40641             }
40642             return c;
40643         }
40644         return this.config.length;
40645     },
40646
40647     /**
40648      * Returns the column configs that return true by the passed function that is called with (columnConfig, index)
40649      * @param {Function} fn
40650      * @param {Object} scope (optional)
40651      * @return {Array} result
40652      */
40653     getColumnsBy : function(fn, scope){
40654         var r = [];
40655         for(var i = 0, len = this.config.length; i < len; i++){
40656             var c = this.config[i];
40657             if(fn.call(scope||this, c, i) === true){
40658                 r[r.length] = c;
40659             }
40660         }
40661         return r;
40662     },
40663
40664     /**
40665      * Returns true if the specified column is sortable.
40666      * @param {Number} col The column index
40667      * @return {Boolean}
40668      */
40669     isSortable : function(col){
40670         if(typeof this.config[col].sortable == "undefined"){
40671             return this.defaultSortable;
40672         }
40673         return this.config[col].sortable;
40674     },
40675
40676     /**
40677      * Returns the rendering (formatting) function defined for the column.
40678      * @param {Number} col The column index.
40679      * @return {Function} The function used to render the cell. See {@link #setRenderer}.
40680      */
40681     getRenderer : function(col){
40682         if(!this.config[col].renderer){
40683             return Roo.grid.ColumnModel.defaultRenderer;
40684         }
40685         return this.config[col].renderer;
40686     },
40687
40688     /**
40689      * Sets the rendering (formatting) function for a column.
40690      * @param {Number} col The column index
40691      * @param {Function} fn The function to use to process the cell's raw data
40692      * to return HTML markup for the grid view. The render function is called with
40693      * the following parameters:<ul>
40694      * <li>Data value.</li>
40695      * <li>Cell metadata. An object in which you may set the following attributes:<ul>
40696      * <li>css A CSS style string to apply to the table cell.</li>
40697      * <li>attr An HTML attribute definition string to apply to the data container element <i>within</i> the table cell.</li></ul>
40698      * <li>The {@link Roo.data.Record} from which the data was extracted.</li>
40699      * <li>Row index</li>
40700      * <li>Column index</li>
40701      * <li>The {@link Roo.data.Store} object from which the Record was extracted</li></ul>
40702      */
40703     setRenderer : function(col, fn){
40704         this.config[col].renderer = fn;
40705     },
40706
40707     /**
40708      * Returns the width for the specified column.
40709      * @param {Number} col The column index
40710      * @param (optional) {String} gridSize bootstrap width size.
40711      * @return {Number}
40712      */
40713     getColumnWidth : function(col, gridSize)
40714         {
40715                 var cfg = this.config[col];
40716                 
40717                 if (typeof(gridSize) == 'undefined') {
40718                         return cfg.width * 1 || this.defaultWidth;
40719                 }
40720                 if (gridSize === false) { // if we set it..
40721                         return cfg.width || false;
40722                 }
40723                 var sizes = ['xl', 'lg', 'md', 'sm', 'xs'];
40724                 
40725                 for(var i = sizes.indexOf(gridSize); i < sizes.length; i++) {
40726                         if (typeof(cfg[ sizes[i] ] ) == 'undefined') {
40727                                 continue;
40728                         }
40729                         return cfg[ sizes[i] ];
40730                 }
40731                 return 1;
40732                 
40733     },
40734
40735     /**
40736      * Sets the width for a column.
40737      * @param {Number} col The column index
40738      * @param {Number} width The new width
40739      */
40740     setColumnWidth : function(col, width, suppressEvent){
40741         this.config[col].width = width;
40742         this.totalWidth = null;
40743         if(!suppressEvent){
40744              this.fireEvent("widthchange", this, col, width);
40745         }
40746     },
40747
40748     /**
40749      * Returns the total width of all columns.
40750      * @param {Boolean} includeHidden True to include hidden column widths
40751      * @return {Number}
40752      */
40753     getTotalWidth : function(includeHidden){
40754         if(!this.totalWidth){
40755             this.totalWidth = 0;
40756             for(var i = 0, len = this.config.length; i < len; i++){
40757                 if(includeHidden || !this.isHidden(i)){
40758                     this.totalWidth += this.getColumnWidth(i);
40759                 }
40760             }
40761         }
40762         return this.totalWidth;
40763     },
40764
40765     /**
40766      * Returns the header for the specified column.
40767      * @param {Number} col The column index
40768      * @return {String}
40769      */
40770     getColumnHeader : function(col){
40771         return this.config[col].header;
40772     },
40773
40774     /**
40775      * Sets the header for a column.
40776      * @param {Number} col The column index
40777      * @param {String} header The new header
40778      */
40779     setColumnHeader : function(col, header){
40780         this.config[col].header = header;
40781         this.fireEvent("headerchange", this, col, header);
40782     },
40783
40784     /**
40785      * Returns the tooltip for the specified column.
40786      * @param {Number} col The column index
40787      * @return {String}
40788      */
40789     getColumnTooltip : function(col){
40790             return this.config[col].tooltip;
40791     },
40792     /**
40793      * Sets the tooltip for a column.
40794      * @param {Number} col The column index
40795      * @param {String} tooltip The new tooltip
40796      */
40797     setColumnTooltip : function(col, tooltip){
40798             this.config[col].tooltip = tooltip;
40799     },
40800
40801     /**
40802      * Returns the dataIndex for the specified column.
40803      * @param {Number} col The column index
40804      * @return {Number}
40805      */
40806     getDataIndex : function(col){
40807         return this.config[col].dataIndex;
40808     },
40809
40810     /**
40811      * Sets the dataIndex for a column.
40812      * @param {Number} col The column index
40813      * @param {Number} dataIndex The new dataIndex
40814      */
40815     setDataIndex : function(col, dataIndex){
40816         this.config[col].dataIndex = dataIndex;
40817     },
40818
40819     
40820     
40821     /**
40822      * Returns true if the cell is editable.
40823      * @param {Number} colIndex The column index
40824      * @param {Number} rowIndex The row index - this is nto actually used..?
40825      * @return {Boolean}
40826      */
40827     isCellEditable : function(colIndex, rowIndex){
40828         return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
40829     },
40830
40831     /**
40832      * Returns the editor defined for the cell/column.
40833      * return false or null to disable editing.
40834      * @param {Number} colIndex The column index
40835      * @param {Number} rowIndex The row index
40836      * @return {Object}
40837      */
40838     getCellEditor : function(colIndex, rowIndex){
40839         return this.config[colIndex].editor;
40840     },
40841
40842     /**
40843      * Sets if a column is editable.
40844      * @param {Number} col The column index
40845      * @param {Boolean} editable True if the column is editable
40846      */
40847     setEditable : function(col, editable){
40848         this.config[col].editable = editable;
40849     },
40850
40851
40852     /**
40853      * Returns true if the column is hidden.
40854      * @param {Number} colIndex The column index
40855      * @return {Boolean}
40856      */
40857     isHidden : function(colIndex){
40858         return this.config[colIndex].hidden;
40859     },
40860
40861
40862     /**
40863      * Returns true if the column width cannot be changed
40864      */
40865     isFixed : function(colIndex){
40866         return this.config[colIndex].fixed;
40867     },
40868
40869     /**
40870      * Returns true if the column can be resized
40871      * @return {Boolean}
40872      */
40873     isResizable : function(colIndex){
40874         return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
40875     },
40876     /**
40877      * Sets if a column is hidden.
40878      * @param {Number} colIndex The column index
40879      * @param {Boolean} hidden True if the column is hidden
40880      */
40881     setHidden : function(colIndex, hidden){
40882         this.config[colIndex].hidden = hidden;
40883         this.totalWidth = null;
40884         this.fireEvent("hiddenchange", this, colIndex, hidden);
40885     },
40886
40887     /**
40888      * Sets the editor for a column.
40889      * @param {Number} col The column index
40890      * @param {Object} editor The editor object
40891      */
40892     setEditor : function(col, editor){
40893         this.config[col].editor = editor;
40894     },
40895     /**
40896      * Add a column (experimental...) - defaults to adding to the end..
40897      * @param {Object} config 
40898     */
40899     addColumn : function(c)
40900     {
40901     
40902         var i = this.config.length;
40903         this.config[i] = c;
40904         
40905         if(typeof c.dataIndex == "undefined"){
40906             c.dataIndex = i;
40907         }
40908         if(typeof c.renderer == "string"){
40909             c.renderer = Roo.util.Format[c.renderer];
40910         }
40911         if(typeof c.id == "undefined"){
40912             c.id = Roo.id();
40913         }
40914         if(c.editor && c.editor.xtype){
40915             c.editor  = Roo.factory(c.editor, Roo.grid);
40916         }
40917         if(c.editor && c.editor.isFormField){
40918             c.editor = new Roo.grid.GridEditor(c.editor);
40919         }
40920         this.lookup[c.id] = c;
40921     }
40922     
40923 });
40924
40925 Roo.grid.ColumnModel.defaultRenderer = function(value)
40926 {
40927     if(typeof value == "object") {
40928         return value;
40929     }
40930         if(typeof value == "string" && value.length < 1){
40931             return "&#160;";
40932         }
40933     
40934         return String.format("{0}", value);
40935 };
40936
40937 // Alias for backwards compatibility
40938 Roo.grid.DefaultColumnModel = Roo.grid.ColumnModel;
40939 /*
40940  * Based on:
40941  * Ext JS Library 1.1.1
40942  * Copyright(c) 2006-2007, Ext JS, LLC.
40943  *
40944  * Originally Released Under LGPL - original licence link has changed is not relivant.
40945  *
40946  * Fork - LGPL
40947  * <script type="text/javascript">
40948  */
40949
40950 /**
40951  * @class Roo.grid.AbstractSelectionModel
40952  * @extends Roo.util.Observable
40953  * @abstract
40954  * Abstract base class for grid SelectionModels.  It provides the interface that should be
40955  * implemented by descendant classes.  This class should not be directly instantiated.
40956  * @constructor
40957  */
40958 Roo.grid.AbstractSelectionModel = function(){
40959     this.locked = false;
40960     Roo.grid.AbstractSelectionModel.superclass.constructor.call(this);
40961 };
40962
40963 Roo.extend(Roo.grid.AbstractSelectionModel, Roo.util.Observable,  {
40964     /** @ignore Called by the grid automatically. Do not call directly. */
40965     init : function(grid){
40966         this.grid = grid;
40967         this.initEvents();
40968     },
40969
40970     /**
40971      * Locks the selections.
40972      */
40973     lock : function(){
40974         this.locked = true;
40975     },
40976
40977     /**
40978      * Unlocks the selections.
40979      */
40980     unlock : function(){
40981         this.locked = false;
40982     },
40983
40984     /**
40985      * Returns true if the selections are locked.
40986      * @return {Boolean}
40987      */
40988     isLocked : function(){
40989         return this.locked;
40990     }
40991 });/*
40992  * Based on:
40993  * Ext JS Library 1.1.1
40994  * Copyright(c) 2006-2007, Ext JS, LLC.
40995  *
40996  * Originally Released Under LGPL - original licence link has changed is not relivant.
40997  *
40998  * Fork - LGPL
40999  * <script type="text/javascript">
41000  */
41001 /**
41002  * @extends Roo.grid.AbstractSelectionModel
41003  * @class Roo.grid.RowSelectionModel
41004  * The default SelectionModel used by {@link Roo.grid.Grid}.
41005  * It supports multiple selections and keyboard selection/navigation. 
41006  * @constructor
41007  * @param {Object} config
41008  */
41009 Roo.grid.RowSelectionModel = function(config){
41010     Roo.apply(this, config);
41011     this.selections = new Roo.util.MixedCollection(false, function(o){
41012         return o.id;
41013     });
41014
41015     this.last = false;
41016     this.lastActive = false;
41017
41018     this.addEvents({
41019         /**
41020         * @event selectionchange
41021         * Fires when the selection changes
41022         * @param {SelectionModel} this
41023         */
41024        "selectionchange" : true,
41025        /**
41026         * @event afterselectionchange
41027         * Fires after the selection changes (eg. by key press or clicking)
41028         * @param {SelectionModel} this
41029         */
41030        "afterselectionchange" : true,
41031        /**
41032         * @event beforerowselect
41033         * Fires when a row is selected being selected, return false to cancel.
41034         * @param {SelectionModel} this
41035         * @param {Number} rowIndex The selected index
41036         * @param {Boolean} keepExisting False if other selections will be cleared
41037         */
41038        "beforerowselect" : true,
41039        /**
41040         * @event rowselect
41041         * Fires when a row is selected.
41042         * @param {SelectionModel} this
41043         * @param {Number} rowIndex The selected index
41044         * @param {Roo.data.Record} r The record
41045         */
41046        "rowselect" : true,
41047        /**
41048         * @event rowdeselect
41049         * Fires when a row is deselected.
41050         * @param {SelectionModel} this
41051         * @param {Number} rowIndex The selected index
41052         */
41053         "rowdeselect" : true
41054     });
41055     Roo.grid.RowSelectionModel.superclass.constructor.call(this);
41056     this.locked = false;
41057 };
41058
41059 Roo.extend(Roo.grid.RowSelectionModel, Roo.grid.AbstractSelectionModel,  {
41060     /**
41061      * @cfg {Boolean} singleSelect
41062      * True to allow selection of only one row at a time (defaults to false)
41063      */
41064     singleSelect : false,
41065
41066     // private
41067     initEvents : function(){
41068
41069         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
41070             this.grid.on("mousedown", this.handleMouseDown, this);
41071         }else{ // allow click to work like normal
41072             this.grid.on("rowclick", this.handleDragableRowClick, this);
41073         }
41074         // bootstrap does not have a view..
41075         var view = this.grid.view ? this.grid.view : this.grid;
41076         this.rowNav = new Roo.KeyNav(this.grid.getGridEl(), {
41077             "up" : function(e){
41078                 if(!e.shiftKey){
41079                     this.selectPrevious(e.shiftKey);
41080                 }else if(this.last !== false && this.lastActive !== false){
41081                     var last = this.last;
41082                     this.selectRange(this.last,  this.lastActive-1);
41083                     view.focusRow(this.lastActive);
41084                     if(last !== false){
41085                         this.last = last;
41086                     }
41087                 }else{
41088                     this.selectFirstRow();
41089                 }
41090                 this.fireEvent("afterselectionchange", this);
41091             },
41092             "down" : function(e){
41093                 if(!e.shiftKey){
41094                     this.selectNext(e.shiftKey);
41095                 }else if(this.last !== false && this.lastActive !== false){
41096                     var last = this.last;
41097                     this.selectRange(this.last,  this.lastActive+1);
41098                     view.focusRow(this.lastActive);
41099                     if(last !== false){
41100                         this.last = last;
41101                     }
41102                 }else{
41103                     this.selectFirstRow();
41104                 }
41105                 this.fireEvent("afterselectionchange", this);
41106             },
41107             scope: this
41108         });
41109
41110          
41111         view.on("refresh", this.onRefresh, this);
41112         view.on("rowupdated", this.onRowUpdated, this);
41113         view.on("rowremoved", this.onRemove, this);
41114     },
41115
41116     // private
41117     onRefresh : function(){
41118         var ds = this.grid.ds, i, v = this.grid.view;
41119         var s = this.selections;
41120         s.each(function(r){
41121             if((i = ds.indexOfId(r.id)) != -1){
41122                 v.onRowSelect(i);
41123                 s.add(ds.getAt(i)); // updating the selection relate data
41124             }else{
41125                 s.remove(r);
41126             }
41127         });
41128     },
41129
41130     // private
41131     onRemove : function(v, index, r){
41132         this.selections.remove(r);
41133     },
41134
41135     // private
41136     onRowUpdated : function(v, index, r){
41137         if(this.isSelected(r)){
41138             v.onRowSelect(index);
41139         }
41140     },
41141
41142     /**
41143      * Select records.
41144      * @param {Array} records The records to select
41145      * @param {Boolean} keepExisting (optional) True to keep existing selections
41146      */
41147     selectRecords : function(records, keepExisting){
41148         if(!keepExisting){
41149             this.clearSelections();
41150         }
41151         var ds = this.grid.ds;
41152         for(var i = 0, len = records.length; i < len; i++){
41153             this.selectRow(ds.indexOf(records[i]), true);
41154         }
41155     },
41156
41157     /**
41158      * Gets the number of selected rows.
41159      * @return {Number}
41160      */
41161     getCount : function(){
41162         return this.selections.length;
41163     },
41164
41165     /**
41166      * Selects the first row in the grid.
41167      */
41168     selectFirstRow : function(){
41169         this.selectRow(0);
41170     },
41171
41172     /**
41173      * Select the last row.
41174      * @param {Boolean} keepExisting (optional) True to keep existing selections
41175      */
41176     selectLastRow : function(keepExisting){
41177         this.selectRow(this.grid.ds.getCount() - 1, keepExisting);
41178     },
41179
41180     /**
41181      * Selects the row immediately following the last selected row.
41182      * @param {Boolean} keepExisting (optional) True to keep existing selections
41183      */
41184     selectNext : function(keepExisting){
41185         if(this.last !== false && (this.last+1) < this.grid.ds.getCount()){
41186             this.selectRow(this.last+1, keepExisting);
41187             var view = this.grid.view ? this.grid.view : this.grid;
41188             view.focusRow(this.last);
41189         }
41190     },
41191
41192     /**
41193      * Selects the row that precedes the last selected row.
41194      * @param {Boolean} keepExisting (optional) True to keep existing selections
41195      */
41196     selectPrevious : function(keepExisting){
41197         if(this.last){
41198             this.selectRow(this.last-1, keepExisting);
41199             var view = this.grid.view ? this.grid.view : this.grid;
41200             view.focusRow(this.last);
41201         }
41202     },
41203
41204     /**
41205      * Returns the selected records
41206      * @return {Array} Array of selected records
41207      */
41208     getSelections : function(){
41209         return [].concat(this.selections.items);
41210     },
41211
41212     /**
41213      * Returns the first selected record.
41214      * @return {Record}
41215      */
41216     getSelected : function(){
41217         return this.selections.itemAt(0);
41218     },
41219
41220
41221     /**
41222      * Clears all selections.
41223      */
41224     clearSelections : function(fast){
41225         if(this.locked) {
41226             return;
41227         }
41228         if(fast !== true){
41229             var ds = this.grid.ds;
41230             var s = this.selections;
41231             s.each(function(r){
41232                 this.deselectRow(ds.indexOfId(r.id));
41233             }, this);
41234             s.clear();
41235         }else{
41236             this.selections.clear();
41237         }
41238         this.last = false;
41239     },
41240
41241
41242     /**
41243      * Selects all rows.
41244      */
41245     selectAll : function(){
41246         if(this.locked) {
41247             return;
41248         }
41249         this.selections.clear();
41250         for(var i = 0, len = this.grid.ds.getCount(); i < len; i++){
41251             this.selectRow(i, true);
41252         }
41253     },
41254
41255     /**
41256      * Returns True if there is a selection.
41257      * @return {Boolean}
41258      */
41259     hasSelection : function(){
41260         return this.selections.length > 0;
41261     },
41262
41263     /**
41264      * Returns True if the specified row is selected.
41265      * @param {Number/Record} record The record or index of the record to check
41266      * @return {Boolean}
41267      */
41268     isSelected : function(index){
41269         var r = typeof index == "number" ? this.grid.ds.getAt(index) : index;
41270         return (r && this.selections.key(r.id) ? true : false);
41271     },
41272
41273     /**
41274      * Returns True if the specified record id is selected.
41275      * @param {String} id The id of record to check
41276      * @return {Boolean}
41277      */
41278     isIdSelected : function(id){
41279         return (this.selections.key(id) ? true : false);
41280     },
41281
41282     // private
41283     handleMouseDown : function(e, t)
41284     {
41285         var view = this.grid.view ? this.grid.view : this.grid;
41286         var rowIndex;
41287         if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){
41288             return;
41289         };
41290         if(e.shiftKey && this.last !== false){
41291             var last = this.last;
41292             this.selectRange(last, rowIndex, e.ctrlKey);
41293             this.last = last; // reset the last
41294             view.focusRow(rowIndex);
41295         }else{
41296             var isSelected = this.isSelected(rowIndex);
41297             if(e.button !== 0 && isSelected){
41298                 view.focusRow(rowIndex);
41299             }else if(e.ctrlKey && isSelected){
41300                 this.deselectRow(rowIndex);
41301             }else if(!isSelected){
41302                 this.selectRow(rowIndex, e.button === 0 && (e.ctrlKey || e.shiftKey));
41303                 view.focusRow(rowIndex);
41304             }
41305         }
41306         this.fireEvent("afterselectionchange", this);
41307     },
41308     // private
41309     handleDragableRowClick :  function(grid, rowIndex, e) 
41310     {
41311         if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
41312             this.selectRow(rowIndex, false);
41313             var view = this.grid.view ? this.grid.view : this.grid;
41314             view.focusRow(rowIndex);
41315              this.fireEvent("afterselectionchange", this);
41316         }
41317     },
41318     
41319     /**
41320      * Selects multiple rows.
41321      * @param {Array} rows Array of the indexes of the row to select
41322      * @param {Boolean} keepExisting (optional) True to keep existing selections
41323      */
41324     selectRows : function(rows, keepExisting){
41325         if(!keepExisting){
41326             this.clearSelections();
41327         }
41328         for(var i = 0, len = rows.length; i < len; i++){
41329             this.selectRow(rows[i], true);
41330         }
41331     },
41332
41333     /**
41334      * Selects a range of rows. All rows in between startRow and endRow are also selected.
41335      * @param {Number} startRow The index of the first row in the range
41336      * @param {Number} endRow The index of the last row in the range
41337      * @param {Boolean} keepExisting (optional) True to retain existing selections
41338      */
41339     selectRange : function(startRow, endRow, keepExisting){
41340         if(this.locked) {
41341             return;
41342         }
41343         if(!keepExisting){
41344             this.clearSelections();
41345         }
41346         if(startRow <= endRow){
41347             for(var i = startRow; i <= endRow; i++){
41348                 this.selectRow(i, true);
41349             }
41350         }else{
41351             for(var i = startRow; i >= endRow; i--){
41352                 this.selectRow(i, true);
41353             }
41354         }
41355     },
41356
41357     /**
41358      * Deselects a range of rows. All rows in between startRow and endRow are also deselected.
41359      * @param {Number} startRow The index of the first row in the range
41360      * @param {Number} endRow The index of the last row in the range
41361      */
41362     deselectRange : function(startRow, endRow, preventViewNotify){
41363         if(this.locked) {
41364             return;
41365         }
41366         for(var i = startRow; i <= endRow; i++){
41367             this.deselectRow(i, preventViewNotify);
41368         }
41369     },
41370
41371     /**
41372      * Selects a row.
41373      * @param {Number} row The index of the row to select
41374      * @param {Boolean} keepExisting (optional) True to keep existing selections
41375      */
41376     selectRow : function(index, keepExisting, preventViewNotify){
41377         if(this.locked || (index < 0 || index >= this.grid.ds.getCount())) {
41378             return;
41379         }
41380         if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){
41381             if(!keepExisting || this.singleSelect){
41382                 this.clearSelections();
41383             }
41384             var r = this.grid.ds.getAt(index);
41385             this.selections.add(r);
41386             this.last = this.lastActive = index;
41387             if(!preventViewNotify){
41388                 var view = this.grid.view ? this.grid.view : this.grid;
41389                 view.onRowSelect(index);
41390             }
41391             this.fireEvent("rowselect", this, index, r);
41392             this.fireEvent("selectionchange", this);
41393         }
41394     },
41395
41396     /**
41397      * Deselects a row.
41398      * @param {Number} row The index of the row to deselect
41399      */
41400     deselectRow : function(index, preventViewNotify){
41401         if(this.locked) {
41402             return;
41403         }
41404         if(this.last == index){
41405             this.last = false;
41406         }
41407         if(this.lastActive == index){
41408             this.lastActive = false;
41409         }
41410         var r = this.grid.ds.getAt(index);
41411         this.selections.remove(r);
41412         if(!preventViewNotify){
41413             var view = this.grid.view ? this.grid.view : this.grid;
41414             view.onRowDeselect(index);
41415         }
41416         this.fireEvent("rowdeselect", this, index);
41417         this.fireEvent("selectionchange", this);
41418     },
41419
41420     // private
41421     restoreLast : function(){
41422         if(this._last){
41423             this.last = this._last;
41424         }
41425     },
41426
41427     // private
41428     acceptsNav : function(row, col, cm){
41429         return !cm.isHidden(col) && cm.isCellEditable(col, row);
41430     },
41431
41432     // private
41433     onEditorKey : function(field, e){
41434         var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
41435         if(k == e.TAB){
41436             e.stopEvent();
41437             ed.completeEdit();
41438             if(e.shiftKey){
41439                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
41440             }else{
41441                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
41442             }
41443         }else if(k == e.ENTER && !e.ctrlKey){
41444             e.stopEvent();
41445             ed.completeEdit();
41446             if(e.shiftKey){
41447                 newCell = g.walkCells(ed.row-1, ed.col, -1, this.acceptsNav, this);
41448             }else{
41449                 newCell = g.walkCells(ed.row+1, ed.col, 1, this.acceptsNav, this);
41450             }
41451         }else if(k == e.ESC){
41452             ed.cancelEdit();
41453         }
41454         if(newCell){
41455             g.startEditing(newCell[0], newCell[1]);
41456         }
41457     }
41458 });/*
41459  * Based on:
41460  * Ext JS Library 1.1.1
41461  * Copyright(c) 2006-2007, Ext JS, LLC.
41462  *
41463  * Originally Released Under LGPL - original licence link has changed is not relivant.
41464  *
41465  * Fork - LGPL
41466  * <script type="text/javascript">
41467  */
41468 /**
41469  * @class Roo.grid.CellSelectionModel
41470  * @extends Roo.grid.AbstractSelectionModel
41471  * This class provides the basic implementation for cell selection in a grid.
41472  * @constructor
41473  * @param {Object} config The object containing the configuration of this model.
41474  * @cfg {Boolean} enter_is_tab Enter behaves the same as tab. (eg. goes to next cell) default: false
41475  */
41476 Roo.grid.CellSelectionModel = function(config){
41477     Roo.apply(this, config);
41478
41479     this.selection = null;
41480
41481     this.addEvents({
41482         /**
41483              * @event beforerowselect
41484              * Fires before a cell is selected.
41485              * @param {SelectionModel} this
41486              * @param {Number} rowIndex The selected row index
41487              * @param {Number} colIndex The selected cell index
41488              */
41489             "beforecellselect" : true,
41490         /**
41491              * @event cellselect
41492              * Fires when a cell is selected.
41493              * @param {SelectionModel} this
41494              * @param {Number} rowIndex The selected row index
41495              * @param {Number} colIndex The selected cell index
41496              */
41497             "cellselect" : true,
41498         /**
41499              * @event selectionchange
41500              * Fires when the active selection changes.
41501              * @param {SelectionModel} this
41502              * @param {Object} selection null for no selection or an object (o) with two properties
41503                 <ul>
41504                 <li>o.record: the record object for the row the selection is in</li>
41505                 <li>o.cell: An array of [rowIndex, columnIndex]</li>
41506                 </ul>
41507              */
41508             "selectionchange" : true,
41509         /**
41510              * @event tabend
41511              * Fires when the tab (or enter) was pressed on the last editable cell
41512              * You can use this to trigger add new row.
41513              * @param {SelectionModel} this
41514              */
41515             "tabend" : true,
41516          /**
41517              * @event beforeeditnext
41518              * Fires before the next editable sell is made active
41519              * You can use this to skip to another cell or fire the tabend
41520              *    if you set cell to false
41521              * @param {Object} eventdata object : { cell : [ row, col ] } 
41522              */
41523             "beforeeditnext" : true
41524     });
41525     Roo.grid.CellSelectionModel.superclass.constructor.call(this);
41526 };
41527
41528 Roo.extend(Roo.grid.CellSelectionModel, Roo.grid.AbstractSelectionModel,  {
41529     
41530     enter_is_tab: false,
41531
41532     /** @ignore */
41533     initEvents : function(){
41534         this.grid.on("mousedown", this.handleMouseDown, this);
41535         this.grid.getGridEl().on(Roo.isIE ? "keydown" : "keypress", this.handleKeyDown, this);
41536         var view = this.grid.view;
41537         view.on("refresh", this.onViewChange, this);
41538         view.on("rowupdated", this.onRowUpdated, this);
41539         view.on("beforerowremoved", this.clearSelections, this);
41540         view.on("beforerowsinserted", this.clearSelections, this);
41541         if(this.grid.isEditor){
41542             this.grid.on("beforeedit", this.beforeEdit,  this);
41543         }
41544     },
41545
41546         //private
41547     beforeEdit : function(e){
41548         this.select(e.row, e.column, false, true, e.record);
41549     },
41550
41551         //private
41552     onRowUpdated : function(v, index, r){
41553         if(this.selection && this.selection.record == r){
41554             v.onCellSelect(index, this.selection.cell[1]);
41555         }
41556     },
41557
41558         //private
41559     onViewChange : function(){
41560         this.clearSelections(true);
41561     },
41562
41563         /**
41564          * Returns the currently selected cell,.
41565          * @return {Array} The selected cell (row, column) or null if none selected.
41566          */
41567     getSelectedCell : function(){
41568         return this.selection ? this.selection.cell : null;
41569     },
41570
41571     /**
41572      * Clears all selections.
41573      * @param {Boolean} true to prevent the gridview from being notified about the change.
41574      */
41575     clearSelections : function(preventNotify){
41576         var s = this.selection;
41577         if(s){
41578             if(preventNotify !== true){
41579                 this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
41580             }
41581             this.selection = null;
41582             this.fireEvent("selectionchange", this, null);
41583         }
41584     },
41585
41586     /**
41587      * Returns true if there is a selection.
41588      * @return {Boolean}
41589      */
41590     hasSelection : function(){
41591         return this.selection ? true : false;
41592     },
41593
41594     /** @ignore */
41595     handleMouseDown : function(e, t){
41596         var v = this.grid.getView();
41597         if(this.isLocked()){
41598             return;
41599         };
41600         var row = v.findRowIndex(t);
41601         var cell = v.findCellIndex(t);
41602         if(row !== false && cell !== false){
41603             this.select(row, cell);
41604         }
41605     },
41606
41607     /**
41608      * Selects a cell.
41609      * @param {Number} rowIndex
41610      * @param {Number} collIndex
41611      */
41612     select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
41613         if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
41614             this.clearSelections();
41615             r = r || this.grid.dataSource.getAt(rowIndex);
41616             this.selection = {
41617                 record : r,
41618                 cell : [rowIndex, colIndex]
41619             };
41620             if(!preventViewNotify){
41621                 var v = this.grid.getView();
41622                 v.onCellSelect(rowIndex, colIndex);
41623                 if(preventFocus !== true){
41624                     v.focusCell(rowIndex, colIndex);
41625                 }
41626             }
41627             this.fireEvent("cellselect", this, rowIndex, colIndex);
41628             this.fireEvent("selectionchange", this, this.selection);
41629         }
41630     },
41631
41632         //private
41633     isSelectable : function(rowIndex, colIndex, cm){
41634         return !cm.isHidden(colIndex);
41635     },
41636
41637     /** @ignore */
41638     handleKeyDown : function(e){
41639         //Roo.log('Cell Sel Model handleKeyDown');
41640         if(!e.isNavKeyPress()){
41641             return;
41642         }
41643         var g = this.grid, s = this.selection;
41644         if(!s){
41645             e.stopEvent();
41646             var cell = g.walkCells(0, 0, 1, this.isSelectable,  this);
41647             if(cell){
41648                 this.select(cell[0], cell[1]);
41649             }
41650             return;
41651         }
41652         var sm = this;
41653         var walk = function(row, col, step){
41654             return g.walkCells(row, col, step, sm.isSelectable,  sm);
41655         };
41656         var k = e.getKey(), r = s.cell[0], c = s.cell[1];
41657         var newCell;
41658
41659       
41660
41661         switch(k){
41662             case e.TAB:
41663                 // handled by onEditorKey
41664                 if (g.isEditor && g.editing) {
41665                     return;
41666                 }
41667                 if(e.shiftKey) {
41668                     newCell = walk(r, c-1, -1);
41669                 } else {
41670                     newCell = walk(r, c+1, 1);
41671                 }
41672                 break;
41673             
41674             case e.DOWN:
41675                newCell = walk(r+1, c, 1);
41676                 break;
41677             
41678             case e.UP:
41679                 newCell = walk(r-1, c, -1);
41680                 break;
41681             
41682             case e.RIGHT:
41683                 newCell = walk(r, c+1, 1);
41684                 break;
41685             
41686             case e.LEFT:
41687                 newCell = walk(r, c-1, -1);
41688                 break;
41689             
41690             case e.ENTER:
41691                 
41692                 if(g.isEditor && !g.editing){
41693                    g.startEditing(r, c);
41694                    e.stopEvent();
41695                    return;
41696                 }
41697                 
41698                 
41699              break;
41700         };
41701         if(newCell){
41702             this.select(newCell[0], newCell[1]);
41703             e.stopEvent();
41704             
41705         }
41706     },
41707
41708     acceptsNav : function(row, col, cm){
41709         return !cm.isHidden(col) && cm.isCellEditable(col, row);
41710     },
41711     /**
41712      * Selects a cell.
41713      * @param {Number} field (not used) - as it's normally used as a listener
41714      * @param {Number} e - event - fake it by using
41715      *
41716      * var e = Roo.EventObjectImpl.prototype;
41717      * e.keyCode = e.TAB
41718      *
41719      * 
41720      */
41721     onEditorKey : function(field, e){
41722         
41723         var k = e.getKey(),
41724             newCell,
41725             g = this.grid,
41726             ed = g.activeEditor,
41727             forward = false;
41728         ///Roo.log('onEditorKey' + k);
41729         
41730         
41731         if (this.enter_is_tab && k == e.ENTER) {
41732             k = e.TAB;
41733         }
41734         
41735         if(k == e.TAB){
41736             if(e.shiftKey){
41737                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
41738             }else{
41739                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
41740                 forward = true;
41741             }
41742             
41743             e.stopEvent();
41744             
41745         } else if(k == e.ENTER &&  !e.ctrlKey){
41746             ed.completeEdit();
41747             e.stopEvent();
41748             newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
41749         
41750                 } else if(k == e.ESC){
41751             ed.cancelEdit();
41752         }
41753                 
41754         if (newCell) {
41755             var ecall = { cell : newCell, forward : forward };
41756             this.fireEvent('beforeeditnext', ecall );
41757             newCell = ecall.cell;
41758                         forward = ecall.forward;
41759         }
41760                 
41761         if(newCell){
41762             //Roo.log('next cell after edit');
41763             g.startEditing.defer(100, g, [newCell[0], newCell[1]]);
41764         } else if (forward) {
41765             // tabbed past last
41766             this.fireEvent.defer(100, this, ['tabend',this]);
41767         }
41768     }
41769 });/*
41770  * Based on:
41771  * Ext JS Library 1.1.1
41772  * Copyright(c) 2006-2007, Ext JS, LLC.
41773  *
41774  * Originally Released Under LGPL - original licence link has changed is not relivant.
41775  *
41776  * Fork - LGPL
41777  * <script type="text/javascript">
41778  */
41779  
41780 /**
41781  * @class Roo.grid.EditorGrid
41782  * @extends Roo.grid.Grid
41783  * Class for creating and editable grid.
41784  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered - 
41785  * The container MUST have some type of size defined for the grid to fill. The container will be 
41786  * automatically set to position relative if it isn't already.
41787  * @param {Object} dataSource The data model to bind to
41788  * @param {Object} colModel The column model with info about this grid's columns
41789  */
41790 Roo.grid.EditorGrid = function(container, config){
41791     Roo.grid.EditorGrid.superclass.constructor.call(this, container, config);
41792     this.getGridEl().addClass("xedit-grid");
41793
41794     if(!this.selModel){
41795         this.selModel = new Roo.grid.CellSelectionModel();
41796     }
41797
41798     this.activeEditor = null;
41799
41800         this.addEvents({
41801             /**
41802              * @event beforeedit
41803              * Fires before cell editing is triggered. The edit event object has the following properties <br />
41804              * <ul style="padding:5px;padding-left:16px;">
41805              * <li>grid - This grid</li>
41806              * <li>record - The record being edited</li>
41807              * <li>field - The field name being edited</li>
41808              * <li>value - The value for the field being edited.</li>
41809              * <li>row - The grid row index</li>
41810              * <li>column - The grid column index</li>
41811              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
41812              * </ul>
41813              * @param {Object} e An edit event (see above for description)
41814              */
41815             "beforeedit" : true,
41816             /**
41817              * @event afteredit
41818              * Fires after a cell is edited. <br />
41819              * <ul style="padding:5px;padding-left:16px;">
41820              * <li>grid - This grid</li>
41821              * <li>record - The record being edited</li>
41822              * <li>field - The field name being edited</li>
41823              * <li>value - The value being set</li>
41824              * <li>originalValue - The original value for the field, before the edit.</li>
41825              * <li>row - The grid row index</li>
41826              * <li>column - The grid column index</li>
41827              * </ul>
41828              * @param {Object} e An edit event (see above for description)
41829              */
41830             "afteredit" : true,
41831             /**
41832              * @event validateedit
41833              * Fires after a cell is edited, but before the value is set in the record. 
41834          * You can use this to modify the value being set in the field, Return false
41835              * to cancel the change. The edit event object has the following properties <br />
41836              * <ul style="padding:5px;padding-left:16px;">
41837          * <li>editor - This editor</li>
41838              * <li>grid - This grid</li>
41839              * <li>record - The record being edited</li>
41840              * <li>field - The field name being edited</li>
41841              * <li>value - The value being set</li>
41842              * <li>originalValue - The original value for the field, before the edit.</li>
41843              * <li>row - The grid row index</li>
41844              * <li>column - The grid column index</li>
41845              * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
41846              * </ul>
41847              * @param {Object} e An edit event (see above for description)
41848              */
41849             "validateedit" : true
41850         });
41851     this.on("bodyscroll", this.stopEditing,  this);
41852     this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick,  this);
41853 };
41854
41855 Roo.extend(Roo.grid.EditorGrid, Roo.grid.Grid, {
41856     /**
41857      * @cfg {Number} clicksToEdit
41858      * The number of clicks on a cell required to display the cell's editor (defaults to 2)
41859      */
41860     clicksToEdit: 2,
41861
41862     // private
41863     isEditor : true,
41864     // private
41865     trackMouseOver: false, // causes very odd FF errors
41866
41867     onCellDblClick : function(g, row, col){
41868         this.startEditing(row, col);
41869     },
41870
41871     onEditComplete : function(ed, value, startValue){
41872         this.editing = false;
41873         this.activeEditor = null;
41874         ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
41875         var r = ed.record;
41876         var field = this.colModel.getDataIndex(ed.col);
41877         var e = {
41878             grid: this,
41879             record: r,
41880             field: field,
41881             originalValue: startValue,
41882             value: value,
41883             row: ed.row,
41884             column: ed.col,
41885             cancel:false,
41886             editor: ed
41887         };
41888         var cell = Roo.get(this.view.getCell(ed.row,ed.col));
41889         cell.show();
41890           
41891         if(String(value) !== String(startValue)){
41892             
41893             if(this.fireEvent("validateedit", e) !== false && !e.cancel){
41894                 r.set(field, e.value);
41895                 // if we are dealing with a combo box..
41896                 // then we also set the 'name' colum to be the displayField
41897                 if (ed.field.displayField && ed.field.name) {
41898                     r.set(ed.field.name, ed.field.el.dom.value);
41899                 }
41900                 
41901                 delete e.cancel; //?? why!!!
41902                 this.fireEvent("afteredit", e);
41903             }
41904         } else {
41905             this.fireEvent("afteredit", e); // always fire it!
41906         }
41907         this.view.focusCell(ed.row, ed.col);
41908     },
41909
41910     /**
41911      * Starts editing the specified for the specified row/column
41912      * @param {Number} rowIndex
41913      * @param {Number} colIndex
41914      */
41915     startEditing : function(row, col){
41916         this.stopEditing();
41917         if(this.colModel.isCellEditable(col, row)){
41918             this.view.ensureVisible(row, col, true);
41919           
41920             var r = this.dataSource.getAt(row);
41921             var field = this.colModel.getDataIndex(col);
41922             var cell = Roo.get(this.view.getCell(row,col));
41923             var e = {
41924                 grid: this,
41925                 record: r,
41926                 field: field,
41927                 value: r.data[field],
41928                 row: row,
41929                 column: col,
41930                 cancel:false 
41931             };
41932             if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
41933                 this.editing = true;
41934                 var ed = this.colModel.getCellEditor(col, row);
41935                 
41936                 if (!ed) {
41937                     return;
41938                 }
41939                 if(!ed.rendered){
41940                     ed.render(ed.parentEl || document.body);
41941                 }
41942                 ed.field.reset();
41943                
41944                 cell.hide();
41945                 
41946                 (function(){ // complex but required for focus issues in safari, ie and opera
41947                     ed.row = row;
41948                     ed.col = col;
41949                     ed.record = r;
41950                     ed.on("complete",   this.onEditComplete,        this,       {single: true});
41951                     ed.on("specialkey", this.selModel.onEditorKey,  this.selModel);
41952                     this.activeEditor = ed;
41953                     var v = r.data[field];
41954                     ed.startEdit(this.view.getCell(row, col), v);
41955                     // combo's with 'displayField and name set
41956                     if (ed.field.displayField && ed.field.name) {
41957                         ed.field.el.dom.value = r.data[ed.field.name];
41958                     }
41959                     
41960                     
41961                 }).defer(50, this);
41962             }
41963         }
41964     },
41965         
41966     /**
41967      * Stops any active editing
41968      */
41969     stopEditing : function(){
41970         if(this.activeEditor){
41971             this.activeEditor.completeEdit();
41972         }
41973         this.activeEditor = null;
41974     },
41975         
41976          /**
41977      * Called to get grid's drag proxy text, by default returns this.ddText.
41978      * @return {String}
41979      */
41980     getDragDropText : function(){
41981         var count = this.selModel.getSelectedCell() ? 1 : 0;
41982         return String.format(this.ddText, count, count == 1 ? '' : 's');
41983     }
41984         
41985 });/*
41986  * Based on:
41987  * Ext JS Library 1.1.1
41988  * Copyright(c) 2006-2007, Ext JS, LLC.
41989  *
41990  * Originally Released Under LGPL - original licence link has changed is not relivant.
41991  *
41992  * Fork - LGPL
41993  * <script type="text/javascript">
41994  */
41995
41996 // private - not really -- you end up using it !
41997 // This is a support class used internally by the Grid components
41998
41999 /**
42000  * @class Roo.grid.GridEditor
42001  * @extends Roo.Editor
42002  * Class for creating and editable grid elements.
42003  * @param {Object} config any settings (must include field)
42004  */
42005 Roo.grid.GridEditor = function(field, config){
42006     if (!config && field.field) {
42007         config = field;
42008         field = Roo.factory(config.field, Roo.form);
42009     }
42010     Roo.grid.GridEditor.superclass.constructor.call(this, field, config);
42011     field.monitorTab = false;
42012 };
42013
42014 Roo.extend(Roo.grid.GridEditor, Roo.Editor, {
42015     
42016     /**
42017      * @cfg {Roo.form.Field} field Field to wrap (or xtyped)
42018      */
42019     
42020     alignment: "tl-tl",
42021     autoSize: "width",
42022     hideEl : false,
42023     cls: "x-small-editor x-grid-editor",
42024     shim:false,
42025     shadow:"frame"
42026 });/*
42027  * Based on:
42028  * Ext JS Library 1.1.1
42029  * Copyright(c) 2006-2007, Ext JS, LLC.
42030  *
42031  * Originally Released Under LGPL - original licence link has changed is not relivant.
42032  *
42033  * Fork - LGPL
42034  * <script type="text/javascript">
42035  */
42036   
42037
42038   
42039 Roo.grid.PropertyRecord = Roo.data.Record.create([
42040     {name:'name',type:'string'},  'value'
42041 ]);
42042
42043
42044 Roo.grid.PropertyStore = function(grid, source){
42045     this.grid = grid;
42046     this.store = new Roo.data.Store({
42047         recordType : Roo.grid.PropertyRecord
42048     });
42049     this.store.on('update', this.onUpdate,  this);
42050     if(source){
42051         this.setSource(source);
42052     }
42053     Roo.grid.PropertyStore.superclass.constructor.call(this);
42054 };
42055
42056
42057
42058 Roo.extend(Roo.grid.PropertyStore, Roo.util.Observable, {
42059     setSource : function(o){
42060         this.source = o;
42061         this.store.removeAll();
42062         var data = [];
42063         for(var k in o){
42064             if(this.isEditableValue(o[k])){
42065                 data.push(new Roo.grid.PropertyRecord({name: k, value: o[k]}, k));
42066             }
42067         }
42068         this.store.loadRecords({records: data}, {}, true);
42069     },
42070
42071     onUpdate : function(ds, record, type){
42072         if(type == Roo.data.Record.EDIT){
42073             var v = record.data['value'];
42074             var oldValue = record.modified['value'];
42075             if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
42076                 this.source[record.id] = v;
42077                 record.commit();
42078                 this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
42079             }else{
42080                 record.reject();
42081             }
42082         }
42083     },
42084
42085     getProperty : function(row){
42086        return this.store.getAt(row);
42087     },
42088
42089     isEditableValue: function(val){
42090         if(val && val instanceof Date){
42091             return true;
42092         }else if(typeof val == 'object' || typeof val == 'function'){
42093             return false;
42094         }
42095         return true;
42096     },
42097
42098     setValue : function(prop, value){
42099         this.source[prop] = value;
42100         this.store.getById(prop).set('value', value);
42101     },
42102
42103     getSource : function(){
42104         return this.source;
42105     }
42106 });
42107
42108 Roo.grid.PropertyColumnModel = function(grid, store){
42109     this.grid = grid;
42110     var g = Roo.grid;
42111     g.PropertyColumnModel.superclass.constructor.call(this, [
42112         {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'},
42113         {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'}
42114     ]);
42115     this.store = store;
42116     this.bselect = Roo.DomHelper.append(document.body, {
42117         tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [
42118             {tag: 'option', value: 'true', html: 'true'},
42119             {tag: 'option', value: 'false', html: 'false'}
42120         ]
42121     });
42122     Roo.id(this.bselect);
42123     var f = Roo.form;
42124     this.editors = {
42125         'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
42126         'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
42127         'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
42128         'int' : new g.GridEditor(new f.NumberField({selectOnFocus:true, allowDecimals:false, style:'text-align:left;'})),
42129         'boolean' : new g.GridEditor(new f.Field({el:this.bselect,selectOnFocus:true}))
42130     };
42131     this.renderCellDelegate = this.renderCell.createDelegate(this);
42132     this.renderPropDelegate = this.renderProp.createDelegate(this);
42133 };
42134
42135 Roo.extend(Roo.grid.PropertyColumnModel, Roo.grid.ColumnModel, {
42136     
42137     
42138     nameText : 'Name',
42139     valueText : 'Value',
42140     
42141     dateFormat : 'm/j/Y',
42142     
42143     
42144     renderDate : function(dateVal){
42145         return dateVal.dateFormat(this.dateFormat);
42146     },
42147
42148     renderBool : function(bVal){
42149         return bVal ? 'true' : 'false';
42150     },
42151
42152     isCellEditable : function(colIndex, rowIndex){
42153         return colIndex == 1;
42154     },
42155
42156     getRenderer : function(col){
42157         return col == 1 ?
42158             this.renderCellDelegate : this.renderPropDelegate;
42159     },
42160
42161     renderProp : function(v){
42162         return this.getPropertyName(v);
42163     },
42164
42165     renderCell : function(val){
42166         var rv = val;
42167         if(val instanceof Date){
42168             rv = this.renderDate(val);
42169         }else if(typeof val == 'boolean'){
42170             rv = this.renderBool(val);
42171         }
42172         return Roo.util.Format.htmlEncode(rv);
42173     },
42174
42175     getPropertyName : function(name){
42176         var pn = this.grid.propertyNames;
42177         return pn && pn[name] ? pn[name] : name;
42178     },
42179
42180     getCellEditor : function(colIndex, rowIndex){
42181         var p = this.store.getProperty(rowIndex);
42182         var n = p.data['name'], val = p.data['value'];
42183         
42184         if(typeof(this.grid.customEditors[n]) == 'string'){
42185             return this.editors[this.grid.customEditors[n]];
42186         }
42187         if(typeof(this.grid.customEditors[n]) != 'undefined'){
42188             return this.grid.customEditors[n];
42189         }
42190         if(val instanceof Date){
42191             return this.editors['date'];
42192         }else if(typeof val == 'number'){
42193             return this.editors['number'];
42194         }else if(typeof val == 'boolean'){
42195             return this.editors['boolean'];
42196         }else{
42197             return this.editors['string'];
42198         }
42199     }
42200 });
42201
42202 /**
42203  * @class Roo.grid.PropertyGrid
42204  * @extends Roo.grid.EditorGrid
42205  * This class represents the  interface of a component based property grid control.
42206  * <br><br>Usage:<pre><code>
42207  var grid = new Roo.grid.PropertyGrid("my-container-id", {
42208       
42209  });
42210  // set any options
42211  grid.render();
42212  * </code></pre>
42213   
42214  * @constructor
42215  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
42216  * The container MUST have some type of size defined for the grid to fill. The container will be
42217  * automatically set to position relative if it isn't already.
42218  * @param {Object} config A config object that sets properties on this grid.
42219  */
42220 Roo.grid.PropertyGrid = function(container, config){
42221     config = config || {};
42222     var store = new Roo.grid.PropertyStore(this);
42223     this.store = store;
42224     var cm = new Roo.grid.PropertyColumnModel(this, store);
42225     store.store.sort('name', 'ASC');
42226     Roo.grid.PropertyGrid.superclass.constructor.call(this, container, Roo.apply({
42227         ds: store.store,
42228         cm: cm,
42229         enableColLock:false,
42230         enableColumnMove:false,
42231         stripeRows:false,
42232         trackMouseOver: false,
42233         clicksToEdit:1
42234     }, config));
42235     this.getGridEl().addClass('x-props-grid');
42236     this.lastEditRow = null;
42237     this.on('columnresize', this.onColumnResize, this);
42238     this.addEvents({
42239          /**
42240              * @event beforepropertychange
42241              * Fires before a property changes (return false to stop?)
42242              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
42243              * @param {String} id Record Id
42244              * @param {String} newval New Value
42245          * @param {String} oldval Old Value
42246              */
42247         "beforepropertychange": true,
42248         /**
42249              * @event propertychange
42250              * Fires after a property changes
42251              * @param {Roo.grid.PropertyGrid} grid property grid? (check could be store)
42252              * @param {String} id Record Id
42253              * @param {String} newval New Value
42254          * @param {String} oldval Old Value
42255              */
42256         "propertychange": true
42257     });
42258     this.customEditors = this.customEditors || {};
42259 };
42260 Roo.extend(Roo.grid.PropertyGrid, Roo.grid.EditorGrid, {
42261     
42262      /**
42263      * @cfg {Object} customEditors map of colnames=> custom editors.
42264      * the custom editor can be one of the standard ones (date|string|number|int|boolean), or a
42265      * grid editor eg. Roo.grid.GridEditor(new Roo.form.TextArea({selectOnFocus:true})),
42266      * false disables editing of the field.
42267          */
42268     
42269       /**
42270      * @cfg {Object} propertyNames map of property Names to their displayed value
42271          */
42272     
42273     render : function(){
42274         Roo.grid.PropertyGrid.superclass.render.call(this);
42275         this.autoSize.defer(100, this);
42276     },
42277
42278     autoSize : function(){
42279         Roo.grid.PropertyGrid.superclass.autoSize.call(this);
42280         if(this.view){
42281             this.view.fitColumns();
42282         }
42283     },
42284
42285     onColumnResize : function(){
42286         this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0));
42287         this.autoSize();
42288     },
42289     /**
42290      * Sets the data for the Grid
42291      * accepts a Key => Value object of all the elements avaiable.
42292      * @param {Object} data  to appear in grid.
42293      */
42294     setSource : function(source){
42295         this.store.setSource(source);
42296         //this.autoSize();
42297     },
42298     /**
42299      * Gets all the data from the grid.
42300      * @return {Object} data  data stored in grid
42301      */
42302     getSource : function(){
42303         return this.store.getSource();
42304     }
42305 });/*
42306   
42307  * Licence LGPL
42308  
42309  */
42310  
42311 /**
42312  * @class Roo.grid.Calendar
42313  * @extends Roo.grid.Grid
42314  * This class extends the Grid to provide a calendar widget
42315  * <br><br>Usage:<pre><code>
42316  var grid = new Roo.grid.Calendar("my-container-id", {
42317      ds: myDataStore,
42318      cm: myColModel,
42319      selModel: mySelectionModel,
42320      autoSizeColumns: true,
42321      monitorWindowResize: false,
42322      trackMouseOver: true
42323      eventstore : real data store..
42324  });
42325  // set any options
42326  grid.render();
42327   
42328   * @constructor
42329  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
42330  * The container MUST have some type of size defined for the grid to fill. The container will be
42331  * automatically set to position relative if it isn't already.
42332  * @param {Object} config A config object that sets properties on this grid.
42333  */
42334 Roo.grid.Calendar = function(container, config){
42335         // initialize the container
42336         this.container = Roo.get(container);
42337         this.container.update("");
42338         this.container.setStyle("overflow", "hidden");
42339     this.container.addClass('x-grid-container');
42340
42341     this.id = this.container.id;
42342
42343     Roo.apply(this, config);
42344     // check and correct shorthanded configs
42345     
42346     var rows = [];
42347     var d =1;
42348     for (var r = 0;r < 6;r++) {
42349         
42350         rows[r]=[];
42351         for (var c =0;c < 7;c++) {
42352             rows[r][c]= '';
42353         }
42354     }
42355     if (this.eventStore) {
42356         this.eventStore= Roo.factory(this.eventStore, Roo.data);
42357         this.eventStore.on('load',this.onLoad, this);
42358         this.eventStore.on('beforeload',this.clearEvents, this);
42359          
42360     }
42361     
42362     this.dataSource = new Roo.data.Store({
42363             proxy: new Roo.data.MemoryProxy(rows),
42364             reader: new Roo.data.ArrayReader({}, [
42365                    'weekday0', 'weekday1', 'weekday2', 'weekday3', 'weekday4', 'weekday5', 'weekday6' ])
42366     });
42367
42368     this.dataSource.load();
42369     this.ds = this.dataSource;
42370     this.ds.xmodule = this.xmodule || false;
42371     
42372     
42373     var cellRender = function(v,x,r)
42374     {
42375         return String.format(
42376             '<div class="fc-day  fc-widget-content"><div>' +
42377                 '<div class="fc-event-container"></div>' +
42378                 '<div class="fc-day-number">{0}</div>'+
42379                 
42380                 '<div class="fc-day-content"><div style="position:relative"></div></div>' +
42381             '</div></div>', v);
42382     
42383     }
42384     
42385     
42386     this.colModel = new Roo.grid.ColumnModel( [
42387         {
42388             xtype: 'ColumnModel',
42389             xns: Roo.grid,
42390             dataIndex : 'weekday0',
42391             header : 'Sunday',
42392             renderer : cellRender
42393         },
42394         {
42395             xtype: 'ColumnModel',
42396             xns: Roo.grid,
42397             dataIndex : 'weekday1',
42398             header : 'Monday',
42399             renderer : cellRender
42400         },
42401         {
42402             xtype: 'ColumnModel',
42403             xns: Roo.grid,
42404             dataIndex : 'weekday2',
42405             header : 'Tuesday',
42406             renderer : cellRender
42407         },
42408         {
42409             xtype: 'ColumnModel',
42410             xns: Roo.grid,
42411             dataIndex : 'weekday3',
42412             header : 'Wednesday',
42413             renderer : cellRender
42414         },
42415         {
42416             xtype: 'ColumnModel',
42417             xns: Roo.grid,
42418             dataIndex : 'weekday4',
42419             header : 'Thursday',
42420             renderer : cellRender
42421         },
42422         {
42423             xtype: 'ColumnModel',
42424             xns: Roo.grid,
42425             dataIndex : 'weekday5',
42426             header : 'Friday',
42427             renderer : cellRender
42428         },
42429         {
42430             xtype: 'ColumnModel',
42431             xns: Roo.grid,
42432             dataIndex : 'weekday6',
42433             header : 'Saturday',
42434             renderer : cellRender
42435         }
42436     ]);
42437     this.cm = this.colModel;
42438     this.cm.xmodule = this.xmodule || false;
42439  
42440         
42441           
42442     //this.selModel = new Roo.grid.CellSelectionModel();
42443     //this.sm = this.selModel;
42444     //this.selModel.init(this);
42445     
42446     
42447     if(this.width){
42448         this.container.setWidth(this.width);
42449     }
42450
42451     if(this.height){
42452         this.container.setHeight(this.height);
42453     }
42454     /** @private */
42455         this.addEvents({
42456         // raw events
42457         /**
42458          * @event click
42459          * The raw click event for the entire grid.
42460          * @param {Roo.EventObject} e
42461          */
42462         "click" : true,
42463         /**
42464          * @event dblclick
42465          * The raw dblclick event for the entire grid.
42466          * @param {Roo.EventObject} e
42467          */
42468         "dblclick" : true,
42469         /**
42470          * @event contextmenu
42471          * The raw contextmenu event for the entire grid.
42472          * @param {Roo.EventObject} e
42473          */
42474         "contextmenu" : true,
42475         /**
42476          * @event mousedown
42477          * The raw mousedown event for the entire grid.
42478          * @param {Roo.EventObject} e
42479          */
42480         "mousedown" : true,
42481         /**
42482          * @event mouseup
42483          * The raw mouseup event for the entire grid.
42484          * @param {Roo.EventObject} e
42485          */
42486         "mouseup" : true,
42487         /**
42488          * @event mouseover
42489          * The raw mouseover event for the entire grid.
42490          * @param {Roo.EventObject} e
42491          */
42492         "mouseover" : true,
42493         /**
42494          * @event mouseout
42495          * The raw mouseout event for the entire grid.
42496          * @param {Roo.EventObject} e
42497          */
42498         "mouseout" : true,
42499         /**
42500          * @event keypress
42501          * The raw keypress event for the entire grid.
42502          * @param {Roo.EventObject} e
42503          */
42504         "keypress" : true,
42505         /**
42506          * @event keydown
42507          * The raw keydown event for the entire grid.
42508          * @param {Roo.EventObject} e
42509          */
42510         "keydown" : true,
42511
42512         // custom events
42513
42514         /**
42515          * @event cellclick
42516          * Fires when a cell is clicked
42517          * @param {Grid} this
42518          * @param {Number} rowIndex
42519          * @param {Number} columnIndex
42520          * @param {Roo.EventObject} e
42521          */
42522         "cellclick" : true,
42523         /**
42524          * @event celldblclick
42525          * Fires when a cell is double clicked
42526          * @param {Grid} this
42527          * @param {Number} rowIndex
42528          * @param {Number} columnIndex
42529          * @param {Roo.EventObject} e
42530          */
42531         "celldblclick" : true,
42532         /**
42533          * @event rowclick
42534          * Fires when a row is clicked
42535          * @param {Grid} this
42536          * @param {Number} rowIndex
42537          * @param {Roo.EventObject} e
42538          */
42539         "rowclick" : true,
42540         /**
42541          * @event rowdblclick
42542          * Fires when a row is double clicked
42543          * @param {Grid} this
42544          * @param {Number} rowIndex
42545          * @param {Roo.EventObject} e
42546          */
42547         "rowdblclick" : true,
42548         /**
42549          * @event headerclick
42550          * Fires when a header is clicked
42551          * @param {Grid} this
42552          * @param {Number} columnIndex
42553          * @param {Roo.EventObject} e
42554          */
42555         "headerclick" : true,
42556         /**
42557          * @event headerdblclick
42558          * Fires when a header cell is double clicked
42559          * @param {Grid} this
42560          * @param {Number} columnIndex
42561          * @param {Roo.EventObject} e
42562          */
42563         "headerdblclick" : true,
42564         /**
42565          * @event rowcontextmenu
42566          * Fires when a row is right clicked
42567          * @param {Grid} this
42568          * @param {Number} rowIndex
42569          * @param {Roo.EventObject} e
42570          */
42571         "rowcontextmenu" : true,
42572         /**
42573          * @event cellcontextmenu
42574          * Fires when a cell is right clicked
42575          * @param {Grid} this
42576          * @param {Number} rowIndex
42577          * @param {Number} cellIndex
42578          * @param {Roo.EventObject} e
42579          */
42580          "cellcontextmenu" : true,
42581         /**
42582          * @event headercontextmenu
42583          * Fires when a header is right clicked
42584          * @param {Grid} this
42585          * @param {Number} columnIndex
42586          * @param {Roo.EventObject} e
42587          */
42588         "headercontextmenu" : true,
42589         /**
42590          * @event bodyscroll
42591          * Fires when the body element is scrolled
42592          * @param {Number} scrollLeft
42593          * @param {Number} scrollTop
42594          */
42595         "bodyscroll" : true,
42596         /**
42597          * @event columnresize
42598          * Fires when the user resizes a column
42599          * @param {Number} columnIndex
42600          * @param {Number} newSize
42601          */
42602         "columnresize" : true,
42603         /**
42604          * @event columnmove
42605          * Fires when the user moves a column
42606          * @param {Number} oldIndex
42607          * @param {Number} newIndex
42608          */
42609         "columnmove" : true,
42610         /**
42611          * @event startdrag
42612          * Fires when row(s) start being dragged
42613          * @param {Grid} this
42614          * @param {Roo.GridDD} dd The drag drop object
42615          * @param {event} e The raw browser event
42616          */
42617         "startdrag" : true,
42618         /**
42619          * @event enddrag
42620          * Fires when a drag operation is complete
42621          * @param {Grid} this
42622          * @param {Roo.GridDD} dd The drag drop object
42623          * @param {event} e The raw browser event
42624          */
42625         "enddrag" : true,
42626         /**
42627          * @event dragdrop
42628          * Fires when dragged row(s) are dropped on a valid DD target
42629          * @param {Grid} this
42630          * @param {Roo.GridDD} dd The drag drop object
42631          * @param {String} targetId The target drag drop object
42632          * @param {event} e The raw browser event
42633          */
42634         "dragdrop" : true,
42635         /**
42636          * @event dragover
42637          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
42638          * @param {Grid} this
42639          * @param {Roo.GridDD} dd The drag drop object
42640          * @param {String} targetId The target drag drop object
42641          * @param {event} e The raw browser event
42642          */
42643         "dragover" : true,
42644         /**
42645          * @event dragenter
42646          *  Fires when the dragged row(s) first cross another DD target while being dragged
42647          * @param {Grid} this
42648          * @param {Roo.GridDD} dd The drag drop object
42649          * @param {String} targetId The target drag drop object
42650          * @param {event} e The raw browser event
42651          */
42652         "dragenter" : true,
42653         /**
42654          * @event dragout
42655          * Fires when the dragged row(s) leave another DD target while being dragged
42656          * @param {Grid} this
42657          * @param {Roo.GridDD} dd The drag drop object
42658          * @param {String} targetId The target drag drop object
42659          * @param {event} e The raw browser event
42660          */
42661         "dragout" : true,
42662         /**
42663          * @event rowclass
42664          * Fires when a row is rendered, so you can change add a style to it.
42665          * @param {GridView} gridview   The grid view
42666          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
42667          */
42668         'rowclass' : true,
42669
42670         /**
42671          * @event render
42672          * Fires when the grid is rendered
42673          * @param {Grid} grid
42674          */
42675         'render' : true,
42676             /**
42677              * @event select
42678              * Fires when a date is selected
42679              * @param {DatePicker} this
42680              * @param {Date} date The selected date
42681              */
42682         'select': true,
42683         /**
42684              * @event monthchange
42685              * Fires when the displayed month changes 
42686              * @param {DatePicker} this
42687              * @param {Date} date The selected month
42688              */
42689         'monthchange': true,
42690         /**
42691              * @event evententer
42692              * Fires when mouse over an event
42693              * @param {Calendar} this
42694              * @param {event} Event
42695              */
42696         'evententer': true,
42697         /**
42698              * @event eventleave
42699              * Fires when the mouse leaves an
42700              * @param {Calendar} this
42701              * @param {event}
42702              */
42703         'eventleave': true,
42704         /**
42705              * @event eventclick
42706              * Fires when the mouse click an
42707              * @param {Calendar} this
42708              * @param {event}
42709              */
42710         'eventclick': true,
42711         /**
42712              * @event eventrender
42713              * Fires before each cell is rendered, so you can modify the contents, like cls / title / qtip
42714              * @param {Calendar} this
42715              * @param {data} data to be modified
42716              */
42717         'eventrender': true
42718         
42719     });
42720
42721     Roo.grid.Grid.superclass.constructor.call(this);
42722     this.on('render', function() {
42723         this.view.el.addClass('x-grid-cal'); 
42724         
42725         (function() { this.setDate(new Date()); }).defer(100,this); //default today..
42726
42727     },this);
42728     
42729     if (!Roo.grid.Calendar.style) {
42730         Roo.grid.Calendar.style = Roo.util.CSS.createStyleSheet({
42731             
42732             
42733             '.x-grid-cal .x-grid-col' :  {
42734                 height: 'auto !important',
42735                 'vertical-align': 'top'
42736             },
42737             '.x-grid-cal  .fc-event-hori' : {
42738                 height: '14px'
42739             }
42740              
42741             
42742         }, Roo.id());
42743     }
42744
42745     
42746     
42747 };
42748 Roo.extend(Roo.grid.Calendar, Roo.grid.Grid, {
42749     /**
42750      * @cfg {Store} eventStore The store that loads events.
42751      */
42752     eventStore : 25,
42753
42754      
42755     activeDate : false,
42756     startDay : 0,
42757     autoWidth : true,
42758     monitorWindowResize : false,
42759
42760     
42761     resizeColumns : function() {
42762         var col = (this.view.el.getWidth() / 7) - 3;
42763         // loop through cols, and setWidth
42764         for(var i =0 ; i < 7 ; i++){
42765             this.cm.setColumnWidth(i, col);
42766         }
42767     },
42768      setDate :function(date) {
42769         
42770         Roo.log('setDate?');
42771         
42772         this.resizeColumns();
42773         var vd = this.activeDate;
42774         this.activeDate = date;
42775 //        if(vd && this.el){
42776 //            var t = date.getTime();
42777 //            if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
42778 //                Roo.log('using add remove');
42779 //                
42780 //                this.fireEvent('monthchange', this, date);
42781 //                
42782 //                this.cells.removeClass("fc-state-highlight");
42783 //                this.cells.each(function(c){
42784 //                   if(c.dateValue == t){
42785 //                       c.addClass("fc-state-highlight");
42786 //                       setTimeout(function(){
42787 //                            try{c.dom.firstChild.focus();}catch(e){}
42788 //                       }, 50);
42789 //                       return false;
42790 //                   }
42791 //                   return true;
42792 //                });
42793 //                return;
42794 //            }
42795 //        }
42796         
42797         var days = date.getDaysInMonth();
42798         
42799         var firstOfMonth = date.getFirstDateOfMonth();
42800         var startingPos = firstOfMonth.getDay()-this.startDay;
42801         
42802         if(startingPos < this.startDay){
42803             startingPos += 7;
42804         }
42805         
42806         var pm = date.add(Date.MONTH, -1);
42807         var prevStart = pm.getDaysInMonth()-startingPos;
42808 //        
42809         
42810         
42811         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
42812         
42813         this.textNodes = this.view.el.query('.x-grid-row .x-grid-col .x-grid-cell-text');
42814         //this.cells.addClassOnOver('fc-state-hover');
42815         
42816         var cells = this.cells.elements;
42817         var textEls = this.textNodes;
42818         
42819         //Roo.each(cells, function(cell){
42820         //    cell.removeClass([ 'fc-past', 'fc-other-month', 'fc-future', 'fc-state-highlight', 'fc-state-disabled']);
42821         //});
42822         
42823         days += startingPos;
42824
42825         // convert everything to numbers so it's fast
42826         var day = 86400000;
42827         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
42828         //Roo.log(d);
42829         //Roo.log(pm);
42830         //Roo.log(prevStart);
42831         
42832         var today = new Date().clearTime().getTime();
42833         var sel = date.clearTime().getTime();
42834         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
42835         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
42836         var ddMatch = this.disabledDatesRE;
42837         var ddText = this.disabledDatesText;
42838         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
42839         var ddaysText = this.disabledDaysText;
42840         var format = this.format;
42841         
42842         var setCellClass = function(cal, cell){
42843             
42844             //Roo.log('set Cell Class');
42845             cell.title = "";
42846             var t = d.getTime();
42847             
42848             //Roo.log(d);
42849             
42850             
42851             cell.dateValue = t;
42852             if(t == today){
42853                 cell.className += " fc-today";
42854                 cell.className += " fc-state-highlight";
42855                 cell.title = cal.todayText;
42856             }
42857             if(t == sel){
42858                 // disable highlight in other month..
42859                 cell.className += " fc-state-highlight";
42860                 
42861             }
42862             // disabling
42863             if(t < min) {
42864                 //cell.className = " fc-state-disabled";
42865                 cell.title = cal.minText;
42866                 return;
42867             }
42868             if(t > max) {
42869                 //cell.className = " fc-state-disabled";
42870                 cell.title = cal.maxText;
42871                 return;
42872             }
42873             if(ddays){
42874                 if(ddays.indexOf(d.getDay()) != -1){
42875                     // cell.title = ddaysText;
42876                    // cell.className = " fc-state-disabled";
42877                 }
42878             }
42879             if(ddMatch && format){
42880                 var fvalue = d.dateFormat(format);
42881                 if(ddMatch.test(fvalue)){
42882                     cell.title = ddText.replace("%0", fvalue);
42883                    cell.className = " fc-state-disabled";
42884                 }
42885             }
42886             
42887             if (!cell.initialClassName) {
42888                 cell.initialClassName = cell.dom.className;
42889             }
42890             
42891             cell.dom.className = cell.initialClassName  + ' ' +  cell.className;
42892         };
42893
42894         var i = 0;
42895         
42896         for(; i < startingPos; i++) {
42897             cells[i].dayName =  (++prevStart);
42898             Roo.log(textEls[i]);
42899             d.setDate(d.getDate()+1);
42900             
42901             //cells[i].className = "fc-past fc-other-month";
42902             setCellClass(this, cells[i]);
42903         }
42904         
42905         var intDay = 0;
42906         
42907         for(; i < days; i++){
42908             intDay = i - startingPos + 1;
42909             cells[i].dayName =  (intDay);
42910             d.setDate(d.getDate()+1);
42911             
42912             cells[i].className = ''; // "x-date-active";
42913             setCellClass(this, cells[i]);
42914         }
42915         var extraDays = 0;
42916         
42917         for(; i < 42; i++) {
42918             //textEls[i].innerHTML = (++extraDays);
42919             
42920             d.setDate(d.getDate()+1);
42921             cells[i].dayName = (++extraDays);
42922             cells[i].className = "fc-future fc-other-month";
42923             setCellClass(this, cells[i]);
42924         }
42925         
42926         //this.el.select('.fc-header-title h2',true).update(Date.monthNames[date.getMonth()] + " " + date.getFullYear());
42927         
42928         var totalRows = Math.ceil((date.getDaysInMonth() + date.getFirstDateOfMonth().getDay()) / 7);
42929         
42930         // this will cause all the cells to mis
42931         var rows= [];
42932         var i =0;
42933         for (var r = 0;r < 6;r++) {
42934             for (var c =0;c < 7;c++) {
42935                 this.ds.getAt(r).set('weekday' + c ,cells[i++].dayName );
42936             }    
42937         }
42938         
42939         this.cells = this.view.el.select('.x-grid-row .x-grid-col',true);
42940         for(i=0;i<cells.length;i++) {
42941             
42942             this.cells.elements[i].dayName = cells[i].dayName ;
42943             this.cells.elements[i].className = cells[i].className;
42944             this.cells.elements[i].initialClassName = cells[i].initialClassName ;
42945             this.cells.elements[i].title = cells[i].title ;
42946             this.cells.elements[i].dateValue = cells[i].dateValue ;
42947         }
42948         
42949         
42950         
42951         
42952         //this.el.select('tr.fc-week.fc-prev-last',true).removeClass('fc-last');
42953         //this.el.select('tr.fc-week.fc-next-last',true).addClass('fc-last').show();
42954         
42955         ////if(totalRows != 6){
42956             //this.el.select('tr.fc-week.fc-last',true).removeClass('fc-last').addClass('fc-next-last').hide();
42957            // this.el.select('tr.fc-week.fc-prev-last',true).addClass('fc-last');
42958        // }
42959         
42960         this.fireEvent('monthchange', this, date);
42961         
42962         
42963     },
42964  /**
42965      * Returns the grid's SelectionModel.
42966      * @return {SelectionModel}
42967      */
42968     getSelectionModel : function(){
42969         if(!this.selModel){
42970             this.selModel = new Roo.grid.CellSelectionModel();
42971         }
42972         return this.selModel;
42973     },
42974
42975     load: function() {
42976         this.eventStore.load()
42977         
42978         
42979         
42980     },
42981     
42982     findCell : function(dt) {
42983         dt = dt.clearTime().getTime();
42984         var ret = false;
42985         this.cells.each(function(c){
42986             //Roo.log("check " +c.dateValue + '?=' + dt);
42987             if(c.dateValue == dt){
42988                 ret = c;
42989                 return false;
42990             }
42991             return true;
42992         });
42993         
42994         return ret;
42995     },
42996     
42997     findCells : function(rec) {
42998         var s = rec.data.start_dt.clone().clearTime().getTime();
42999        // Roo.log(s);
43000         var e= rec.data.end_dt.clone().clearTime().getTime();
43001        // Roo.log(e);
43002         var ret = [];
43003         this.cells.each(function(c){
43004              ////Roo.log("check " +c.dateValue + '<' + e + ' > ' + s);
43005             
43006             if(c.dateValue > e){
43007                 return ;
43008             }
43009             if(c.dateValue < s){
43010                 return ;
43011             }
43012             ret.push(c);
43013         });
43014         
43015         return ret;    
43016     },
43017     
43018     findBestRow: function(cells)
43019     {
43020         var ret = 0;
43021         
43022         for (var i =0 ; i < cells.length;i++) {
43023             ret  = Math.max(cells[i].rows || 0,ret);
43024         }
43025         return ret;
43026         
43027     },
43028     
43029     
43030     addItem : function(rec)
43031     {
43032         // look for vertical location slot in
43033         var cells = this.findCells(rec);
43034         
43035         rec.row = this.findBestRow(cells);
43036         
43037         // work out the location.
43038         
43039         var crow = false;
43040         var rows = [];
43041         for(var i =0; i < cells.length; i++) {
43042             if (!crow) {
43043                 crow = {
43044                     start : cells[i],
43045                     end :  cells[i]
43046                 };
43047                 continue;
43048             }
43049             if (crow.start.getY() == cells[i].getY()) {
43050                 // on same row.
43051                 crow.end = cells[i];
43052                 continue;
43053             }
43054             // different row.
43055             rows.push(crow);
43056             crow = {
43057                 start: cells[i],
43058                 end : cells[i]
43059             };
43060             
43061         }
43062         
43063         rows.push(crow);
43064         rec.els = [];
43065         rec.rows = rows;
43066         rec.cells = cells;
43067         for (var i = 0; i < cells.length;i++) {
43068             cells[i].rows = Math.max(cells[i].rows || 0 , rec.row + 1 );
43069             
43070         }
43071         
43072         
43073     },
43074     
43075     clearEvents: function() {
43076         
43077         if (!this.eventStore.getCount()) {
43078             return;
43079         }
43080         // reset number of rows in cells.
43081         Roo.each(this.cells.elements, function(c){
43082             c.rows = 0;
43083         });
43084         
43085         this.eventStore.each(function(e) {
43086             this.clearEvent(e);
43087         },this);
43088         
43089     },
43090     
43091     clearEvent : function(ev)
43092     {
43093         if (ev.els) {
43094             Roo.each(ev.els, function(el) {
43095                 el.un('mouseenter' ,this.onEventEnter, this);
43096                 el.un('mouseleave' ,this.onEventLeave, this);
43097                 el.remove();
43098             },this);
43099             ev.els = [];
43100         }
43101     },
43102     
43103     
43104     renderEvent : function(ev,ctr) {
43105         if (!ctr) {
43106              ctr = this.view.el.select('.fc-event-container',true).first();
43107         }
43108         
43109          
43110         this.clearEvent(ev);
43111             //code
43112        
43113         
43114         
43115         ev.els = [];
43116         var cells = ev.cells;
43117         var rows = ev.rows;
43118         this.fireEvent('eventrender', this, ev);
43119         
43120         for(var i =0; i < rows.length; i++) {
43121             
43122             cls = '';
43123             if (i == 0) {
43124                 cls += ' fc-event-start';
43125             }
43126             if ((i+1) == rows.length) {
43127                 cls += ' fc-event-end';
43128             }
43129             
43130             //Roo.log(ev.data);
43131             // how many rows should it span..
43132             var cg = this.eventTmpl.append(ctr,Roo.apply({
43133                 fccls : cls
43134                 
43135             }, ev.data) , true);
43136             
43137             
43138             cg.on('mouseenter' ,this.onEventEnter, this, ev);
43139             cg.on('mouseleave' ,this.onEventLeave, this, ev);
43140             cg.on('click', this.onEventClick, this, ev);
43141             
43142             ev.els.push(cg);
43143             
43144             var sbox = rows[i].start.select('.fc-day-content',true).first().getBox();
43145             var ebox = rows[i].end.select('.fc-day-content',true).first().getBox();
43146             //Roo.log(cg);
43147              
43148             cg.setXY([sbox.x +2, sbox.y +(ev.row * 20)]);    
43149             cg.setWidth(ebox.right - sbox.x -2);
43150         }
43151     },
43152     
43153     renderEvents: function()
43154     {   
43155         // first make sure there is enough space..
43156         
43157         if (!this.eventTmpl) {
43158             this.eventTmpl = new Roo.Template(
43159                 '<div class="roo-dynamic fc-event fc-event-hori fc-event-draggable ui-draggable {fccls} {cls}"  style="position: absolute" unselectable="on">' +
43160                     '<div class="fc-event-inner">' +
43161                         '<span class="fc-event-time">{time}</span>' +
43162                         '<span class="fc-event-title" qtip="{qtip}">{title}</span>' +
43163                     '</div>' +
43164                     '<div class="ui-resizable-heandle ui-resizable-e">&nbsp;&nbsp;&nbsp;</div>' +
43165                 '</div>'
43166             );
43167                 
43168         }
43169                
43170         
43171         
43172         this.cells.each(function(c) {
43173             //Roo.log(c.select('.fc-day-content div',true).first());
43174             c.select('.fc-day-content div',true).first().setHeight(Math.max(34, (c.rows || 1) * 20));
43175         });
43176         
43177         var ctr = this.view.el.select('.fc-event-container',true).first();
43178         
43179         var cls;
43180         this.eventStore.each(function(ev){
43181             
43182             this.renderEvent(ev);
43183              
43184              
43185         }, this);
43186         this.view.layout();
43187         
43188     },
43189     
43190     onEventEnter: function (e, el,event,d) {
43191         this.fireEvent('evententer', this, el, event);
43192     },
43193     
43194     onEventLeave: function (e, el,event,d) {
43195         this.fireEvent('eventleave', this, el, event);
43196     },
43197     
43198     onEventClick: function (e, el,event,d) {
43199         this.fireEvent('eventclick', this, el, event);
43200     },
43201     
43202     onMonthChange: function () {
43203         this.store.load();
43204     },
43205     
43206     onLoad: function () {
43207         
43208         //Roo.log('calendar onload');
43209 //         
43210         if(this.eventStore.getCount() > 0){
43211             
43212            
43213             
43214             this.eventStore.each(function(d){
43215                 
43216                 
43217                 // FIXME..
43218                 var add =   d.data;
43219                 if (typeof(add.end_dt) == 'undefined')  {
43220                     Roo.log("Missing End time in calendar data: ");
43221                     Roo.log(d);
43222                     return;
43223                 }
43224                 if (typeof(add.start_dt) == 'undefined')  {
43225                     Roo.log("Missing Start time in calendar data: ");
43226                     Roo.log(d);
43227                     return;
43228                 }
43229                 add.start_dt = typeof(add.start_dt) == 'string' ? Date.parseDate(add.start_dt,'Y-m-d H:i:s') : add.start_dt,
43230                 add.end_dt = typeof(add.end_dt) == 'string' ? Date.parseDate(add.end_dt,'Y-m-d H:i:s') : add.end_dt,
43231                 add.id = add.id || d.id;
43232                 add.title = add.title || '??';
43233                 
43234                 this.addItem(d);
43235                 
43236              
43237             },this);
43238         }
43239         
43240         this.renderEvents();
43241     }
43242     
43243
43244 });
43245 /*
43246  grid : {
43247                 xtype: 'Grid',
43248                 xns: Roo.grid,
43249                 listeners : {
43250                     render : function ()
43251                     {
43252                         _this.grid = this;
43253                         
43254                         if (!this.view.el.hasClass('course-timesheet')) {
43255                             this.view.el.addClass('course-timesheet');
43256                         }
43257                         if (this.tsStyle) {
43258                             this.ds.load({});
43259                             return; 
43260                         }
43261                         Roo.log('width');
43262                         Roo.log(_this.grid.view.el.getWidth());
43263                         
43264                         
43265                         this.tsStyle =  Roo.util.CSS.createStyleSheet({
43266                             '.course-timesheet .x-grid-row' : {
43267                                 height: '80px'
43268                             },
43269                             '.x-grid-row td' : {
43270                                 'vertical-align' : 0
43271                             },
43272                             '.course-edit-link' : {
43273                                 'color' : 'blue',
43274                                 'text-overflow' : 'ellipsis',
43275                                 'overflow' : 'hidden',
43276                                 'white-space' : 'nowrap',
43277                                 'cursor' : 'pointer'
43278                             },
43279                             '.sub-link' : {
43280                                 'color' : 'green'
43281                             },
43282                             '.de-act-sup-link' : {
43283                                 'color' : 'purple',
43284                                 'text-decoration' : 'line-through'
43285                             },
43286                             '.de-act-link' : {
43287                                 'color' : 'red',
43288                                 'text-decoration' : 'line-through'
43289                             },
43290                             '.course-timesheet .course-highlight' : {
43291                                 'border-top-style': 'dashed !important',
43292                                 'border-bottom-bottom': 'dashed !important'
43293                             },
43294                             '.course-timesheet .course-item' : {
43295                                 'font-family'   : 'tahoma, arial, helvetica',
43296                                 'font-size'     : '11px',
43297                                 'overflow'      : 'hidden',
43298                                 'padding-left'  : '10px',
43299                                 'padding-right' : '10px',
43300                                 'padding-top' : '10px' 
43301                             }
43302                             
43303                         }, Roo.id());
43304                                 this.ds.load({});
43305                     }
43306                 },
43307                 autoWidth : true,
43308                 monitorWindowResize : false,
43309                 cellrenderer : function(v,x,r)
43310                 {
43311                     return v;
43312                 },
43313                 sm : {
43314                     xtype: 'CellSelectionModel',
43315                     xns: Roo.grid
43316                 },
43317                 dataSource : {
43318                     xtype: 'Store',
43319                     xns: Roo.data,
43320                     listeners : {
43321                         beforeload : function (_self, options)
43322                         {
43323                             options.params = options.params || {};
43324                             options.params._month = _this.monthField.getValue();
43325                             options.params.limit = 9999;
43326                             options.params['sort'] = 'when_dt';    
43327                             options.params['dir'] = 'ASC';    
43328                             this.proxy.loadResponse = this.loadResponse;
43329                             Roo.log("load?");
43330                             //this.addColumns();
43331                         },
43332                         load : function (_self, records, options)
43333                         {
43334                             _this.grid.view.el.select('.course-edit-link', true).on('click', function() {
43335                                 // if you click on the translation.. you can edit it...
43336                                 var el = Roo.get(this);
43337                                 var id = el.dom.getAttribute('data-id');
43338                                 var d = el.dom.getAttribute('data-date');
43339                                 var t = el.dom.getAttribute('data-time');
43340                                 //var id = this.child('span').dom.textContent;
43341                                 
43342                                 //Roo.log(this);
43343                                 Pman.Dialog.CourseCalendar.show({
43344                                     id : id,
43345                                     when_d : d,
43346                                     when_t : t,
43347                                     productitem_active : id ? 1 : 0
43348                                 }, function() {
43349                                     _this.grid.ds.load({});
43350                                 });
43351                            
43352                            });
43353                            
43354                            _this.panel.fireEvent('resize', [ '', '' ]);
43355                         }
43356                     },
43357                     loadResponse : function(o, success, response){
43358                             // this is overridden on before load..
43359                             
43360                             Roo.log("our code?");       
43361                             //Roo.log(success);
43362                             //Roo.log(response)
43363                             delete this.activeRequest;
43364                             if(!success){
43365                                 this.fireEvent("loadexception", this, o, response);
43366                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
43367                                 return;
43368                             }
43369                             var result;
43370                             try {
43371                                 result = o.reader.read(response);
43372                             }catch(e){
43373                                 Roo.log("load exception?");
43374                                 this.fireEvent("loadexception", this, o, response, e);
43375                                 o.request.callback.call(o.request.scope, null, o.request.arg, false);
43376                                 return;
43377                             }
43378                             Roo.log("ready...");        
43379                             // loop through result.records;
43380                             // and set this.tdate[date] = [] << array of records..
43381                             _this.tdata  = {};
43382                             Roo.each(result.records, function(r){
43383                                 //Roo.log(r.data);
43384                                 if(typeof(_this.tdata[r.data.when_dt.format('j')]) == 'undefined'){
43385                                     _this.tdata[r.data.when_dt.format('j')] = [];
43386                                 }
43387                                 _this.tdata[r.data.when_dt.format('j')].push(r.data);
43388                             });
43389                             
43390                             //Roo.log(_this.tdata);
43391                             
43392                             result.records = [];
43393                             result.totalRecords = 6;
43394                     
43395                             // let's generate some duumy records for the rows.
43396                             //var st = _this.dateField.getValue();
43397                             
43398                             // work out monday..
43399                             //st = st.add(Date.DAY, -1 * st.format('w'));
43400                             
43401                             var date = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
43402                             
43403                             var firstOfMonth = date.getFirstDayOfMonth();
43404                             var days = date.getDaysInMonth();
43405                             var d = 1;
43406                             var firstAdded = false;
43407                             for (var i = 0; i < result.totalRecords ; i++) {
43408                                 //var d= st.add(Date.DAY, i);
43409                                 var row = {};
43410                                 var added = 0;
43411                                 for(var w = 0 ; w < 7 ; w++){
43412                                     if(!firstAdded && firstOfMonth != w){
43413                                         continue;
43414                                     }
43415                                     if(d > days){
43416                                         continue;
43417                                     }
43418                                     firstAdded = true;
43419                                     var dd = (d > 0 && d < 10) ? "0"+d : d;
43420                                     row['weekday'+w] = String.format(
43421                                                     '<span style="font-size: 16px;"><b>{0}</b></span>'+
43422                                                     '<span class="course-edit-link" style="color:blue;" data-id="0" data-date="{1}"> Add New</span>',
43423                                                     d,
43424                                                     date.format('Y-m-')+dd
43425                                                 );
43426                                     added++;
43427                                     if(typeof(_this.tdata[d]) != 'undefined'){
43428                                         Roo.each(_this.tdata[d], function(r){
43429                                             var is_sub = '';
43430                                             var deactive = '';
43431                                             var id = r.id;
43432                                             var desc = (r.productitem_id_descrip) ? r.productitem_id_descrip : '';
43433                                             if(r.parent_id*1>0){
43434                                                 is_sub = (r.productitem_id_visible*1 < 1) ? 'de-act-sup-link' :'sub-link';
43435                                                 id = r.parent_id;
43436                                             }
43437                                             if(r.productitem_id_visible*1 < 1 && r.parent_id*1 < 1){
43438                                                 deactive = 'de-act-link';
43439                                             }
43440                                             
43441                                             row['weekday'+w] += String.format(
43442                                                     '<br /><span class="course-edit-link {3} {4}" qtip="{5}" data-id="{0}">{2} - {1}</span>',
43443                                                     id, //0
43444                                                     r.product_id_name, //1
43445                                                     r.when_dt.format('h:ia'), //2
43446                                                     is_sub, //3
43447                                                     deactive, //4
43448                                                     desc // 5
43449                                             );
43450                                         });
43451                                     }
43452                                     d++;
43453                                 }
43454                                 
43455                                 // only do this if something added..
43456                                 if(added > 0){ 
43457                                     result.records.push(_this.grid.dataSource.reader.newRow(row));
43458                                 }
43459                                 
43460                                 
43461                                 // push it twice. (second one with an hour..
43462                                 
43463                             }
43464                             //Roo.log(result);
43465                             this.fireEvent("load", this, o, o.request.arg);
43466                             o.request.callback.call(o.request.scope, result, o.request.arg, true);
43467                         },
43468                     sortInfo : {field: 'when_dt', direction : 'ASC' },
43469                     proxy : {
43470                         xtype: 'HttpProxy',
43471                         xns: Roo.data,
43472                         method : 'GET',
43473                         url : baseURL + '/Roo/Shop_course.php'
43474                     },
43475                     reader : {
43476                         xtype: 'JsonReader',
43477                         xns: Roo.data,
43478                         id : 'id',
43479                         fields : [
43480                             {
43481                                 'name': 'id',
43482                                 'type': 'int'
43483                             },
43484                             {
43485                                 'name': 'when_dt',
43486                                 'type': 'string'
43487                             },
43488                             {
43489                                 'name': 'end_dt',
43490                                 'type': 'string'
43491                             },
43492                             {
43493                                 'name': 'parent_id',
43494                                 'type': 'int'
43495                             },
43496                             {
43497                                 'name': 'product_id',
43498                                 'type': 'int'
43499                             },
43500                             {
43501                                 'name': 'productitem_id',
43502                                 'type': 'int'
43503                             },
43504                             {
43505                                 'name': 'guid',
43506                                 'type': 'int'
43507                             }
43508                         ]
43509                     }
43510                 },
43511                 toolbar : {
43512                     xtype: 'Toolbar',
43513                     xns: Roo,
43514                     items : [
43515                         {
43516                             xtype: 'Button',
43517                             xns: Roo.Toolbar,
43518                             listeners : {
43519                                 click : function (_self, e)
43520                                 {
43521                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
43522                                     sd.setMonth(sd.getMonth()-1);
43523                                     _this.monthField.setValue(sd.format('Y-m-d'));
43524                                     _this.grid.ds.load({});
43525                                 }
43526                             },
43527                             text : "Back"
43528                         },
43529                         {
43530                             xtype: 'Separator',
43531                             xns: Roo.Toolbar
43532                         },
43533                         {
43534                             xtype: 'MonthField',
43535                             xns: Roo.form,
43536                             listeners : {
43537                                 render : function (_self)
43538                                 {
43539                                     _this.monthField = _self;
43540                                    // _this.monthField.set  today
43541                                 },
43542                                 select : function (combo, date)
43543                                 {
43544                                     _this.grid.ds.load({});
43545                                 }
43546                             },
43547                             value : (function() { return new Date(); })()
43548                         },
43549                         {
43550                             xtype: 'Separator',
43551                             xns: Roo.Toolbar
43552                         },
43553                         {
43554                             xtype: 'TextItem',
43555                             xns: Roo.Toolbar,
43556                             text : "Blue: in-active, green: in-active sup-event, red: de-active, purple: de-active sup-event"
43557                         },
43558                         {
43559                             xtype: 'Fill',
43560                             xns: Roo.Toolbar
43561                         },
43562                         {
43563                             xtype: 'Button',
43564                             xns: Roo.Toolbar,
43565                             listeners : {
43566                                 click : function (_self, e)
43567                                 {
43568                                     var sd = Date.parseDate(_this.monthField.getValue(), "Y-m-d");
43569                                     sd.setMonth(sd.getMonth()+1);
43570                                     _this.monthField.setValue(sd.format('Y-m-d'));
43571                                     _this.grid.ds.load({});
43572                                 }
43573                             },
43574                             text : "Next"
43575                         }
43576                     ]
43577                 },
43578                  
43579             }
43580         };
43581         
43582         *//*
43583  * Based on:
43584  * Ext JS Library 1.1.1
43585  * Copyright(c) 2006-2007, Ext JS, LLC.
43586  *
43587  * Originally Released Under LGPL - original licence link has changed is not relivant.
43588  *
43589  * Fork - LGPL
43590  * <script type="text/javascript">
43591  */
43592  
43593 /**
43594  * @class Roo.LoadMask
43595  * A simple utility class for generically masking elements while loading data.  If the element being masked has
43596  * an underlying {@link Roo.data.Store}, the masking will be automatically synchronized with the store's loading
43597  * process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
43598  * element's UpdateManager load indicator and will be destroyed after the initial load.
43599  * @constructor
43600  * Create a new LoadMask
43601  * @param {String/HTMLElement/Roo.Element} el The element or DOM node, or its id
43602  * @param {Object} config The config object
43603  */
43604 Roo.LoadMask = function(el, config){
43605     this.el = Roo.get(el);
43606     Roo.apply(this, config);
43607     if(this.store){
43608         this.store.on('beforeload', this.onBeforeLoad, this);
43609         this.store.on('load', this.onLoad, this);
43610         this.store.on('loadexception', this.onLoadException, this);
43611         this.removeMask = false;
43612     }else{
43613         var um = this.el.getUpdateManager();
43614         um.showLoadIndicator = false; // disable the default indicator
43615         um.on('beforeupdate', this.onBeforeLoad, this);
43616         um.on('update', this.onLoad, this);
43617         um.on('failure', this.onLoad, this);
43618         this.removeMask = true;
43619     }
43620 };
43621
43622 Roo.LoadMask.prototype = {
43623     /**
43624      * @cfg {Boolean} removeMask
43625      * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
43626      * False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
43627      */
43628     removeMask : false,
43629     /**
43630      * @cfg {String} msg
43631      * The text to display in a centered loading message box (defaults to 'Loading...')
43632      */
43633     msg : 'Loading...',
43634     /**
43635      * @cfg {String} msgCls
43636      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
43637      */
43638     msgCls : 'x-mask-loading',
43639
43640     /**
43641      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
43642      * @type Boolean
43643      */
43644     disabled: false,
43645
43646     /**
43647      * Disables the mask to prevent it from being displayed
43648      */
43649     disable : function(){
43650        this.disabled = true;
43651     },
43652
43653     /**
43654      * Enables the mask so that it can be displayed
43655      */
43656     enable : function(){
43657         this.disabled = false;
43658     },
43659     
43660     onLoadException : function()
43661     {
43662         Roo.log(arguments);
43663         
43664         if (typeof(arguments[3]) != 'undefined') {
43665             Roo.MessageBox.alert("Error loading",arguments[3]);
43666         } 
43667         /*
43668         try {
43669             if (this.store && typeof(this.store.reader.jsonData.errorMsg) != 'undefined') {
43670                 Roo.MessageBox.alert("Error loading",this.store.reader.jsonData.errorMsg);
43671             }   
43672         } catch(e) {
43673             
43674         }
43675         */
43676     
43677         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
43678     },
43679     // private
43680     onLoad : function()
43681     {
43682         (function() { this.el.unmask(this.removeMask); }).defer(50, this);
43683     },
43684
43685     // private
43686     onBeforeLoad : function(){
43687         if(!this.disabled){
43688             (function() { this.el.mask(this.msg, this.msgCls); }).defer(50, this);
43689         }
43690     },
43691
43692     // private
43693     destroy : function(){
43694         if(this.store){
43695             this.store.un('beforeload', this.onBeforeLoad, this);
43696             this.store.un('load', this.onLoad, this);
43697             this.store.un('loadexception', this.onLoadException, this);
43698         }else{
43699             var um = this.el.getUpdateManager();
43700             um.un('beforeupdate', this.onBeforeLoad, this);
43701             um.un('update', this.onLoad, this);
43702             um.un('failure', this.onLoad, this);
43703         }
43704     }
43705 };/*
43706  * Based on:
43707  * Ext JS Library 1.1.1
43708  * Copyright(c) 2006-2007, Ext JS, LLC.
43709  *
43710  * Originally Released Under LGPL - original licence link has changed is not relivant.
43711  *
43712  * Fork - LGPL
43713  * <script type="text/javascript">
43714  */
43715
43716
43717 /**
43718  * @class Roo.XTemplate
43719  * @extends Roo.Template
43720  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
43721 <pre><code>
43722 var t = new Roo.XTemplate(
43723         '&lt;select name="{name}"&gt;',
43724                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
43725         '&lt;/select&gt;'
43726 );
43727  
43728 // then append, applying the master template values
43729  </code></pre>
43730  *
43731  * Supported features:
43732  *
43733  *  Tags:
43734
43735 <pre><code>
43736       {a_variable} - output encoded.
43737       {a_variable.format:("Y-m-d")} - call a method on the variable
43738       {a_variable:raw} - unencoded output
43739       {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
43740       {a_variable:this.method_on_template(...)} - call a method on the template object.
43741  
43742 </code></pre>
43743  *  The tpl tag:
43744 <pre><code>
43745         &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
43746         &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
43747         &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
43748         &lt;tpl name="named_template"&gt;&lt;/tpl&gt; (experimental)
43749   
43750         &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
43751         &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
43752 </code></pre>
43753  *      
43754  */
43755 Roo.XTemplate = function()
43756 {
43757     Roo.XTemplate.superclass.constructor.apply(this, arguments);
43758     if (this.html) {
43759         this.compile();
43760     }
43761 };
43762
43763
43764 Roo.extend(Roo.XTemplate, Roo.Template, {
43765
43766     /**
43767      * The various sub templates
43768      */
43769     tpls : false,
43770     /**
43771      *
43772      * basic tag replacing syntax
43773      * WORD:WORD()
43774      *
43775      * // you can fake an object call by doing this
43776      *  x.t:(test,tesT) 
43777      * 
43778      */
43779     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
43780
43781     /**
43782      * compile the template
43783      *
43784      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
43785      *
43786      */
43787     compile: function()
43788     {
43789         var s = this.html;
43790      
43791         s = ['<tpl>', s, '</tpl>'].join('');
43792     
43793         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
43794             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
43795             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
43796             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
43797             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
43798             m,
43799             id     = 0,
43800             tpls   = [];
43801     
43802         while(true == !!(m = s.match(re))){
43803             var forMatch   = m[0].match(nameRe),
43804                 ifMatch   = m[0].match(ifRe),
43805                 execMatch   = m[0].match(execRe),
43806                 namedMatch   = m[0].match(namedRe),
43807                 
43808                 exp  = null, 
43809                 fn   = null,
43810                 exec = null,
43811                 name = forMatch && forMatch[1] ? forMatch[1] : '';
43812                 
43813             if (ifMatch) {
43814                 // if - puts fn into test..
43815                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
43816                 if(exp){
43817                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
43818                 }
43819             }
43820             
43821             if (execMatch) {
43822                 // exec - calls a function... returns empty if true is  returned.
43823                 exp = execMatch && execMatch[1] ? execMatch[1] : null;
43824                 if(exp){
43825                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
43826                 }
43827             }
43828             
43829             
43830             if (name) {
43831                 // for = 
43832                 switch(name){
43833                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
43834                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
43835                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
43836                 }
43837             }
43838             var uid = namedMatch ? namedMatch[1] : id;
43839             
43840             
43841             tpls.push({
43842                 id:     namedMatch ? namedMatch[1] : id,
43843                 target: name,
43844                 exec:   exec,
43845                 test:   fn,
43846                 body:   m[1] || ''
43847             });
43848             if (namedMatch) {
43849                 s = s.replace(m[0], '');
43850             } else { 
43851                 s = s.replace(m[0], '{xtpl'+ id + '}');
43852             }
43853             ++id;
43854         }
43855         this.tpls = [];
43856         for(var i = tpls.length-1; i >= 0; --i){
43857             this.compileTpl(tpls[i]);
43858             this.tpls[tpls[i].id] = tpls[i];
43859         }
43860         this.master = tpls[tpls.length-1];
43861         return this;
43862     },
43863     /**
43864      * same as applyTemplate, except it's done to one of the subTemplates
43865      * when using named templates, you can do:
43866      *
43867      * var str = pl.applySubTemplate('your-name', values);
43868      *
43869      * 
43870      * @param {Number} id of the template
43871      * @param {Object} values to apply to template
43872      * @param {Object} parent (normaly the instance of this object)
43873      */
43874     applySubTemplate : function(id, values, parent)
43875     {
43876         
43877         
43878         var t = this.tpls[id];
43879         
43880         
43881         try { 
43882             if(t.test && !t.test.call(this, values, parent)){
43883                 return '';
43884             }
43885         } catch(e) {
43886             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
43887             Roo.log(e.toString());
43888             Roo.log(t.test);
43889             return ''
43890         }
43891         try { 
43892             
43893             if(t.exec && t.exec.call(this, values, parent)){
43894                 return '';
43895             }
43896         } catch(e) {
43897             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
43898             Roo.log(e.toString());
43899             Roo.log(t.exec);
43900             return ''
43901         }
43902         try {
43903             var vs = t.target ? t.target.call(this, values, parent) : values;
43904             parent = t.target ? values : parent;
43905             if(t.target && vs instanceof Array){
43906                 var buf = [];
43907                 for(var i = 0, len = vs.length; i < len; i++){
43908                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
43909                 }
43910                 return buf.join('');
43911             }
43912             return t.compiled.call(this, vs, parent);
43913         } catch (e) {
43914             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
43915             Roo.log(e.toString());
43916             Roo.log(t.compiled);
43917             return '';
43918         }
43919     },
43920
43921     compileTpl : function(tpl)
43922     {
43923         var fm = Roo.util.Format;
43924         var useF = this.disableFormats !== true;
43925         var sep = Roo.isGecko ? "+" : ",";
43926         var undef = function(str) {
43927             Roo.log("Property not found :"  + str);
43928             return '';
43929         };
43930         
43931         var fn = function(m, name, format, args)
43932         {
43933             //Roo.log(arguments);
43934             args = args ? args.replace(/\\'/g,"'") : args;
43935             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
43936             if (typeof(format) == 'undefined') {
43937                 format= 'htmlEncode';
43938             }
43939             if (format == 'raw' ) {
43940                 format = false;
43941             }
43942             
43943             if(name.substr(0, 4) == 'xtpl'){
43944                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
43945             }
43946             
43947             // build an array of options to determine if value is undefined..
43948             
43949             // basically get 'xxxx.yyyy' then do
43950             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
43951             //    (function () { Roo.log("Property not found"); return ''; })() :
43952             //    ......
43953             
43954             var udef_ar = [];
43955             var lookfor = '';
43956             Roo.each(name.split('.'), function(st) {
43957                 lookfor += (lookfor.length ? '.': '') + st;
43958                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
43959             });
43960             
43961             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
43962             
43963             
43964             if(format && useF){
43965                 
43966                 args = args ? ',' + args : "";
43967                  
43968                 if(format.substr(0, 5) != "this."){
43969                     format = "fm." + format + '(';
43970                 }else{
43971                     format = 'this.call("'+ format.substr(5) + '", ';
43972                     args = ", values";
43973                 }
43974                 
43975                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
43976             }
43977              
43978             if (args.length) {
43979                 // called with xxyx.yuu:(test,test)
43980                 // change to ()
43981                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
43982             }
43983             // raw.. - :raw modifier..
43984             return "'"+ sep + udef_st  + name + ")"+sep+"'";
43985             
43986         };
43987         var body;
43988         // branched to use + in gecko and [].join() in others
43989         if(Roo.isGecko){
43990             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
43991                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
43992                     "';};};";
43993         }else{
43994             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
43995             body.push(tpl.body.replace(/(\r\n|\n)/g,
43996                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
43997             body.push("'].join('');};};");
43998             body = body.join('');
43999         }
44000         
44001         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
44002        
44003         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
44004         eval(body);
44005         
44006         return this;
44007     },
44008
44009     applyTemplate : function(values){
44010         return this.master.compiled.call(this, values, {});
44011         //var s = this.subs;
44012     },
44013
44014     apply : function(){
44015         return this.applyTemplate.apply(this, arguments);
44016     }
44017
44018  });
44019
44020 Roo.XTemplate.from = function(el){
44021     el = Roo.getDom(el);
44022     return new Roo.XTemplate(el.value || el.innerHTML);
44023 };Roo.dialog = {};
44024 /*
44025 * Licence: LGPL
44026 */
44027
44028 /**
44029  * @class Roo.dialog.UploadCropbox
44030  * @extends Roo.BoxComponent
44031  * Dialog UploadCropbox class
44032  * @cfg {String} emptyText show when image has been loaded
44033  * @cfg {String} rotateNotify show when image too small to rotate
44034  * @cfg {Number} errorTimeout default 3000
44035  * @cfg {Number} minWidth default 300
44036  * @cfg {Number} minHeight default 300
44037  * @cfg {Number} outputMaxWidth default 1200
44038  * @cfg {Number} windowSize default 300
44039  * @cfg {Array} buttons default ['rotateLeft', 'pictureBtn', 'rotateRight']
44040  * @cfg {Boolean} isDocument (true|false) default false
44041  * @cfg {String} url action url
44042  * @cfg {String} paramName default 'imageUpload'
44043  * @cfg {String} method default POST
44044  * @cfg {Boolean} loadMask (true|false) default true
44045  * @cfg {Boolean} loadingText default 'Loading...'
44046  * 
44047  * @constructor
44048  * Create a new UploadCropbox
44049  * @param {Object} config The config object
44050  */
44051
44052  Roo.dialog.UploadCropbox = function(config){
44053     Roo.dialog.UploadCropbox.superclass.constructor.call(this, config);
44054     
44055     this.addEvents({
44056         /**
44057          * @event beforeselectfile
44058          * Fire before select file
44059          * @param {Roo.dialog.UploadCropbox} this
44060          */
44061         "beforeselectfile" : true,
44062         /**
44063          * @event initial
44064          * Fire after initEvent
44065          * @param {Roo.dialog.UploadCropbox} this
44066          */
44067         "initial" : true,
44068         /**
44069          * @event crop
44070          * Fire after initEvent
44071          * @param {Roo.dialog.UploadCropbox} this
44072          * @param {String} data
44073          */
44074         "crop" : true,
44075         /**
44076          * @event prepare
44077          * Fire when preparing the file data
44078          * @param {Roo.dialog.UploadCropbox} this
44079          * @param {Object} file
44080          */
44081         "prepare" : true,
44082         /**
44083          * @event exception
44084          * Fire when get exception
44085          * @param {Roo.dialog.UploadCropbox} this
44086          * @param {XMLHttpRequest} xhr
44087          */
44088         "exception" : true,
44089         /**
44090          * @event beforeloadcanvas
44091          * Fire before load the canvas
44092          * @param {Roo.dialog.UploadCropbox} this
44093          * @param {String} src
44094          */
44095         "beforeloadcanvas" : true,
44096         /**
44097          * @event trash
44098          * Fire when trash image
44099          * @param {Roo.dialog.UploadCropbox} this
44100          */
44101         "trash" : true,
44102         /**
44103          * @event download
44104          * Fire when download the image
44105          * @param {Roo.dialog.UploadCropbox} this
44106          */
44107         "download" : true,
44108         /**
44109          * @event footerbuttonclick
44110          * Fire when footerbuttonclick
44111          * @param {Roo.dialog.UploadCropbox} this
44112          * @param {String} type
44113          */
44114         "footerbuttonclick" : true,
44115         /**
44116          * @event resize
44117          * Fire when resize
44118          * @param {Roo.dialog.UploadCropbox} this
44119          */
44120         "resize" : true,
44121         /**
44122          * @event rotate
44123          * Fire when rotate the image
44124          * @param {Roo.dialog.UploadCropbox} this
44125          * @param {String} pos
44126          */
44127         "rotate" : true,
44128         /**
44129          * @event inspect
44130          * Fire when inspect the file
44131          * @param {Roo.dialog.UploadCropbox} this
44132          * @param {Object} file
44133          */
44134         "inspect" : true,
44135         /**
44136          * @event upload
44137          * Fire when xhr upload the file
44138          * @param {Roo.dialog.UploadCropbox} this
44139          * @param {Object} data
44140          */
44141         "upload" : true,
44142         /**
44143          * @event arrange
44144          * Fire when arrange the file data
44145          * @param {Roo.dialog.UploadCropbox} this
44146          * @param {Object} formData
44147          */
44148         "arrange" : true,
44149         /**
44150          * @event loadcanvas
44151          * Fire after load the canvas
44152          * @param {Roo.dialog.UploadCropbox}
44153          * @param {Object} imgEl
44154          */
44155         "loadcanvas" : true
44156     });
44157     
44158     this.buttons = this.buttons || Roo.dialog.UploadCropbox.footer.STANDARD;
44159 };
44160
44161 Roo.extend(Roo.dialog.UploadCropbox, Roo.Component,  {
44162     
44163     emptyText : 'Click to upload image',
44164     rotateNotify : 'Image is too small to rotate',
44165     errorTimeout : 3000,
44166     scale : 0,
44167     baseScale : 1,
44168     rotate : 0,
44169     dragable : false,
44170     pinching : false,
44171     mouseX : 0,
44172     mouseY : 0,
44173     cropData : false,
44174     minWidth : 300,
44175     minHeight : 300,
44176     outputMaxWidth : 1200,
44177     windowSize : 300,
44178     file : false,
44179     exif : {},
44180     baseRotate : 1,
44181     cropType : 'image/jpeg',
44182     buttons : false,
44183     canvasLoaded : false,
44184     isDocument : false,
44185     method : 'POST',
44186     paramName : 'imageUpload',
44187     loadMask : true,
44188     loadingText : 'Loading...',
44189     maskEl : false,
44190     
44191     getAutoCreate : function()
44192     {
44193         var cfg = {
44194             tag : 'div',
44195             cls : 'roo-upload-cropbox',
44196             cn : [
44197                 {
44198                     tag : 'input',
44199                     cls : 'roo-upload-cropbox-selector',
44200                     type : 'file'
44201                 },
44202                 {
44203                     tag : 'div',
44204                     cls : 'roo-upload-cropbox-body',
44205                     style : 'cursor:pointer',
44206                     cn : [
44207                         {
44208                             tag : 'div',
44209                             cls : 'roo-upload-cropbox-preview'
44210                         },
44211                         {
44212                             tag : 'div',
44213                             cls : 'roo-upload-cropbox-thumb'
44214                         },
44215                         {
44216                             tag : 'div',
44217                             cls : 'roo-upload-cropbox-empty-notify',
44218                             html : this.emptyText
44219                         },
44220                         {
44221                             tag : 'div',
44222                             cls : 'roo-upload-cropbox-error-notify alert alert-danger',
44223                             html : this.rotateNotify
44224                         }
44225                     ]
44226                 },
44227                 {
44228                     tag : 'div',
44229                     cls : 'roo-upload-cropbox-footer',
44230                     cn : {
44231                         tag : 'div',
44232                         cls : 'btn-group btn-group-justified roo-upload-cropbox-btn-group',
44233                         cn : []
44234                     }
44235                 }
44236             ]
44237         };
44238         
44239         return cfg;
44240     },
44241     
44242     onRender : function(ct, position)
44243     {
44244         Roo.dialog.UploadCropbox.superclass.onRender.call(this, ct, position);
44245
44246         if(this.el){
44247             if (this.el.attr('xtype')) {
44248                 this.el.attr('xtypex', this.el.attr('xtype'));
44249                 this.el.dom.removeAttribute('xtype');
44250                 
44251                 this.initEvents();
44252             }
44253         }
44254         else {
44255             var cfg = Roo.apply({},  this.getAutoCreate());
44256         
44257             cfg.id = this.id || Roo.id();
44258             
44259             if (this.cls) {
44260                 cfg.cls = (typeof(cfg.cls) == 'undefined' ? this.cls : cfg.cls) + ' ' + this.cls;
44261             }
44262             
44263             if (this.style) { // fixme needs to support more complex style data.
44264                 cfg.style = (typeof(cfg.style) == 'undefined' ? this.style : cfg.style) + '; ' + this.style;
44265             }
44266             
44267             this.el = ct.createChild(cfg, position);
44268             
44269             this.initEvents();
44270         }
44271         
44272         if (this.buttons.length) {
44273             
44274             Roo.each(this.buttons, function(bb) {
44275                 
44276                 var btn = this.el.select('.roo-upload-cropbox-footer div.roo-upload-cropbox-btn-group').first().createChild(bb);
44277                 
44278                 btn.on('click', this.onFooterButtonClick.createDelegate(this, [bb.action], true));
44279                 
44280             }, this);
44281         }
44282         
44283         if(this.loadMask){
44284             this.maskEl = this.el;
44285         }
44286     },
44287     
44288     initEvents : function()
44289     {
44290         this.urlAPI = (window.createObjectURL && window) || 
44291                                 (window.URL && URL.revokeObjectURL && URL) || 
44292                                 (window.webkitURL && webkitURL);
44293                         
44294         this.bodyEl = this.el.select('.roo-upload-cropbox-body', true).first();
44295         this.bodyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
44296         
44297         this.selectorEl = this.el.select('.roo-upload-cropbox-selector', true).first();
44298         this.selectorEl.hide();
44299         
44300         this.previewEl = this.el.select('.roo-upload-cropbox-preview', true).first();
44301         this.previewEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
44302         
44303         this.thumbEl = this.el.select('.roo-upload-cropbox-thumb', true).first();
44304         this.thumbEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
44305         this.thumbEl.hide();
44306         
44307         this.notifyEl = this.el.select('.roo-upload-cropbox-empty-notify', true).first();
44308         this.notifyEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
44309         
44310         this.errorEl = this.el.select('.roo-upload-cropbox-error-notify', true).first();
44311         this.errorEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
44312         this.errorEl.hide();
44313         
44314         this.footerEl = this.el.select('.roo-upload-cropbox-footer', true).first();
44315         this.footerEl.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';
44316         this.footerEl.hide();
44317         
44318         this.setThumbBoxSize();
44319         
44320         this.bind();
44321         
44322         this.resize();
44323         
44324         this.fireEvent('initial', this);
44325     },
44326
44327     bind : function()
44328     {
44329         var _this = this;
44330         
44331         window.addEventListener("resize", function() { _this.resize(); } );
44332         
44333         this.bodyEl.on('click', this.beforeSelectFile, this);
44334         
44335         if(Roo.isTouch){
44336             this.bodyEl.on('touchstart', this.onTouchStart, this);
44337             this.bodyEl.on('touchmove', this.onTouchMove, this);
44338             this.bodyEl.on('touchend', this.onTouchEnd, this);
44339         }
44340         
44341         if(!Roo.isTouch){
44342             this.bodyEl.on('mousedown', this.onMouseDown, this);
44343             this.bodyEl.on('mousemove', this.onMouseMove, this);
44344             var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
44345             this.bodyEl.on(mousewheel, this.onMouseWheel, this);
44346             Roo.get(document).on('mouseup', this.onMouseUp, this);
44347         }
44348         
44349         this.selectorEl.on('change', this.onFileSelected, this);
44350     },
44351     
44352     reset : function()
44353     {    
44354         this.scale = 0;
44355         this.baseScale = 1;
44356         this.rotate = 0;
44357         this.baseRotate = 1;
44358         this.dragable = false;
44359         this.pinching = false;
44360         this.mouseX = 0;
44361         this.mouseY = 0;
44362         this.cropData = false;
44363         this.notifyEl.dom.innerHTML = this.emptyText;
44364         
44365         // this.selectorEl.dom.value = '';
44366         
44367     },
44368     
44369     resize : function()
44370     {
44371         if(this.fireEvent('resize', this) != false){
44372             this.setThumbBoxPosition();
44373             this.setCanvasPosition();
44374         }
44375     },
44376     
44377     onFooterButtonClick : function(e, el, o, type)
44378     {
44379         switch (type) {
44380             case 'rotate-left' :
44381                 this.onRotateLeft(e);
44382                 break;
44383             case 'rotate-right' :
44384                 this.onRotateRight(e);
44385                 break;
44386             case 'picture' :
44387                 this.beforeSelectFile(e);
44388                 break;
44389             case 'trash' :
44390                 this.trash(e);
44391                 break;
44392             case 'crop' :
44393                 this.crop(e);
44394                 break;
44395             case 'download' :
44396                 this.download(e);
44397                 break;
44398             case 'center' :
44399                 this.center(e);
44400                 break;
44401             default :
44402                 break;
44403         }
44404         
44405         this.fireEvent('footerbuttonclick', this, type);
44406     },
44407     
44408     beforeSelectFile : function(e)
44409     {
44410         e.preventDefault();
44411         
44412         if(this.fireEvent('beforeselectfile', this) != false){
44413             this.selectorEl.dom.click();
44414         }
44415     },
44416     
44417     onFileSelected : function(e)
44418     {
44419         e.preventDefault();
44420         
44421         if(typeof(this.selectorEl.dom.files) == 'undefined' || !this.selectorEl.dom.files.length){
44422             return;
44423         }
44424         
44425         var file = this.selectorEl.dom.files[0];
44426         
44427         if(this.fireEvent('inspect', this, file) != false){
44428             this.prepare(file);
44429         }
44430         
44431     },
44432     
44433     trash : function(e)
44434     {
44435         this.fireEvent('trash', this);
44436     },
44437     
44438     download : function(e)
44439     {
44440         this.fireEvent('download', this);
44441     },
44442
44443     center : function(e)
44444     {
44445         this.setCanvasPosition();
44446     },
44447     
44448     loadCanvas : function(src)
44449     {   
44450         if(this.fireEvent('beforeloadcanvas', this, src) != false){
44451             
44452             this.reset();
44453             
44454             this.imageEl = document.createElement('img');
44455             
44456             var _this = this;
44457             
44458             this.imageEl.addEventListener("load", function(){ _this.onLoadCanvas(); });
44459             
44460             this.imageEl.src = src;
44461         }
44462     },
44463     
44464     onLoadCanvas : function()
44465     {   
44466         this.imageEl.OriginWidth = this.imageEl.naturalWidth || this.imageEl.width;
44467         this.imageEl.OriginHeight = this.imageEl.naturalHeight || this.imageEl.height;
44468
44469         if(this.fireEvent('loadcanvas', this, this.imageEl) != false){
44470         
44471             this.bodyEl.un('click', this.beforeSelectFile, this);
44472             
44473             this.notifyEl.hide();
44474             this.thumbEl.show();
44475             this.footerEl.show();
44476             
44477             this.baseRotateLevel();
44478             
44479             if(this.isDocument){
44480                 this.setThumbBoxSize();
44481             }
44482             
44483             this.setThumbBoxPosition();
44484             
44485             this.baseScaleLevel();
44486             
44487             this.draw();
44488             
44489             this.resize();
44490             
44491             this.canvasLoaded = true;
44492         
44493         }
44494         
44495         if(this.loadMask){
44496             this.maskEl.unmask();
44497         }
44498         
44499     },
44500     
44501     setCanvasPosition : function(center = true)
44502     {   
44503         if(!this.canvasEl){
44504             return;
44505         }
44506
44507         var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
44508         var newCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
44509
44510         if(center) {
44511             this.previewEl.setLeft(newCenterLeft);
44512             this.previewEl.setTop(newCenterTop);
44513
44514             return;
44515         }
44516         
44517         var oldScaleLevel = this.baseScale * Math.pow(1.02, this.startScale);
44518         var oldCanvasWidth = Math.floor(this.imageEl.OriginWidth * oldScaleLevel);
44519         var oldCanvasHeight = Math.floor(this.imageEl.OriginHeight * oldScaleLevel);
44520
44521         var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - oldCanvasWidth) / 2);
44522         var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - oldCanvasHeight) / 2);
44523
44524         var leftDiff = newCenterLeft - oldCenterLeft;
44525         var topDiff = newCenterTop - oldCenterTop;
44526
44527         var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
44528         var newPreviewTop = this.previewEl.getTop(true) + topDiff;
44529
44530         this.previewEl.setLeft(newPreviewLeft);
44531         this.previewEl.setTop(newPreviewTop);
44532         
44533     },
44534     
44535     onMouseDown : function(e)
44536     {   
44537         e.stopEvent();
44538         
44539         this.dragable = true;
44540         this.pinching = false;
44541         
44542         if(this.isDocument && (this.canvasEl.width < this.thumbEl.getWidth() || this.canvasEl.height < this.thumbEl.getHeight())){
44543             this.dragable = false;
44544             return;
44545         }
44546         
44547         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
44548         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
44549         
44550     },
44551     
44552     onMouseMove : function(e)
44553     {   
44554         e.stopEvent();
44555         
44556         if(!this.canvasLoaded){
44557             return;
44558         }
44559         
44560         if (!this.dragable){
44561             return;
44562         }
44563
44564         var maxPaddingLeft = this.canvasEl.width / 0.9 * 0.05;
44565         var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
44566
44567         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
44568             maxPaddingLeft = (this.canvasEl.height * this.minWidth / this.minHeight - this.canvasEl.width) / 2 + maxPaddingLeft;
44569         }
44570
44571         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
44572             maxPaddingTop = (this.canvasEl.width * this.minHeight / this.minWidth - this.canvasEl.height) / 2 + maxPaddingTop;
44573         }
44574         
44575         var minX = Math.ceil(this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - this.canvasEl.width - maxPaddingLeft);
44576         var minY = Math.ceil(this.thumbEl.getTop(true) + this.thumbEl.getHeight() - this.canvasEl.height - maxPaddingTop);
44577         
44578         var maxX = Math.ceil(this.thumbEl.getLeft(true) + maxPaddingLeft);
44579         var maxY = Math.ceil(this.thumbEl.getTop(true) +  maxPaddingTop);
44580
44581         if(minX > maxX) {
44582             var tempX = minX;
44583             minX = maxX;
44584             maxX = tempX;
44585         }
44586
44587         if(minY > maxY) {
44588             var tempY = minY;
44589             minY = maxY;
44590             maxY = tempY;
44591         }
44592
44593         var x = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
44594         var y = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
44595         
44596         x = x - this.mouseX;
44597         y = y - this.mouseY;
44598
44599         var bgX = Math.ceil(x + this.previewEl.getLeft(true));
44600         var bgY = Math.ceil(y + this.previewEl.getTop(true));
44601         
44602         bgX = (bgX < minX) ? minX : ((bgX > maxX) ? maxX : bgX);
44603         bgY = (bgY < minY) ? minY : ((bgY > maxY) ? maxY : bgY);
44604         
44605         this.previewEl.setLeft(bgX);
44606         this.previewEl.setTop(bgY);
44607         
44608         this.mouseX = Roo.isTouch ? e.browserEvent.touches[0].pageX : e.getPageX();
44609         this.mouseY = Roo.isTouch ? e.browserEvent.touches[0].pageY : e.getPageY();
44610     },
44611     
44612     onMouseUp : function(e)
44613     {   
44614         e.stopEvent();
44615         
44616         this.dragable = false;
44617     },
44618     
44619     onMouseWheel : function(e)
44620     {   
44621         e.stopEvent();
44622         
44623         this.startScale = this.scale;
44624         this.scale = (e.getWheelDelta() > 0) ? (this.scale + 1) : (this.scale - 1);
44625         
44626         if(!this.zoomable()){
44627             this.scale = this.startScale;
44628             return;
44629         }
44630
44631         
44632         this.draw();
44633         
44634         return;
44635     },
44636     
44637     zoomable : function()
44638     {
44639         var minScale = this.thumbEl.getWidth() / this.minWidth;
44640         
44641         if(this.minWidth < this.minHeight){
44642             minScale = this.thumbEl.getHeight() / this.minHeight;
44643         }
44644         
44645         var width = Math.ceil(this.imageEl.OriginWidth * this.getScaleLevel() / minScale);
44646         var height = Math.ceil(this.imageEl.OriginHeight * this.getScaleLevel() / minScale);
44647  
44648         var maxWidth = this.imageEl.OriginWidth;
44649         var maxHeight = this.imageEl.OriginHeight;
44650
44651
44652         var newCanvasWidth = Math.floor(this.imageEl.OriginWidth * this.getScaleLevel());
44653         var newCanvasHeight = Math.floor(this.imageEl.OriginHeight * this.getScaleLevel());
44654
44655         var oldCenterLeft = Math.ceil((this.bodyEl.getWidth() - this.canvasEl.width) / 2);
44656         var oldCenterTop = Math.ceil((this.bodyEl.getHeight() - this.canvasEl.height) / 2);
44657
44658         var newCenterLeft = Math.ceil((this.bodyEl.getWidth() - newCanvasWidth) / 2);
44659         var newCenterTop = Math.ceil((this.bodyEl.getHeight() - newCanvasHeight) / 2);
44660
44661         var leftDiff = newCenterLeft - oldCenterLeft;
44662         var topDiff = newCenterTop - oldCenterTop;
44663
44664         var newPreviewLeft = this.previewEl.getLeft(true) + leftDiff;
44665         var newPreviewTop = this.previewEl.getTop(true) + topDiff;
44666
44667         var paddingLeft = newPreviewLeft - this.thumbEl.getLeft(true);
44668         var paddingTop = newPreviewTop - this.thumbEl.getTop(true);
44669
44670         var paddingRight = this.thumbEl.getLeft(true) + this.thumbEl.getWidth() - newCanvasWidth - newPreviewLeft;
44671         var paddingBottom = this.thumbEl.getTop(true) + this.thumbEl.getHeight() - newCanvasHeight - newPreviewTop;
44672
44673         var maxPaddingLeft = newCanvasWidth / 0.9 * 0.05;
44674         var maxPaddingTop = maxPaddingLeft * this.minHeight / this.minWidth;
44675
44676         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight <= this.minWidth / this.minHeight)) {
44677             maxPaddingLeft = (newCanvasHeight * this.minWidth / this.minHeight - newCanvasWidth) / 2 + maxPaddingLeft;
44678         }
44679
44680         if ((this.imageEl.OriginWidth / this.imageEl.OriginHeight >= this.minWidth / this.minHeight)) {
44681             maxPaddingTop = (newCanvasWidth * this.minHeight / this.minWidth - newCanvasHeight) / 2 + maxPaddingTop;
44682         }
44683         
44684         if(
44685                 this.isDocument &&
44686                 (this.rotate == 0 || this.rotate == 180) && 
44687                 (
44688                     width > this.imageEl.OriginWidth || 
44689                     height > this.imageEl.OriginHeight ||
44690                     (width < this.minWidth && height < this.minHeight)
44691                 )
44692         ){
44693             return false;
44694         }
44695         
44696         if(
44697                 this.isDocument &&
44698                 (this.rotate == 90 || this.rotate == 270) && 
44699                 (
44700                     width > this.imageEl.OriginWidth || 
44701                     height > this.imageEl.OriginHeight ||
44702                     (width < this.minHeight && height < this.minWidth)
44703                 )
44704         ){
44705             return false;
44706         }
44707         
44708         if(
44709                 !this.isDocument &&
44710                 (this.rotate == 0 || this.rotate == 180) && 
44711                 (
44712                     // for zoom out
44713                     paddingLeft > maxPaddingLeft ||
44714                     paddingRight > maxPaddingLeft ||
44715                     paddingTop > maxPaddingTop ||
44716                     paddingBottom > maxPaddingTop ||
44717                     // for zoom in
44718                     width > maxWidth ||
44719                     height > maxHeight
44720                 )
44721         ){
44722             return false;
44723         }
44724         
44725         if(
44726                 !this.isDocument &&
44727                 (this.rotate == 90 || this.rotate == 270) && 
44728                 (
44729                     width < this.minHeight || 
44730                     width > this.imageEl.OriginWidth || 
44731                     height < this.minWidth || 
44732                     height > this.imageEl.OriginHeight
44733                 )
44734         ){
44735             return false;
44736         }
44737         
44738         return true;
44739         
44740     },
44741     
44742     onRotateLeft : function(e)
44743     {   
44744         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
44745             
44746             var minScale = this.thumbEl.getWidth() / this.minWidth;
44747             
44748             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
44749             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
44750             
44751             this.startScale = this.scale;
44752             
44753             while (this.getScaleLevel() < minScale){
44754             
44755                 this.scale = this.scale + 1;
44756                 
44757                 if(!this.zoomable()){
44758                     break;
44759                 }
44760                 
44761                 if(
44762                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
44763                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
44764                 ){
44765                     continue;
44766                 }
44767                 
44768                 this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
44769
44770                 this.draw();
44771                 
44772                 return;
44773             }
44774             
44775             this.scale = this.startScale;
44776             
44777             this.onRotateFail();
44778             
44779             return false;
44780         }
44781         
44782         this.rotate = (this.rotate < 90) ? 270 : this.rotate - 90;
44783
44784         if(this.isDocument){
44785             this.setThumbBoxSize();
44786             this.setThumbBoxPosition();
44787             this.setCanvasPosition();
44788         }
44789         
44790         this.draw();
44791         
44792         this.fireEvent('rotate', this, 'left');
44793         
44794     },
44795     
44796     onRotateRight : function(e)
44797     {
44798         if(!this.isDocument && (this.canvasEl.height < this.thumbEl.getWidth() || this.canvasEl.width < this.thumbEl.getHeight())){
44799             
44800             var minScale = this.thumbEl.getWidth() / this.minWidth;
44801         
44802             var bw = Math.ceil(this.canvasEl.width / this.getScaleLevel());
44803             var bh = Math.ceil(this.canvasEl.height / this.getScaleLevel());
44804             
44805             this.startScale = this.scale;
44806             
44807             while (this.getScaleLevel() < minScale){
44808             
44809                 this.scale = this.scale + 1;
44810                 
44811                 if(!this.zoomable()){
44812                     break;
44813                 }
44814                 
44815                 if(
44816                         Math.ceil(bw * this.getScaleLevel()) < this.thumbEl.getHeight() ||
44817                         Math.ceil(bh * this.getScaleLevel()) < this.thumbEl.getWidth()
44818                 ){
44819                     continue;
44820                 }
44821                 
44822                 this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
44823
44824                 this.draw();
44825                 
44826                 return;
44827             }
44828             
44829             this.scale = this.startScale;
44830             
44831             this.onRotateFail();
44832             
44833             return false;
44834         }
44835         
44836         this.rotate = (this.rotate > 180) ? 0 : this.rotate + 90;
44837
44838         if(this.isDocument){
44839             this.setThumbBoxSize();
44840             this.setThumbBoxPosition();
44841             this.setCanvasPosition();
44842         }
44843         
44844         this.draw();
44845         
44846         this.fireEvent('rotate', this, 'right');
44847     },
44848     
44849     onRotateFail : function()
44850     {
44851         this.errorEl.show(true);
44852         
44853         var _this = this;
44854         
44855         (function() { _this.errorEl.hide(true); }).defer(this.errorTimeout);
44856     },
44857     
44858     draw : function()
44859     {
44860         this.previewEl.dom.innerHTML = '';
44861         
44862         var canvasEl = document.createElement("canvas");
44863         
44864         var contextEl = canvasEl.getContext("2d");
44865         
44866         canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
44867         canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
44868         var center = this.imageEl.OriginWidth / 2;
44869         
44870         if(this.imageEl.OriginWidth < this.imageEl.OriginHeight){
44871             canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
44872             canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
44873             center = this.imageEl.OriginHeight / 2;
44874         }
44875         
44876         contextEl.scale(this.getScaleLevel(), this.getScaleLevel());
44877         
44878         contextEl.translate(center, center);
44879         contextEl.rotate(this.rotate * Math.PI / 180);
44880
44881         contextEl.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
44882         
44883         this.canvasEl = document.createElement("canvas");
44884         
44885         this.contextEl = this.canvasEl.getContext("2d");
44886         
44887         switch (this.rotate) {
44888             case 0 :
44889                 
44890                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
44891                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
44892                 
44893                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
44894                 
44895                 break;
44896             case 90 : 
44897                 
44898                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
44899                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
44900                 
44901                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
44902                     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);
44903                     break;
44904                 }
44905                 
44906                 this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
44907                 
44908                 break;
44909             case 180 :
44910                 
44911                 this.canvasEl.width = this.imageEl.OriginWidth * this.getScaleLevel();
44912                 this.canvasEl.height = this.imageEl.OriginHeight * this.getScaleLevel();
44913                 
44914                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
44915                     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);
44916                     break;
44917                 }
44918                 
44919                 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);
44920                 
44921                 break;
44922             case 270 :
44923                 
44924                 this.canvasEl.width = this.imageEl.OriginHeight * this.getScaleLevel();
44925                 this.canvasEl.height = this.imageEl.OriginWidth * this.getScaleLevel();
44926         
44927                 if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
44928                     this.contextEl.drawImage(canvasEl, 0, 0, this.canvasEl.width, this.canvasEl.height, 0, 0, this.canvasEl.width, this.canvasEl.height);
44929                     break;
44930                 }
44931                 
44932                 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);
44933                 
44934                 break;
44935             default : 
44936                 break;
44937         }
44938         
44939         this.previewEl.appendChild(this.canvasEl);
44940         
44941         this.setCanvasPosition(false);
44942     },
44943     
44944     crop : function()
44945     {
44946         if(!this.canvasLoaded){
44947             return;
44948         }
44949         
44950         var imageCanvas = document.createElement("canvas");
44951         
44952         var imageContext = imageCanvas.getContext("2d");
44953         
44954         imageCanvas.width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
44955         imageCanvas.height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? this.imageEl.OriginWidth : this.imageEl.OriginHeight;
44956         
44957         var center = imageCanvas.width / 2;
44958         
44959         imageContext.translate(center, center);
44960         
44961         imageContext.rotate(this.rotate * Math.PI / 180);
44962         
44963         imageContext.drawImage(this.imageEl, 0, 0, this.imageEl.OriginWidth, this.imageEl.OriginHeight, center * -1, center * -1, this.imageEl.OriginWidth, this.imageEl.OriginHeight);
44964         
44965         var canvas = document.createElement("canvas");
44966         
44967         var context = canvas.getContext("2d");
44968
44969         canvas.width = this.thumbEl.getWidth() / this.getScaleLevel();
44970         
44971         canvas.height = this.thumbEl.getHeight() / this.getScaleLevel();
44972
44973         switch (this.rotate) {
44974             case 0 :
44975                 
44976                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
44977                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
44978                 
44979                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
44980                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
44981                 
44982                 var sx = this.thumbEl.getLeft(true) - this.previewEl.getLeft(true);
44983                 var sy = this.thumbEl.getTop(true) - this.previewEl.getTop(true);
44984
44985                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
44986                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
44987
44988                 if(canvas.width > this.outputMaxWidth) {
44989                     var scale = this.outputMaxWidth / canvas.width;
44990                     canvas.width = canvas.width * scale;
44991                     canvas.height = canvas.height * scale;
44992                     context.scale(scale, scale);
44993                 }
44994
44995                 context.fillStyle = 'white';
44996                 context.fillRect(0, 0, this.thumbEl.getWidth() / this.getScaleLevel(), this.thumbEl.getHeight() / this.getScaleLevel());
44997
44998
44999                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
45000                 
45001                 break;
45002             case 90 : 
45003                 
45004                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
45005                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
45006                 
45007                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
45008                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
45009                 
45010                 var targetWidth = this.minWidth - 2 * x;
45011                 var targetHeight = this.minHeight - 2 * y;
45012                 
45013                 var scale = 1;
45014                 
45015                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
45016                     scale = targetWidth / width;
45017                 }
45018                 
45019                 if(x > 0 && y == 0){
45020                     scale = targetHeight / height;
45021                 }
45022                 
45023                 if(x > 0 && y > 0){
45024                     scale = targetWidth / width;
45025                     
45026                     if(width < height){
45027                         scale = targetHeight / height;
45028                     }
45029                 }
45030                 
45031                 context.scale(scale, scale);
45032                 
45033                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
45034                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
45035
45036                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
45037                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
45038                 
45039                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
45040                 
45041                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
45042                 
45043                 break;
45044             case 180 :
45045                 
45046                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getWidth() / this.getScaleLevel());
45047                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getHeight() / this.getScaleLevel());
45048                 
45049                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
45050                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
45051                 
45052                 var targetWidth = this.minWidth - 2 * x;
45053                 var targetHeight = this.minHeight - 2 * y;
45054                 
45055                 var scale = 1;
45056                 
45057                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
45058                     scale = targetWidth / width;
45059                 }
45060                 
45061                 if(x > 0 && y == 0){
45062                     scale = targetHeight / height;
45063                 }
45064                 
45065                 if(x > 0 && y > 0){
45066                     scale = targetWidth / width;
45067                     
45068                     if(width < height){
45069                         scale = targetHeight / height;
45070                     }
45071                 }
45072                 
45073                 context.scale(scale, scale);
45074                 
45075                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
45076                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
45077
45078                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
45079                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
45080
45081                 sx += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
45082                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight) : 0;
45083                 
45084                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
45085                 
45086                 break;
45087             case 270 :
45088                 
45089                 var width = (this.thumbEl.getWidth() / this.getScaleLevel() > this.imageEl.OriginHeight) ? this.imageEl.OriginHeight : (this.thumbEl.getWidth() / this.getScaleLevel());
45090                 var height = (this.thumbEl.getHeight() / this.getScaleLevel() > this.imageEl.OriginWidth) ? this.imageEl.OriginWidth : (this.thumbEl.getHeight() / this.getScaleLevel());
45091                 
45092                 var x = (this.thumbEl.getLeft(true) > this.previewEl.getLeft(true)) ? 0 : ((this.previewEl.getLeft(true) - this.thumbEl.getLeft(true)) / this.getScaleLevel());
45093                 var y = (this.thumbEl.getTop(true) > this.previewEl.getTop(true)) ? 0 : ((this.previewEl.getTop(true) - this.thumbEl.getTop(true)) / this.getScaleLevel());
45094                 
45095                 var targetWidth = this.minWidth - 2 * x;
45096                 var targetHeight = this.minHeight - 2 * y;
45097                 
45098                 var scale = 1;
45099                 
45100                 if((x == 0 && y == 0) || (x == 0 && y > 0)){
45101                     scale = targetWidth / width;
45102                 }
45103                 
45104                 if(x > 0 && y == 0){
45105                     scale = targetHeight / height;
45106                 }
45107                 
45108                 if(x > 0 && y > 0){
45109                     scale = targetWidth / width;
45110                     
45111                     if(width < height){
45112                         scale = targetHeight / height;
45113                     }
45114                 }
45115                 
45116                 context.scale(scale, scale);
45117                 var sx = Math.min(this.canvasEl.width - this.thumbEl.getWidth(), this.thumbEl.getLeft(true) - this.previewEl.getLeft(true));
45118                 var sy = Math.min(this.canvasEl.height - this.thumbEl.getHeight(), this.thumbEl.getTop(true) - this.previewEl.getTop(true));
45119
45120                 sx = sx < 0 ? 0 : (sx / this.getScaleLevel());
45121                 sy = sy < 0 ? 0 : (sy / this.getScaleLevel());
45122                 
45123                 sy += (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? 0 : Math.abs(this.imageEl.OriginWidth - this.imageEl.OriginHeight);
45124                 
45125                 context.drawImage(imageCanvas, sx, sy, width, height, x, y, width, height);
45126                 
45127                 break;
45128             default : 
45129                 break;
45130         }
45131         
45132         this.cropData = canvas.toDataURL(this.cropType);
45133         
45134         if(this.fireEvent('crop', this, this.cropData) !== false){
45135             this.process(this.file, this.cropData);
45136         }
45137         
45138         return;
45139         
45140     },
45141     
45142     setThumbBoxSize : function()
45143     {
45144         var width, height;
45145         
45146         if(this.isDocument && typeof(this.imageEl) != 'undefined'){
45147             width = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.max(this.minWidth, this.minHeight) : Math.min(this.minWidth, this.minHeight);
45148             height = (this.imageEl.OriginWidth > this.imageEl.OriginHeight) ? Math.min(this.minWidth, this.minHeight) : Math.max(this.minWidth, this.minHeight);
45149             
45150             this.minWidth = width;
45151             this.minHeight = height;
45152             
45153             if(this.rotate == 90 || this.rotate == 270){
45154                 this.minWidth = height;
45155                 this.minHeight = width;
45156             }
45157         }
45158         
45159         height = this.windowSize;
45160         width = Math.ceil(this.minWidth * height / this.minHeight);
45161         
45162         if(this.minWidth > this.minHeight){
45163             width = this.windowSize;
45164             height = Math.ceil(this.minHeight * width / this.minWidth);
45165         }
45166         
45167         this.thumbEl.setStyle({
45168             width : width + 'px',
45169             height : height + 'px'
45170         });
45171
45172         return;
45173             
45174     },
45175     
45176     setThumbBoxPosition : function()
45177     {
45178         var x = Math.ceil((this.bodyEl.getWidth() - this.thumbEl.getWidth()) / 2 );
45179         var y = Math.ceil((this.bodyEl.getHeight() - this.thumbEl.getHeight()) / 2);
45180         
45181         this.thumbEl.setLeft(x);
45182         this.thumbEl.setTop(y);
45183         
45184     },
45185     
45186     baseRotateLevel : function()
45187     {
45188         this.baseRotate = 1;
45189         
45190         if(
45191                 typeof(this.exif) != 'undefined' &&
45192                 typeof(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != 'undefined' &&
45193                 [1, 3, 6, 8].indexOf(this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']]) != -1
45194         ){
45195             this.baseRotate = this.exif[Roo.dialog.UploadCropbox['tags']['Orientation']];
45196         }
45197         
45198         this.rotate = Roo.dialog.UploadCropbox['Orientation'][this.baseRotate];
45199         
45200     },
45201     
45202     baseScaleLevel : function()
45203     {
45204         var width, height;
45205         
45206         if(this.isDocument){
45207             
45208             if(this.baseRotate == 6 || this.baseRotate == 8){
45209             
45210                 height = this.thumbEl.getHeight();
45211                 this.baseScale = height / this.imageEl.OriginWidth;
45212
45213                 if(this.imageEl.OriginHeight * this.baseScale > this.thumbEl.getWidth()){
45214                     width = this.thumbEl.getWidth();
45215                     this.baseScale = width / this.imageEl.OriginHeight;
45216                 }
45217
45218                 return;
45219             }
45220
45221             height = this.thumbEl.getHeight();
45222             this.baseScale = height / this.imageEl.OriginHeight;
45223
45224             if(this.imageEl.OriginWidth * this.baseScale > this.thumbEl.getWidth()){
45225                 width = this.thumbEl.getWidth();
45226                 this.baseScale = width / this.imageEl.OriginWidth;
45227             }
45228
45229             return;
45230         }
45231         
45232         if(this.baseRotate == 6 || this.baseRotate == 8){
45233             
45234             width = this.thumbEl.getHeight();
45235             this.baseScale = width / this.imageEl.OriginHeight;
45236             
45237             if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getWidth()){
45238                 height = this.thumbEl.getWidth();
45239                 this.baseScale = height / this.imageEl.OriginHeight;
45240             }
45241             
45242             if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
45243                 height = this.thumbEl.getWidth();
45244                 this.baseScale = height / this.imageEl.OriginHeight;
45245                 
45246                 if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getHeight()){
45247                     width = this.thumbEl.getHeight();
45248                     this.baseScale = width / this.imageEl.OriginWidth;
45249                 }
45250             }
45251             
45252             return;
45253         }
45254         
45255         width = this.thumbEl.getWidth();
45256         this.baseScale = width / this.imageEl.OriginWidth;
45257         
45258         if(this.imageEl.OriginHeight * this.baseScale < this.thumbEl.getHeight()){
45259             height = this.thumbEl.getHeight();
45260             this.baseScale = height / this.imageEl.OriginHeight;
45261         }
45262         
45263         if(this.imageEl.OriginWidth > this.imageEl.OriginHeight){
45264             
45265             height = this.thumbEl.getHeight();
45266             this.baseScale = height / this.imageEl.OriginHeight;
45267             
45268             if(this.imageEl.OriginWidth * this.baseScale < this.thumbEl.getWidth()){
45269                 width = this.thumbEl.getWidth();
45270                 this.baseScale = width / this.imageEl.OriginWidth;
45271             }
45272             
45273         }
45274
45275         if(this.imageEl.OriginWidth < this.minWidth || this.imageEl.OriginHeight < this.minHeight) {
45276             this.baseScale = width / this.minWidth;
45277         }
45278
45279         return;
45280     },
45281     
45282     getScaleLevel : function()
45283     {
45284         return this.baseScale * Math.pow(1.02, this.scale);
45285     },
45286     
45287     onTouchStart : function(e)
45288     {
45289         if(!this.canvasLoaded){
45290             this.beforeSelectFile(e);
45291             return;
45292         }
45293         
45294         var touches = e.browserEvent.touches;
45295         
45296         if(!touches){
45297             return;
45298         }
45299         
45300         if(touches.length == 1){
45301             this.onMouseDown(e);
45302             return;
45303         }
45304         
45305         if(touches.length != 2){
45306             return;
45307         }
45308         
45309         var coords = [];
45310         
45311         for(var i = 0, finger; finger = touches[i]; i++){
45312             coords.push(finger.pageX, finger.pageY);
45313         }
45314         
45315         var x = Math.pow(coords[0] - coords[2], 2);
45316         var y = Math.pow(coords[1] - coords[3], 2);
45317         
45318         this.startDistance = Math.sqrt(x + y);
45319         
45320         this.startScale = this.scale;
45321         
45322         this.pinching = true;
45323         this.dragable = false;
45324         
45325     },
45326     
45327     onTouchMove : function(e)
45328     {
45329         if(!this.pinching && !this.dragable){
45330             return;
45331         }
45332         
45333         var touches = e.browserEvent.touches;
45334         
45335         if(!touches){
45336             return;
45337         }
45338         
45339         if(this.dragable){
45340             this.onMouseMove(e);
45341             return;
45342         }
45343         
45344         var coords = [];
45345         
45346         for(var i = 0, finger; finger = touches[i]; i++){
45347             coords.push(finger.pageX, finger.pageY);
45348         }
45349         
45350         var x = Math.pow(coords[0] - coords[2], 2);
45351         var y = Math.pow(coords[1] - coords[3], 2);
45352         
45353         this.endDistance = Math.sqrt(x + y);
45354         
45355         this.scale = this.startScale + Math.floor(Math.log(this.endDistance / this.startDistance) / Math.log(1.1));
45356         
45357         if(!this.zoomable()){
45358             this.scale = this.startScale;
45359             return;
45360         }
45361         
45362         this.draw();
45363         
45364     },
45365     
45366     onTouchEnd : function(e)
45367     {
45368         this.pinching = false;
45369         this.dragable = false;
45370         
45371     },
45372     
45373     process : function(file, crop)
45374     {
45375         if(this.loadMask){
45376             this.maskEl.mask(this.loadingText);
45377         }
45378         
45379         this.xhr = new XMLHttpRequest();
45380         
45381         file.xhr = this.xhr;
45382
45383         this.xhr.open(this.method, this.url, true);
45384         
45385         var headers = {
45386             "Accept": "application/json",
45387             "Cache-Control": "no-cache",
45388             "X-Requested-With": "XMLHttpRequest"
45389         };
45390         
45391         for (var headerName in headers) {
45392             var headerValue = headers[headerName];
45393             if (headerValue) {
45394                 this.xhr.setRequestHeader(headerName, headerValue);
45395             }
45396         }
45397         
45398         var _this = this;
45399         
45400         this.xhr.onload = function()
45401         {
45402             _this.xhrOnLoad(_this.xhr);
45403         }
45404         
45405         this.xhr.onerror = function()
45406         {
45407             _this.xhrOnError(_this.xhr);
45408         }
45409         
45410         var formData = new FormData();
45411
45412         formData.append('returnHTML', 'NO');
45413
45414         if(crop){
45415             formData.append('crop', crop);
45416             var blobBin = atob(crop.split(',')[1]);
45417             var array = [];
45418             for(var i = 0; i < blobBin.length; i++) {
45419                 array.push(blobBin.charCodeAt(i));
45420             }
45421             var croppedFile =new Blob([new Uint8Array(array)], {type: this.cropType});
45422             formData.append(this.paramName, croppedFile, file.name);
45423         }
45424         
45425         if(typeof(file.filename) != 'undefined'){
45426             formData.append('filename', file.filename);
45427         }
45428         
45429         if(typeof(file.mimetype) != 'undefined'){
45430             formData.append('mimetype', file.mimetype);
45431         }
45432
45433         if(this.fireEvent('arrange', this, formData) != false){
45434             this.xhr.send(formData);
45435         };
45436     },
45437     
45438     xhrOnLoad : function(xhr)
45439     {
45440         if(this.loadMask){
45441             this.maskEl.unmask();
45442         }
45443         
45444         if (xhr.readyState !== 4) {
45445             this.fireEvent('exception', this, xhr);
45446             return;
45447         }
45448
45449         var response = Roo.decode(xhr.responseText);
45450         
45451         if(!response.success){
45452             this.fireEvent('exception', this, xhr);
45453             return;
45454         }
45455         
45456         var response = Roo.decode(xhr.responseText);
45457         
45458         this.fireEvent('upload', this, response);
45459         
45460     },
45461     
45462     xhrOnError : function()
45463     {
45464         if(this.loadMask){
45465             this.maskEl.unmask();
45466         }
45467         
45468         Roo.log('xhr on error');
45469         
45470         var response = Roo.decode(xhr.responseText);
45471           
45472         Roo.log(response);
45473         
45474     },
45475     
45476     prepare : function(file)
45477     {   
45478         if(this.loadMask){
45479             this.maskEl.mask(this.loadingText);
45480         }
45481         
45482         this.file = false;
45483         this.exif = {};
45484         
45485         if(typeof(file) === 'string'){
45486             this.loadCanvas(file);
45487             return;
45488         }
45489         
45490         if(!file || !this.urlAPI){
45491             return;
45492         }
45493         
45494         this.file = file;
45495         if(typeof(file.type) != 'undefined' && file.type.length != 0) {
45496             this.cropType = file.type;
45497         }
45498         
45499         var _this = this;
45500         
45501         if(this.fireEvent('prepare', this, this.file) != false){
45502             
45503             var reader = new FileReader();
45504             
45505             reader.onload = function (e) {
45506                 if (e.target.error) {
45507                     Roo.log(e.target.error);
45508                     return;
45509                 }
45510                 
45511                 var buffer = e.target.result,
45512                     dataView = new DataView(buffer),
45513                     offset = 2,
45514                     maxOffset = dataView.byteLength - 4,
45515                     markerBytes,
45516                     markerLength;
45517                 
45518                 if (dataView.getUint16(0) === 0xffd8) {
45519                     while (offset < maxOffset) {
45520                         markerBytes = dataView.getUint16(offset);
45521                         
45522                         if ((markerBytes >= 0xffe0 && markerBytes <= 0xffef) || markerBytes === 0xfffe) {
45523                             markerLength = dataView.getUint16(offset + 2) + 2;
45524                             if (offset + markerLength > dataView.byteLength) {
45525                                 Roo.log('Invalid meta data: Invalid segment size.');
45526                                 break;
45527                             }
45528                             
45529                             if(markerBytes == 0xffe1){
45530                                 _this.parseExifData(
45531                                     dataView,
45532                                     offset,
45533                                     markerLength
45534                                 );
45535                             }
45536                             
45537                             offset += markerLength;
45538                             
45539                             continue;
45540                         }
45541                         
45542                         break;
45543                     }
45544                     
45545                 }
45546                 
45547                 var url = _this.urlAPI.createObjectURL(_this.file);
45548                 
45549                 _this.loadCanvas(url);
45550                 
45551                 return;
45552             }
45553             
45554             reader.readAsArrayBuffer(this.file);
45555             
45556         }
45557         
45558     },
45559     
45560     parseExifData : function(dataView, offset, length)
45561     {
45562         var tiffOffset = offset + 10,
45563             littleEndian,
45564             dirOffset;
45565     
45566         if (dataView.getUint32(offset + 4) !== 0x45786966) {
45567             // No Exif data, might be XMP data instead
45568             return;
45569         }
45570         
45571         // Check for the ASCII code for "Exif" (0x45786966):
45572         if (dataView.getUint32(offset + 4) !== 0x45786966) {
45573             // No Exif data, might be XMP data instead
45574             return;
45575         }
45576         if (tiffOffset + 8 > dataView.byteLength) {
45577             Roo.log('Invalid Exif data: Invalid segment size.');
45578             return;
45579         }
45580         // Check for the two null bytes:
45581         if (dataView.getUint16(offset + 8) !== 0x0000) {
45582             Roo.log('Invalid Exif data: Missing byte alignment offset.');
45583             return;
45584         }
45585         // Check the byte alignment:
45586         switch (dataView.getUint16(tiffOffset)) {
45587         case 0x4949:
45588             littleEndian = true;
45589             break;
45590         case 0x4D4D:
45591             littleEndian = false;
45592             break;
45593         default:
45594             Roo.log('Invalid Exif data: Invalid byte alignment marker.');
45595             return;
45596         }
45597         // Check for the TIFF tag marker (0x002A):
45598         if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) {
45599             Roo.log('Invalid Exif data: Missing TIFF marker.');
45600             return;
45601         }
45602         // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
45603         dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
45604         
45605         this.parseExifTags(
45606             dataView,
45607             tiffOffset,
45608             tiffOffset + dirOffset,
45609             littleEndian
45610         );
45611     },
45612     
45613     parseExifTags : function(dataView, tiffOffset, dirOffset, littleEndian)
45614     {
45615         var tagsNumber,
45616             dirEndOffset,
45617             i;
45618         if (dirOffset + 6 > dataView.byteLength) {
45619             Roo.log('Invalid Exif data: Invalid directory offset.');
45620             return;
45621         }
45622         tagsNumber = dataView.getUint16(dirOffset, littleEndian);
45623         dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
45624         if (dirEndOffset + 4 > dataView.byteLength) {
45625             Roo.log('Invalid Exif data: Invalid directory size.');
45626             return;
45627         }
45628         for (i = 0; i < tagsNumber; i += 1) {
45629             this.parseExifTag(
45630                 dataView,
45631                 tiffOffset,
45632                 dirOffset + 2 + 12 * i, // tag offset
45633                 littleEndian
45634             );
45635         }
45636         // Return the offset to the next directory:
45637         return dataView.getUint32(dirEndOffset, littleEndian);
45638     },
45639     
45640     parseExifTag : function (dataView, tiffOffset, offset, littleEndian) 
45641     {
45642         var tag = dataView.getUint16(offset, littleEndian);
45643         
45644         this.exif[tag] = this.getExifValue(
45645             dataView,
45646             tiffOffset,
45647             offset,
45648             dataView.getUint16(offset + 2, littleEndian), // tag type
45649             dataView.getUint32(offset + 4, littleEndian), // tag length
45650             littleEndian
45651         );
45652     },
45653     
45654     getExifValue : function (dataView, tiffOffset, offset, type, length, littleEndian)
45655     {
45656         var tagType = Roo.dialog.UploadCropbox.exifTagTypes[type],
45657             tagSize,
45658             dataOffset,
45659             values,
45660             i,
45661             str,
45662             c;
45663     
45664         if (!tagType) {
45665             Roo.log('Invalid Exif data: Invalid tag type.');
45666             return;
45667         }
45668         
45669         tagSize = tagType.size * length;
45670         // Determine if the value is contained in the dataOffset bytes,
45671         // or if the value at the dataOffset is a pointer to the actual data:
45672         dataOffset = tagSize > 4 ?
45673                 tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8);
45674         if (dataOffset + tagSize > dataView.byteLength) {
45675             Roo.log('Invalid Exif data: Invalid data offset.');
45676             return;
45677         }
45678         if (length === 1) {
45679             return tagType.getValue(dataView, dataOffset, littleEndian);
45680         }
45681         values = [];
45682         for (i = 0; i < length; i += 1) {
45683             values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian);
45684         }
45685         
45686         if (tagType.ascii) {
45687             str = '';
45688             // Concatenate the chars:
45689             for (i = 0; i < values.length; i += 1) {
45690                 c = values[i];
45691                 // Ignore the terminating NULL byte(s):
45692                 if (c === '\u0000') {
45693                     break;
45694                 }
45695                 str += c;
45696             }
45697             return str;
45698         }
45699         return values;
45700     }
45701     
45702 });
45703
45704 Roo.apply(Roo.dialog.UploadCropbox, {
45705     tags : {
45706         'Orientation': 0x0112
45707     },
45708     
45709     Orientation: {
45710             1: 0, //'top-left',
45711 //            2: 'top-right',
45712             3: 180, //'bottom-right',
45713 //            4: 'bottom-left',
45714 //            5: 'left-top',
45715             6: 90, //'right-top',
45716 //            7: 'right-bottom',
45717             8: 270 //'left-bottom'
45718     },
45719     
45720     exifTagTypes : {
45721         // byte, 8-bit unsigned int:
45722         1: {
45723             getValue: function (dataView, dataOffset) {
45724                 return dataView.getUint8(dataOffset);
45725             },
45726             size: 1
45727         },
45728         // ascii, 8-bit byte:
45729         2: {
45730             getValue: function (dataView, dataOffset) {
45731                 return String.fromCharCode(dataView.getUint8(dataOffset));
45732             },
45733             size: 1,
45734             ascii: true
45735         },
45736         // short, 16 bit int:
45737         3: {
45738             getValue: function (dataView, dataOffset, littleEndian) {
45739                 return dataView.getUint16(dataOffset, littleEndian);
45740             },
45741             size: 2
45742         },
45743         // long, 32 bit int:
45744         4: {
45745             getValue: function (dataView, dataOffset, littleEndian) {
45746                 return dataView.getUint32(dataOffset, littleEndian);
45747             },
45748             size: 4
45749         },
45750         // rational = two long values, first is numerator, second is denominator:
45751         5: {
45752             getValue: function (dataView, dataOffset, littleEndian) {
45753                 return dataView.getUint32(dataOffset, littleEndian) /
45754                     dataView.getUint32(dataOffset + 4, littleEndian);
45755             },
45756             size: 8
45757         },
45758         // slong, 32 bit signed int:
45759         9: {
45760             getValue: function (dataView, dataOffset, littleEndian) {
45761                 return dataView.getInt32(dataOffset, littleEndian);
45762             },
45763             size: 4
45764         },
45765         // srational, two slongs, first is numerator, second is denominator:
45766         10: {
45767             getValue: function (dataView, dataOffset, littleEndian) {
45768                 return dataView.getInt32(dataOffset, littleEndian) /
45769                     dataView.getInt32(dataOffset + 4, littleEndian);
45770             },
45771             size: 8
45772         }
45773     },
45774     
45775     footer : {
45776         STANDARD : [
45777             {
45778                 tag : 'div',
45779                 cls : 'btn-group roo-upload-cropbox-rotate-left',
45780                 action : 'rotate-left',
45781                 cn : [
45782                     {
45783                         tag : 'button',
45784                         cls : 'btn btn-default',
45785                         html : '<i class="fa fa-undo"></i>'
45786                     }
45787                 ]
45788             },
45789             {
45790                 tag : 'div',
45791                 cls : 'btn-group roo-upload-cropbox-picture',
45792                 action : 'picture',
45793                 cn : [
45794                     {
45795                         tag : 'button',
45796                         cls : 'btn btn-default',
45797                         html : '<i class="fa fa-picture-o"></i>'
45798                     }
45799                 ]
45800             },
45801             {
45802                 tag : 'div',
45803                 cls : 'btn-group roo-upload-cropbox-rotate-right',
45804                 action : 'rotate-right',
45805                 cn : [
45806                     {
45807                         tag : 'button',
45808                         cls : 'btn btn-default',
45809                         html : '<i class="fa fa-repeat"></i>'
45810                     }
45811                 ]
45812             }
45813         ],
45814         DOCUMENT : [
45815             {
45816                 tag : 'div',
45817                 cls : 'btn-group roo-upload-cropbox-rotate-left',
45818                 action : 'rotate-left',
45819                 cn : [
45820                     {
45821                         tag : 'button',
45822                         cls : 'btn btn-default',
45823                         html : '<i class="fa fa-undo"></i>'
45824                     }
45825                 ]
45826             },
45827             {
45828                 tag : 'div',
45829                 cls : 'btn-group roo-upload-cropbox-download',
45830                 action : 'download',
45831                 cn : [
45832                     {
45833                         tag : 'button',
45834                         cls : 'btn btn-default',
45835                         html : '<i class="fa fa-download"></i>'
45836                     }
45837                 ]
45838             },
45839             {
45840                 tag : 'div',
45841                 cls : 'btn-group roo-upload-cropbox-crop',
45842                 action : 'crop',
45843                 cn : [
45844                     {
45845                         tag : 'button',
45846                         cls : 'btn btn-default',
45847                         html : '<i class="fa fa-crop"></i>'
45848                     }
45849                 ]
45850             },
45851             {
45852                 tag : 'div',
45853                 cls : 'btn-group roo-upload-cropbox-trash',
45854                 action : 'trash',
45855                 cn : [
45856                     {
45857                         tag : 'button',
45858                         cls : 'btn btn-default',
45859                         html : '<i class="fa fa-trash"></i>'
45860                     }
45861                 ]
45862             },
45863             {
45864                 tag : 'div',
45865                 cls : 'btn-group roo-upload-cropbox-rotate-right',
45866                 action : 'rotate-right',
45867                 cn : [
45868                     {
45869                         tag : 'button',
45870                         cls : 'btn btn-default',
45871                         html : '<i class="fa fa-repeat"></i>'
45872                     }
45873                 ]
45874             }
45875         ],
45876         ROTATOR : [
45877             {
45878                 tag : 'div',
45879                 cls : 'btn-group roo-upload-cropbox-rotate-left',
45880                 action : 'rotate-left',
45881                 cn : [
45882                     {
45883                         tag : 'button',
45884                         cls : 'btn btn-default',
45885                         html : '<i class="fa fa-undo"></i>'
45886                     }
45887                 ]
45888             },
45889             {
45890                 tag : 'div',
45891                 cls : 'btn-group roo-upload-cropbox-rotate-right',
45892                 action : 'rotate-right',
45893                 cn : [
45894                     {
45895                         tag : 'button',
45896                         cls : 'btn btn-default',
45897                         html : '<i class="fa fa-repeat"></i>'
45898                     }
45899                 ]
45900             }
45901         ],
45902         CENTER : [
45903             {
45904                 tag : 'div',
45905                 cls : 'btn-group roo-upload-cropbox-center',
45906                 action : 'center',
45907                 cn : [
45908                     {
45909                         tag : 'button',
45910                         cls : 'btn btn-default',
45911                         html : 'CENTER'
45912                     }
45913                 ]
45914             }
45915         ]
45916     }
45917 });