Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / builds / ext-all-sandbox-debug.js
1 /*
2 Ext JS - JavaScript Library
3 Copyright (c) 2006-2011, Sencha Inc.
4 All rights reserved.
5 licensing@sencha.com
6 */
7 (function(Ext){
8 if (typeof Ext === 'undefined') {
9 this.Ext = {};
10 }
11
12 Ext.buildSettings = {"baseCSSPrefix":"x4-","scopeResetCSS":true};
13 /*
14 Ext JS - JavaScript Library
15 Copyright (c) 2006-2011, Sencha Inc.
16 All rights reserved.
17 licensing@sencha.com
18 */
19 /**
20  * @class Ext
21  * @singleton
22  */
23 (function() {
24     var global = this,
25         objectPrototype = Object.prototype,
26         toString = Object.prototype.toString,
27         enumerables = true,
28         enumerablesTest = { toString: 1 },
29         i;
30
31     if (typeof Ext === 'undefined') {
32         global.Ext = {};
33     }
34
35     Ext.global = global;
36
37     for (i in enumerablesTest) {
38         enumerables = null;
39     }
40
41     if (enumerables) {
42         enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable',
43                        'toLocaleString', 'toString', 'constructor'];
44     }
45
46     /**
47      * An array containing extra enumerables for old browsers
48      * @type Array
49      */
50     Ext.enumerables = enumerables;
51
52     /**
53      * Copies all the properties of config to the specified object.
54      * Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use
55      * {@link Ext.Object#merge} instead.
56      * @param {Object} object The receiver of the properties
57      * @param {Object} config The source of the properties
58      * @param {Object} defaults A different object that will also be applied for default values
59      * @return {Object} returns obj
60      */
61     Ext.apply = function(object, config, defaults) {
62         if (defaults) {
63             Ext.apply(object, defaults);
64         }
65
66         if (object && config && typeof config === 'object') {
67             var i, j, k;
68
69             for (i in config) {
70                 object[i] = config[i];
71             }
72
73             if (enumerables) {
74                 for (j = enumerables.length; j--;) {
75                     k = enumerables[j];
76                     if (config.hasOwnProperty(k)) {
77                         object[k] = config[k];
78                     }
79                 }
80             }
81         }
82
83         return object;
84     };
85
86     Ext.buildSettings = Ext.apply({
87         baseCSSPrefix: 'x-',
88         scopeResetCSS: false
89     }, Ext.buildSettings || {});
90
91     Ext.apply(Ext, {
92         /**
93          * A reusable empty function
94          */
95         emptyFn: function() {},
96
97         baseCSSPrefix: Ext.buildSettings.baseCSSPrefix,
98
99         /**
100          * Copies all the properties of config to object if they don't already exist.
101          * @function
102          * @param {Object} object The receiver of the properties
103          * @param {Object} config The source of the properties
104          * @return {Object} returns obj
105          */
106         applyIf: function(object, config) {
107             var property;
108
109             if (object) {
110                 for (property in config) {
111                     if (object[property] === undefined) {
112                         object[property] = config[property];
113                     }
114                 }
115             }
116
117             return object;
118         },
119
120         /**
121          * Iterates either an array or an object. This method delegates to
122          * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise.
123          *
124          * @param {Object/Array} object The object or array to be iterated.
125          * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and
126          * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object
127          * type that is being iterated.
128          * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
129          * Defaults to the object being iterated itself.
130          * @markdown
131          */
132         iterate: function(object, fn, scope) {
133             if (Ext.isEmpty(object)) {
134                 return;
135             }
136
137             if (scope === undefined) {
138                 scope = object;
139             }
140
141             if (Ext.isIterable(object)) {
142                 Ext.Array.each.call(Ext.Array, object, fn, scope);
143             }
144             else {
145                 Ext.Object.each.call(Ext.Object, object, fn, scope);
146             }
147         }
148     });
149
150     Ext.apply(Ext, {
151
152         /**
153          * This method deprecated. Use {@link Ext#define Ext.define} instead.
154          * @function
155          * @param {Function} superclass
156          * @param {Object} overrides
157          * @return {Function} The subclass constructor from the <tt>overrides</tt> parameter, or a generated one if not provided.
158          * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead
159          */
160         extend: function() {
161             // inline overrides
162             var objectConstructor = objectPrototype.constructor,
163                 inlineOverrides = function(o) {
164                 for (var m in o) {
165                     if (!o.hasOwnProperty(m)) {
166                         continue;
167                     }
168                     this[m] = o[m];
169                 }
170             };
171
172             return function(subclass, superclass, overrides) {
173                 // First we check if the user passed in just the superClass with overrides
174                 if (Ext.isObject(superclass)) {
175                     overrides = superclass;
176                     superclass = subclass;
177                     subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() {
178                         superclass.apply(this, arguments);
179                     };
180                 }
181
182                 if (!superclass) {
183                     Ext.Error.raise({
184                         sourceClass: 'Ext',
185                         sourceMethod: 'extend',
186                         msg: 'Attempting to extend from a class which has not been loaded on the page.'
187                     });
188                 }
189
190                 // We create a new temporary class
191                 var F = function() {},
192                     subclassProto, superclassProto = superclass.prototype;
193
194                 F.prototype = superclassProto;
195                 subclassProto = subclass.prototype = new F();
196                 subclassProto.constructor = subclass;
197                 subclass.superclass = superclassProto;
198
199                 if (superclassProto.constructor === objectConstructor) {
200                     superclassProto.constructor = superclass;
201                 }
202
203                 subclass.override = function(overrides) {
204                     Ext.override(subclass, overrides);
205                 };
206
207                 subclassProto.override = inlineOverrides;
208                 subclassProto.proto = subclassProto;
209
210                 subclass.override(overrides);
211                 subclass.extend = function(o) {
212                     return Ext.extend(subclass, o);
213                 };
214
215                 return subclass;
216             };
217         }(),
218
219         /**
220          * Proxy to {@link Ext.Base#override}. Please refer {@link Ext.Base#override} for further details.
221
222     Ext.define('My.cool.Class', {
223         sayHi: function() {
224             alert('Hi!');
225         }
226     }
227
228     Ext.override(My.cool.Class, {
229         sayHi: function() {
230             alert('About to say...');
231
232             this.callOverridden();
233         }
234     });
235
236     var cool = new My.cool.Class();
237     cool.sayHi(); // alerts 'About to say...'
238                   // alerts 'Hi!'
239
240          * Please note that `this.callOverridden()` only works if the class was previously
241          * created with {@link Ext#define)
242          *
243          * @param {Object} cls The class to override
244          * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
245          * containing one or more methods.
246          * @method override
247          * @markdown
248          */
249         override: function(cls, overrides) {
250             if (cls.prototype.$className) {
251                 return cls.override(overrides);
252             }
253             else {
254                 Ext.apply(cls.prototype, overrides);
255             }
256         }
257     });
258
259     // A full set of static methods to do type checking
260     Ext.apply(Ext, {
261
262         /**
263          * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
264          * value (second argument) otherwise.
265          *
266          * @param {Mixed} value The value to test
267          * @param {Mixed} defaultValue The value to return if the original value is empty
268          * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
269          * @return {Mixed} value, if non-empty, else defaultValue
270          */
271         valueFrom: function(value, defaultValue, allowBlank){
272             return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
273         },
274
275         /**
276          * Returns the type of the given variable in string format. List of possible values are:
277          *
278          * - `undefined`: If the given value is `undefined`
279          * - `null`: If the given value is `null`
280          * - `string`: If the given value is a string
281          * - `number`: If the given value is a number
282          * - `boolean`: If the given value is a boolean value
283          * - `date`: If the given value is a `Date` object
284          * - `function`: If the given value is a function reference
285          * - `object`: If the given value is an object
286          * - `array`: If the given value is an array
287          * - `regexp`: If the given value is a regular expression
288          * - `element`: If the given value is a DOM Element
289          * - `textnode`: If the given value is a DOM text node and contains something other than whitespace
290          * - `whitespace`: If the given value is a DOM text node and contains only whitespace
291          *
292          * @param {Mixed} value
293          * @return {String}
294          * @markdown
295          */
296         typeOf: function(value) {
297             if (value === null) {
298                 return 'null';
299             }
300
301             var type = typeof value;
302
303             if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
304                 return type;
305             }
306
307             var typeToString = toString.call(value);
308
309             switch(typeToString) {
310                 case '[object Array]':
311                     return 'array';
312                 case '[object Date]':
313                     return 'date';
314                 case '[object Boolean]':
315                     return 'boolean';
316                 case '[object Number]':
317                     return 'number';
318                 case '[object RegExp]':
319                     return 'regexp';
320             }
321
322             if (type === 'function') {
323                 return 'function';
324             }
325
326             if (type === 'object') {
327                 if (value.nodeType !== undefined) {
328                     if (value.nodeType === 3) {
329                         return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
330                     }
331                     else {
332                         return 'element';
333                     }
334                 }
335
336                 return 'object';
337             }
338
339             Ext.Error.raise({
340                 sourceClass: 'Ext',
341                 sourceMethod: 'typeOf',
342                 msg: 'Failed to determine the type of the specified value "' + value + '". This is most likely a bug.'
343             });
344         },
345
346         /**
347          * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
348          *
349          * - `null`
350          * - `undefined`
351          * - a zero-length array
352          * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
353          *
354          * @param {Mixed} value The value to test
355          * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
356          * @return {Boolean}
357          * @markdown
358          */
359         isEmpty: function(value, allowEmptyString) {
360             return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
361         },
362
363         /**
364          * Returns true if the passed value is a JavaScript Array, false otherwise.
365          *
366          * @param {Mixed} target The target to test
367          * @return {Boolean}
368          */
369         isArray: ('isArray' in Array) ? Array.isArray : function(value) {
370             return toString.call(value) === '[object Array]';
371         },
372
373         /**
374          * Returns true if the passed value is a JavaScript Date object, false otherwise.
375          * @param {Object} object The object to test
376          * @return {Boolean}
377          */
378         isDate: function(value) {
379             return toString.call(value) === '[object Date]';
380         },
381
382         /**
383          * Returns true if the passed value is a JavaScript Object, false otherwise.
384          * @param {Mixed} value The value to test
385          * @return {Boolean}
386          */
387         isObject: (toString.call(null) === '[object Object]') ?
388         function(value) {
389             return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.nodeType === undefined;
390         } :
391         function(value) {
392             return toString.call(value) === '[object Object]';
393         },
394
395         /**
396          * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
397          * @param {Mixed} value The value to test
398          * @return {Boolean}
399          */
400         isPrimitive: function(value) {
401             var type = typeof value;
402
403             return type === 'string' || type === 'number' || type === 'boolean';
404         },
405
406         /**
407          * Returns true if the passed value is a JavaScript Function, false otherwise.
408          * @param {Mixed} value The value to test
409          * @return {Boolean}
410          */
411         isFunction:
412         // Safari 3.x and 4.x returns 'function' for typeof <NodeList>, hence we need to fall back to using
413         // Object.prorotype.toString (slower)
414         (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
415             return toString.call(value) === '[object Function]';
416         } : function(value) {
417             return typeof value === 'function';
418         },
419
420         /**
421          * Returns true if the passed value is a number. Returns false for non-finite numbers.
422          * @param {Mixed} value The value to test
423          * @return {Boolean}
424          */
425         isNumber: function(value) {
426             return typeof value === 'number' && isFinite(value);
427         },
428
429         /**
430          * Validates that a value is numeric.
431          * @param {Mixed} value Examples: 1, '1', '2.34'
432          * @return {Boolean} True if numeric, false otherwise
433          */
434         isNumeric: function(value) {
435             return !isNaN(parseFloat(value)) && isFinite(value);
436         },
437
438         /**
439          * Returns true if the passed value is a string.
440          * @param {Mixed} value The value to test
441          * @return {Boolean}
442          */
443         isString: function(value) {
444             return typeof value === 'string';
445         },
446
447         /**
448          * Returns true if the passed value is a boolean.
449          *
450          * @param {Mixed} value The value to test
451          * @return {Boolean}
452          */
453         isBoolean: function(value) {
454             return typeof value === 'boolean';
455         },
456
457         /**
458          * Returns true if the passed value is an HTMLElement
459          * @param {Mixed} value The value to test
460          * @return {Boolean}
461          */
462         isElement: function(value) {
463             return value ? value.nodeType !== undefined : false;
464         },
465
466         /**
467          * Returns true if the passed value is a TextNode
468          * @param {Mixed} value The value to test
469          * @return {Boolean}
470          */
471         isTextNode: function(value) {
472             return value ? value.nodeName === "#text" : false;
473         },
474
475         /**
476          * Returns true if the passed value is defined.
477          * @param {Mixed} value The value to test
478          * @return {Boolean}
479          */
480         isDefined: function(value) {
481             return typeof value !== 'undefined';
482         },
483
484         /**
485          * Returns true if the passed value is iterable, false otherwise
486          * @param {Mixed} value The value to test
487          * @return {Boolean}
488          */
489         isIterable: function(value) {
490             return (value && typeof value !== 'string') ? value.length !== undefined : false;
491         }
492     });
493
494     Ext.apply(Ext, {
495
496         /**
497          * Clone almost any type of variable including array, object, DOM nodes and Date without keeping the old reference
498          * @param {Mixed} item The variable to clone
499          * @return {Mixed} clone
500          */
501         clone: function(item) {
502             if (item === null || item === undefined) {
503                 return item;
504             }
505
506             // DOM nodes
507             // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
508             // recursively
509             if (item.nodeType && item.cloneNode) {
510                 return item.cloneNode(true);
511             }
512
513             var type = toString.call(item);
514
515             // Date
516             if (type === '[object Date]') {
517                 return new Date(item.getTime());
518             }
519
520             var i, j, k, clone, key;
521
522             // Array
523             if (type === '[object Array]') {
524                 i = item.length;
525
526                 clone = [];
527
528                 while (i--) {
529                     clone[i] = Ext.clone(item[i]);
530                 }
531             }
532             // Object
533             else if (type === '[object Object]' && item.constructor === Object) {
534                 clone = {};
535
536                 for (key in item) {
537                     clone[key] = Ext.clone(item[key]);
538                 }
539
540                 if (enumerables) {
541                     for (j = enumerables.length; j--;) {
542                         k = enumerables[j];
543                         clone[k] = item[k];
544                     }
545                 }
546             }
547
548             return clone || item;
549         },
550
551         /**
552          * @private
553          * Generate a unique reference of Ext in the global scope, useful for sandboxing
554          */
555         getUniqueGlobalNamespace: function() {
556             var uniqueGlobalNamespace = this.uniqueGlobalNamespace;
557
558             if (uniqueGlobalNamespace === undefined) {
559                 var i = 0;
560
561                 do {
562                     uniqueGlobalNamespace = 'ExtSandbox' + (++i);
563                 } while (Ext.global[uniqueGlobalNamespace] !== undefined);
564
565                 Ext.global[uniqueGlobalNamespace] = Ext;
566                 this.uniqueGlobalNamespace = uniqueGlobalNamespace;
567             }
568
569             return uniqueGlobalNamespace;
570         },
571
572         /**
573          * @private
574          */
575         functionFactory: function() {
576             var args = Array.prototype.slice.call(arguments);
577
578             if (args.length > 0) {
579                 args[args.length - 1] = 'var Ext=window.' + this.getUniqueGlobalNamespace() + ';' +
580                     args[args.length - 1];
581             }
582
583             return Function.prototype.constructor.apply(Function.prototype, args);
584         }
585     });
586
587     /**
588      * Old alias to {@link Ext#typeOf}
589      * @deprecated 4.0.0 Use {@link Ext#typeOf} instead
590      */
591     Ext.type = Ext.typeOf;
592
593 })();
594
595 /**
596  * @author Jacky Nguyen <jacky@sencha.com>
597  * @docauthor Jacky Nguyen <jacky@sencha.com>
598  * @class Ext.Version
599  *
600  * A utility class that wrap around a string version number and provide convenient
601  * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
602
603     var version = new Ext.Version('1.0.2beta');
604     console.log("Version is " + version); // Version is 1.0.2beta
605
606     console.log(version.getMajor()); // 1
607     console.log(version.getMinor()); // 0
608     console.log(version.getPatch()); // 2
609     console.log(version.getBuild()); // 0
610     console.log(version.getRelease()); // beta
611
612     console.log(version.isGreaterThan('1.0.1')); // True
613     console.log(version.isGreaterThan('1.0.2alpha')); // True
614     console.log(version.isGreaterThan('1.0.2RC')); // False
615     console.log(version.isGreaterThan('1.0.2')); // False
616     console.log(version.isLessThan('1.0.2')); // True
617
618     console.log(version.match(1.0)); // True
619     console.log(version.match('1.0.2')); // True
620
621  * @markdown
622  */
623 (function() {
624
625 // Current core version
626 var version = '4.0.0', Version;
627     Ext.Version = Version = Ext.extend(Object, {
628
629         /**
630          * @constructor
631          * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]
632          * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC
633          * @return {Ext.Version} this
634          * @param version
635          */
636         constructor: function(version) {
637             var parts, releaseStartIndex;
638
639             if (version instanceof Version) {
640                 return version;
641             }
642
643             this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
644
645             releaseStartIndex = this.version.search(/([^\d\.])/);
646
647             if (releaseStartIndex !== -1) {
648                 this.release = this.version.substr(releaseStartIndex, version.length);
649                 this.shortVersion = this.version.substr(0, releaseStartIndex);
650             }
651
652             this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
653
654             parts = this.version.split('.');
655
656             this.major = parseInt(parts.shift() || 0, 10);
657             this.minor = parseInt(parts.shift() || 0, 10);
658             this.patch = parseInt(parts.shift() || 0, 10);
659             this.build = parseInt(parts.shift() || 0, 10);
660
661             return this;
662         },
663
664         /**
665          * Override the native toString method
666          * @private
667          * @return {String} version
668          */
669         toString: function() {
670             return this.version;
671         },
672
673         /**
674          * Override the native valueOf method
675          * @private
676          * @return {String} version
677          */
678         valueOf: function() {
679             return this.version;
680         },
681
682         /**
683          * Returns the major component value
684          * @return {Number} major
685          */
686         getMajor: function() {
687             return this.major || 0;
688         },
689
690         /**
691          * Returns the minor component value
692          * @return {Number} minor
693          */
694         getMinor: function() {
695             return this.minor || 0;
696         },
697
698         /**
699          * Returns the patch component value
700          * @return {Number} patch
701          */
702         getPatch: function() {
703             return this.patch || 0;
704         },
705
706         /**
707          * Returns the build component value
708          * @return {Number} build
709          */
710         getBuild: function() {
711             return this.build || 0;
712         },
713
714         /**
715          * Returns the release component value
716          * @return {Number} release
717          */
718         getRelease: function() {
719             return this.release || '';
720         },
721
722         /**
723          * Returns whether this version if greater than the supplied argument
724          * @param {String/Number} target The version to compare with
725          * @return {Boolean} True if this version if greater than the target, false otherwise
726          */
727         isGreaterThan: function(target) {
728             return Version.compare(this.version, target) === 1;
729         },
730
731         /**
732          * Returns whether this version if smaller than the supplied argument
733          * @param {String/Number} target The version to compare with
734          * @return {Boolean} True if this version if smaller than the target, false otherwise
735          */
736         isLessThan: function(target) {
737             return Version.compare(this.version, target) === -1;
738         },
739
740         /**
741          * Returns whether this version equals to the supplied argument
742          * @param {String/Number} target The version to compare with
743          * @return {Boolean} True if this version equals to the target, false otherwise
744          */
745         equals: function(target) {
746             return Version.compare(this.version, target) === 0;
747         },
748
749         /**
750          * Returns whether this version matches the supplied argument. Example:
751          * <pre><code>
752          * var version = new Ext.Version('1.0.2beta');
753          * console.log(version.match(1)); // True
754          * console.log(version.match(1.0)); // True
755          * console.log(version.match('1.0.2')); // True
756          * console.log(version.match('1.0.2RC')); // False
757          * </code></pre>
758          * @param {String/Number} target The version to compare with
759          * @return {Boolean} True if this version matches the target, false otherwise
760          */
761         match: function(target) {
762             target = String(target);
763             return this.version.substr(0, target.length) === target;
764         },
765
766         /**
767          * Returns this format: [major, minor, patch, build, release]. Useful for comparison
768          * @return {Array}
769          */
770         toArray: function() {
771             return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
772         },
773
774         /**
775          * Returns shortVersion version without dots and release
776          * @return {String}
777          */
778         getShortVersion: function() {
779             return this.shortVersion;
780         }
781     });
782
783     Ext.apply(Version, {
784         // @private
785         releaseValueMap: {
786             'dev': -6,
787             'alpha': -5,
788             'a': -5,
789             'beta': -4,
790             'b': -4,
791             'rc': -3,
792             '#': -2,
793             'p': -1,
794             'pl': -1
795         },
796
797         /**
798          * Converts a version component to a comparable value
799          *
800          * @static
801          * @param {Mixed} value The value to convert
802          * @return {Mixed}
803          */
804         getComponentValue: function(value) {
805             return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
806         },
807
808         /**
809          * Compare 2 specified versions, starting from left to right. If a part contains special version strings,
810          * they are handled in the following order:
811          * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
812          *
813          * @static
814          * @param {String} current The current version to compare to
815          * @param {String} target The target version to compare to
816          * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
817          */
818         compare: function(current, target) {
819             var currentValue, targetValue, i;
820
821             current = new Version(current).toArray();
822             target = new Version(target).toArray();
823
824             for (i = 0; i < Math.max(current.length, target.length); i++) {
825                 currentValue = this.getComponentValue(current[i]);
826                 targetValue = this.getComponentValue(target[i]);
827
828                 if (currentValue < targetValue) {
829                     return -1;
830                 } else if (currentValue > targetValue) {
831                     return 1;
832                 }
833             }
834
835             return 0;
836         }
837     });
838
839     Ext.apply(Ext, {
840         /**
841          * @private
842          */
843         versions: {},
844
845         /**
846          * @private
847          */
848         lastRegisteredVersion: null,
849
850         /**
851          * Set version number for the given package name.
852          *
853          * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
854          * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
855          * @return {Ext}
856          */
857         setVersion: function(packageName, version) {
858             Ext.versions[packageName] = new Version(version);
859             Ext.lastRegisteredVersion = Ext.versions[packageName];
860
861             return this;
862         },
863
864         /**
865          * Get the version number of the supplied package name; will return the last registered version
866          * (last Ext.setVersion call) if there's no package name given.
867          *
868          * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
869          * @return {Ext.Version} The version
870          */
871         getVersion: function(packageName) {
872             if (packageName === undefined) {
873                 return Ext.lastRegisteredVersion;
874             }
875
876             return Ext.versions[packageName];
877         },
878
879         /**
880          * Create a closure for deprecated code.
881          *
882     // This means Ext.oldMethod is only supported in 4.0.0beta and older.
883     // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
884     // the closure will not be invoked
885     Ext.deprecate('extjs', '4.0.0beta', function() {
886         Ext.oldMethod = Ext.newMethod;
887
888         ...
889     });
890
891          * @param {String} packageName The package name
892          * @param {String} since The last version before it's deprecated
893          * @param {Function} closure The callback function to be executed with the specified version is less than the current version
894          * @param {Object} scope The execution scope (<tt>this</tt>) if the closure
895          * @markdown
896          */
897         deprecate: function(packageName, since, closure, scope) {
898             if (Version.compare(Ext.getVersion(packageName), since) < 1) {
899                 closure.call(scope);
900             }
901         }
902     }); // End Versioning
903
904     Ext.setVersion('core', version);
905
906 })();
907
908 /**
909  * @class Ext.String
910  *
911  * A collection of useful static methods to deal with strings
912  * @singleton
913  */
914
915 Ext.String = {
916     trimRegex: /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,
917     escapeRe: /('|\\)/g,
918     formatRe: /\{(\d+)\}/g,
919     escapeRegexRe: /([-.*+?^${}()|[\]\/\\])/g,
920
921     /**
922      * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
923      * @param {String} value The string to encode
924      * @return {String} The encoded text
925      */
926     htmlEncode: (function() {
927         var entities = {
928             '&': '&amp;',
929             '>': '&gt;',
930             '<': '&lt;',
931             '"': '&quot;'
932         }, keys = [], p, regex;
933         
934         for (p in entities) {
935             keys.push(p);
936         }
937         
938         regex = new RegExp('(' + keys.join('|') + ')', 'g');
939         
940         return function(value) {
941             return (!value) ? value : String(value).replace(regex, function(match, capture) {
942                 return entities[capture];    
943             });
944         };
945     })(),
946
947     /**
948      * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
949      * @param {String} value The string to decode
950      * @return {String} The decoded text
951      */
952     htmlDecode: (function() {
953         var entities = {
954             '&amp;': '&',
955             '&gt;': '>',
956             '&lt;': '<',
957             '&quot;': '"'
958         }, keys = [], p, regex;
959         
960         for (p in entities) {
961             keys.push(p);
962         }
963         
964         regex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
965         
966         return function(value) {
967             return (!value) ? value : String(value).replace(regex, function(match, capture) {
968                 if (capture in entities) {
969                     return entities[capture];
970                 } else {
971                     return String.fromCharCode(parseInt(capture.substr(2), 10));
972                 }
973             });
974         };
975     })(),
976
977     /**
978      * Appends content to the query string of a URL, handling logic for whether to place
979      * a question mark or ampersand.
980      * @param {String} url The URL to append to.
981      * @param {String} string The content to append to the URL.
982      * @return (String) The resulting URL
983      */
984     urlAppend : function(url, string) {
985         if (!Ext.isEmpty(string)) {
986             return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
987         }
988
989         return url;
990     },
991
992     /**
993      * Trims whitespace from either end of a string, leaving spaces within the string intact.  Example:
994      * @example
995 var s = '  foo bar  ';
996 alert('-' + s + '-');         //alerts "- foo bar -"
997 alert('-' + Ext.String.trim(s) + '-');  //alerts "-foo bar-"
998
999      * @param {String} string The string to escape
1000      * @return {String} The trimmed string
1001      */
1002     trim: function(string) {
1003         return string.replace(Ext.String.trimRegex, "");
1004     },
1005
1006     /**
1007      * Capitalize the given string
1008      * @param {String} string
1009      * @return {String}
1010      */
1011     capitalize: function(string) {
1012         return string.charAt(0).toUpperCase() + string.substr(1);
1013     },
1014
1015     /**
1016      * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
1017      * @param {String} value The string to truncate
1018      * @param {Number} length The maximum length to allow before truncating
1019      * @param {Boolean} word True to try to find a common word break
1020      * @return {String} The converted text
1021      */
1022     ellipsis: function(value, len, word) {
1023         if (value && value.length > len) {
1024             if (word) {
1025                 var vs = value.substr(0, len - 2),
1026                 index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
1027                 if (index !== -1 && index >= (len - 15)) {
1028                     return vs.substr(0, index) + "...";
1029                 }
1030             }
1031             return value.substr(0, len - 3) + "...";
1032         }
1033         return value;
1034     },
1035
1036     /**
1037      * Escapes the passed string for use in a regular expression
1038      * @param {String} string
1039      * @return {String}
1040      */
1041     escapeRegex: function(string) {
1042         return string.replace(Ext.String.escapeRegexRe, "\\$1");
1043     },
1044
1045     /**
1046      * Escapes the passed string for ' and \
1047      * @param {String} string The string to escape
1048      * @return {String} The escaped string
1049      */
1050     escape: function(string) {
1051         return string.replace(Ext.String.escapeRe, "\\$1");
1052     },
1053
1054     /**
1055      * Utility function that allows you to easily switch a string between two alternating values.  The passed value
1056      * is compared to the current string, and if they are equal, the other value that was passed in is returned.  If
1057      * they are already different, the first value passed in is returned.  Note that this method returns the new value
1058      * but does not change the current string.
1059      * <pre><code>
1060     // alternate sort directions
1061     sort = Ext.String.toggle(sort, 'ASC', 'DESC');
1062
1063     // instead of conditional logic:
1064     sort = (sort == 'ASC' ? 'DESC' : 'ASC');
1065        </code></pre>
1066      * @param {String} string The current string
1067      * @param {String} value The value to compare to the current string
1068      * @param {String} other The new value to use if the string already equals the first value passed in
1069      * @return {String} The new value
1070      */
1071     toggle: function(string, value, other) {
1072         return string === value ? other : value;
1073     },
1074
1075     /**
1076      * Pads the left side of a string with a specified character.  This is especially useful
1077      * for normalizing number and date strings.  Example usage:
1078      *
1079      * <pre><code>
1080 var s = Ext.String.leftPad('123', 5, '0');
1081 // s now contains the string: '00123'
1082        </code></pre>
1083      * @param {String} string The original string
1084      * @param {Number} size The total length of the output string
1085      * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
1086      * @return {String} The padded string
1087      */
1088     leftPad: function(string, size, character) {
1089         var result = String(string);
1090         character = character || " ";
1091         while (result.length < size) {
1092             result = character + result;
1093         }
1094         return result;
1095     },
1096
1097     /**
1098      * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens.  Each
1099      * token must be unique, and must increment in the format {0}, {1}, etc.  Example usage:
1100      * <pre><code>
1101 var cls = 'my-class', text = 'Some text';
1102 var s = Ext.String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
1103 // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
1104        </code></pre>
1105      * @param {String} string The tokenized string to be formatted
1106      * @param {String} value1 The value to replace token {0}
1107      * @param {String} value2 Etc...
1108      * @return {String} The formatted string
1109      */
1110     format: function(format) {
1111         var args = Ext.Array.toArray(arguments, 1);
1112         return format.replace(Ext.String.formatRe, function(m, i) {
1113             return args[i];
1114         });
1115     }
1116 };
1117
1118 /**
1119  * @class Ext.Number
1120  *
1121  * A collection of useful static methods to deal with numbers
1122  * @singleton
1123  */
1124
1125 (function() {
1126
1127 var isToFixedBroken = (0.9).toFixed() !== '1';
1128
1129 Ext.Number = {
1130     /**
1131      * Checks whether or not the current number is within a desired range.  If the number is already within the
1132      * range it is returned, otherwise the min or max value is returned depending on which side of the range is
1133      * exceeded. Note that this method returns the constrained value but does not change the current number.
1134      * @param {Number} number The number to check
1135      * @param {Number} min The minimum number in the range
1136      * @param {Number} max The maximum number in the range
1137      * @return {Number} The constrained value if outside the range, otherwise the current value
1138      */
1139     constrain: function(number, min, max) {
1140         number = parseFloat(number);
1141
1142         if (!isNaN(min)) {
1143             number = Math.max(number, min);
1144         }
1145         if (!isNaN(max)) {
1146             number = Math.min(number, max);
1147         }
1148         return number;
1149     },
1150
1151     /**
1152      * Formats a number using fixed-point notation
1153      * @param {Number} value The number to format
1154      * @param {Number} precision The number of digits to show after the decimal point
1155      */
1156     toFixed: function(value, precision) {
1157         if (isToFixedBroken) {
1158             precision = precision || 0;
1159             var pow = Math.pow(10, precision);
1160             return (Math.round(value * pow) / pow).toFixed(precision);
1161         }
1162
1163         return value.toFixed(precision);
1164     },
1165
1166     /**
1167      * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
1168      * it is not.
1169
1170 Ext.Number.from('1.23', 1); // returns 1.23
1171 Ext.Number.from('abc', 1); // returns 1
1172
1173      * @param {Mixed} value
1174      * @param {Number} defaultValue The value to return if the original value is non-numeric
1175      * @return {Number} value, if numeric, defaultValue otherwise
1176      */
1177     from: function(value, defaultValue) {
1178         if (isFinite(value)) {
1179             value = parseFloat(value);
1180         }
1181
1182         return !isNaN(value) ? value : defaultValue;
1183     }
1184 };
1185
1186 })();
1187
1188 /**
1189  * This method is deprecated, please use {@link Ext.Number#from Ext.Number.from} instead
1190  *
1191  * @deprecated 4.0.0 Replaced by Ext.Number.from
1192  * @member Ext
1193  * @method num
1194  */
1195 Ext.num = function() {
1196     return Ext.Number.from.apply(this, arguments);
1197 };
1198 /**
1199  * @author Jacky Nguyen <jacky@sencha.com>
1200  * @docauthor Jacky Nguyen <jacky@sencha.com>
1201  * @class Ext.Array
1202  *
1203  * A set of useful static methods to deal with arrays; provide missing methods for older browsers.
1204
1205  * @singleton
1206  * @markdown
1207  */
1208 (function() {
1209
1210     var arrayPrototype = Array.prototype,
1211         slice = arrayPrototype.slice,
1212         supportsForEach = 'forEach' in arrayPrototype,
1213         supportsMap = 'map' in arrayPrototype,
1214         supportsIndexOf = 'indexOf' in arrayPrototype,
1215         supportsEvery = 'every' in arrayPrototype,
1216         supportsSome = 'some' in arrayPrototype,
1217         supportsFilter = 'filter' in arrayPrototype,
1218         supportsSort = function() {
1219             var a = [1,2,3,4,5].sort(function(){ return 0; });
1220             return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
1221         }(),
1222         supportsSliceOnNodeList = true,
1223         ExtArray;
1224     try {
1225         // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
1226         if (typeof document !== 'undefined') {
1227             slice.call(document.getElementsByTagName('body'));
1228         }
1229     } catch (e) {
1230         supportsSliceOnNodeList = false;
1231     }
1232
1233     ExtArray = Ext.Array = {
1234         /*
1235          * Iterates an array or an iterable value and invoke the given callback function for each item.
1236
1237     var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
1238
1239     Ext.Array.each(countries, function(name, index, countriesItSelf) {
1240         console.log(name);
1241     });
1242
1243     var sum = function() {
1244         var sum = 0;
1245
1246         Ext.Array.each(arguments, function(value) {
1247             sum += value;
1248         });
1249
1250         return sum;
1251     };
1252
1253     sum(1, 2, 3); // returns 6
1254
1255          * The iteration can be stopped by returning false in the function callback.
1256
1257     Ext.Array.each(countries, function(name, index, countriesItSelf) {
1258         if (name === 'Singapore') {
1259             return false; // break here
1260         }
1261     });
1262
1263          * @param {Array/NodeList/Mixed} iterable The value to be iterated. If this
1264          * argument is not iterable, the callback function is called once.
1265          * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
1266          * the current `index`. Arguments passed to this callback function are:
1267
1268 - `item`: {Mixed} The item at the current `index` in the passed `array`
1269 - `index`: {Number} The current `index` within the `array`
1270 - `allItems`: {Array/NodeList/Mixed} The `array` passed as the first argument to `Ext.Array.each`
1271
1272          * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
1273          * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
1274          * Defaults false
1275          * @return {Boolean} See description for the `fn` parameter.
1276          * @markdown
1277          */
1278         each: function(array, fn, scope, reverse) {
1279             array = ExtArray.from(array);
1280
1281             var i,
1282                 ln = array.length;
1283
1284             if (reverse !== true) {
1285                 for (i = 0; i < ln; i++) {
1286                     if (fn.call(scope || array[i], array[i], i, array) === false) {
1287                         return i;
1288                     }
1289                 }
1290             }
1291             else {
1292                 for (i = ln - 1; i > -1; i--) {
1293                     if (fn.call(scope || array[i], array[i], i, array) === false) {
1294                         return i;
1295                     }
1296                 }
1297             }
1298
1299             return true;
1300         },
1301
1302         /**
1303          * Iterates an array and invoke the given callback function for each item. Note that this will simply
1304          * delegate to the native Array.prototype.forEach method if supported.
1305          * It doesn't support stopping the iteration by returning false in the callback function like
1306          * {@link Ext.Array#each}. However, performance could be much better in modern browsers comparing with
1307          * {@link Ext.Array#each}
1308          *
1309          * @param {Array} array The array to iterate
1310          * @param {Function} fn The function callback, to be invoked these arguments:
1311          *
1312 - `item`: {Mixed} The item at the current `index` in the passed `array`
1313 - `index`: {Number} The current `index` within the `array`
1314 - `allItems`: {Array} The `array` itself which was passed as the first argument
1315
1316          * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
1317          * @markdown
1318          */
1319         forEach: function(array, fn, scope) {
1320             if (supportsForEach) {
1321                 return array.forEach(fn, scope);
1322             }
1323
1324             var i = 0,
1325                 ln = array.length;
1326
1327             for (; i < ln; i++) {
1328                 fn.call(scope, array[i], i, array);
1329             }
1330         },
1331
1332         /**
1333          * Get the index of the provided `item` in the given `array`, a supplement for the
1334          * missing arrayPrototype.indexOf in Internet Explorer.
1335          *
1336          * @param {Array} array The array to check
1337          * @param {Mixed} item The item to look for
1338          * @param {Number} from (Optional) The index at which to begin the search
1339          * @return {Number} The index of item in the array (or -1 if it is not found)
1340          * @markdown
1341          */
1342         indexOf: function(array, item, from) {
1343             if (supportsIndexOf) {
1344                 return array.indexOf(item, from);
1345             }
1346
1347             var i, length = array.length;
1348
1349             for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
1350                 if (array[i] === item) {
1351                     return i;
1352                 }
1353             }
1354
1355             return -1;
1356         },
1357
1358         /**
1359          * Checks whether or not the given `array` contains the specified `item`
1360          *
1361          * @param {Array} array The array to check
1362          * @param {Mixed} item The item to look for
1363          * @return {Boolean} True if the array contains the item, false otherwise
1364          * @markdown
1365          */
1366         contains: function(array, item) {
1367             if (supportsIndexOf) {
1368                 return array.indexOf(item) !== -1;
1369             }
1370
1371             var i, ln;
1372
1373             for (i = 0, ln = array.length; i < ln; i++) {
1374                 if (array[i] === item) {
1375                     return true;
1376                 }
1377             }
1378
1379             return false;
1380         },
1381
1382         /**
1383          * Converts any iterable (numeric indices and a length property) into a true array.
1384
1385 function test() {
1386     var args = Ext.Array.toArray(arguments),
1387         fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
1388
1389     alert(args.join(' '));
1390     alert(fromSecondToLastArgs.join(' '));
1391 }
1392
1393 test('just', 'testing', 'here'); // alerts 'just testing here';
1394                                  // alerts 'testing here';
1395
1396 Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
1397 Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
1398 Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l', 'i']
1399
1400          * @param {Mixed} iterable the iterable object to be turned into a true Array.
1401          * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
1402          * @param {Number} end (Optional) a zero-based index that specifies the end of extraction. Defaults to the last
1403          * index of the iterable value
1404          * @return {Array} array
1405          * @markdown
1406          */
1407         toArray: function(iterable, start, end){
1408             if (!iterable || !iterable.length) {
1409                 return [];
1410             }
1411
1412             if (typeof iterable === 'string') {
1413                 iterable = iterable.split('');
1414             }
1415
1416             if (supportsSliceOnNodeList) {
1417                 return slice.call(iterable, start || 0, end || iterable.length);
1418             }
1419
1420             var array = [],
1421                 i;
1422
1423             start = start || 0;
1424             end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
1425
1426             for (i = start; i < end; i++) {
1427                 array.push(iterable[i]);
1428             }
1429
1430             return array;
1431         },
1432
1433         /**
1434          * Plucks the value of a property from each item in the Array. Example:
1435          *
1436     Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
1437
1438          * @param {Array|NodeList} array The Array of items to pluck the value from.
1439          * @param {String} propertyName The property name to pluck from each element.
1440          * @return {Array} The value from each item in the Array.
1441          */
1442         pluck: function(array, propertyName) {
1443             var ret = [],
1444                 i, ln, item;
1445
1446             for (i = 0, ln = array.length; i < ln; i++) {
1447                 item = array[i];
1448
1449                 ret.push(item[propertyName]);
1450             }
1451
1452             return ret;
1453         },
1454
1455         /**
1456          * Creates a new array with the results of calling a provided function on every element in this array.
1457          * @param {Array} array
1458          * @param {Function} fn Callback function for each item
1459          * @param {Object} scope Callback function scope
1460          * @return {Array} results
1461          */
1462         map: function(array, fn, scope) {
1463             if (supportsMap) {
1464                 return array.map(fn, scope);
1465             }
1466
1467             var results = [],
1468                 i = 0,
1469                 len = array.length;
1470
1471             for (; i < len; i++) {
1472                 results[i] = fn.call(scope, array[i], i, array);
1473             }
1474
1475             return results;
1476         },
1477
1478         /**
1479          * Executes the specified function for each array element until the function returns a falsy value.
1480          * If such an item is found, the function will return false immediately.
1481          * Otherwise, it will return true.
1482          *
1483          * @param {Array} array
1484          * @param {Function} fn Callback function for each item
1485          * @param {Object} scope Callback function scope
1486          * @return {Boolean} True if no false value is returned by the callback function.
1487          */
1488         every: function(array, fn, scope) {
1489             if (!fn) {
1490                 Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.');
1491             }
1492             if (supportsEvery) {
1493                 return array.every(fn, scope);
1494             }
1495
1496             var i = 0,
1497                 ln = array.length;
1498
1499             for (; i < ln; ++i) {
1500                 if (!fn.call(scope, array[i], i, array)) {
1501                     return false;
1502                 }
1503             }
1504
1505             return true;
1506         },
1507
1508         /**
1509          * Executes the specified function for each array element until the function returns a truthy value.
1510          * If such an item is found, the function will return true immediately. Otherwise, it will return false.
1511          *
1512          * @param {Array} array
1513          * @param {Function} fn Callback function for each item
1514          * @param {Object} scope Callback function scope
1515          * @return {Boolean} True if the callback function returns a truthy value.
1516          */
1517         some: function(array, fn, scope) {
1518             if (!fn) {
1519                 Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.');
1520             }
1521             if (supportsSome) {
1522                 return array.some(fn, scope);
1523             }
1524
1525             var i = 0,
1526                 ln = array.length;
1527
1528             for (; i < ln; ++i) {
1529                 if (fn.call(scope, array[i], i, array)) {
1530                     return true;
1531                 }
1532             }
1533
1534             return false;
1535         },
1536
1537         /**
1538          * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
1539          *
1540          * @see Ext.Array.filter
1541          * @param {Array} array
1542          * @return {Array} results
1543          */
1544         clean: function(array) {
1545             var results = [],
1546                 i = 0,
1547                 ln = array.length,
1548                 item;
1549
1550             for (; i < ln; i++) {
1551                 item = array[i];
1552
1553                 if (!Ext.isEmpty(item)) {
1554                     results.push(item);
1555                 }
1556             }
1557
1558             return results;
1559         },
1560
1561         /**
1562          * Returns a new array with unique items
1563          *
1564          * @param {Array} array
1565          * @return {Array} results
1566          */
1567         unique: function(array) {
1568             var clone = [],
1569                 i = 0,
1570                 ln = array.length,
1571                 item;
1572
1573             for (; i < ln; i++) {
1574                 item = array[i];
1575
1576                 if (ExtArray.indexOf(clone, item) === -1) {
1577                     clone.push(item);
1578                 }
1579             }
1580
1581             return clone;
1582         },
1583
1584         /**
1585          * Creates a new array with all of the elements of this array for which
1586          * the provided filtering function returns true.
1587          * @param {Array} array
1588          * @param {Function} fn Callback function for each item
1589          * @param {Object} scope Callback function scope
1590          * @return {Array} results
1591          */
1592         filter: function(array, fn, scope) {
1593             if (supportsFilter) {
1594                 return array.filter(fn, scope);
1595             }
1596
1597             var results = [],
1598                 i = 0,
1599                 ln = array.length;
1600
1601             for (; i < ln; i++) {
1602                 if (fn.call(scope, array[i], i, array)) {
1603                     results.push(array[i]);
1604                 }
1605             }
1606
1607             return results;
1608         },
1609
1610         /**
1611          * Converts a value to an array if it's not already an array; returns:
1612          *
1613          * - An empty array if given value is `undefined` or `null`
1614          * - Itself if given value is already an array
1615          * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
1616          * - An array with one item which is the given value, otherwise
1617          *
1618          * @param {Array/Mixed} value The value to convert to an array if it's not already is an array
1619          * @param {Boolean} (Optional) newReference True to clone the given array and return a new reference if necessary,
1620          * defaults to false
1621          * @return {Array} array
1622          * @markdown
1623          */
1624         from: function(value, newReference) {
1625             if (value === undefined || value === null) {
1626                 return [];
1627             }
1628
1629             if (Ext.isArray(value)) {
1630                 return (newReference) ? slice.call(value) : value;
1631             }
1632
1633             if (value && value.length !== undefined && typeof value !== 'string') {
1634                 return Ext.toArray(value);
1635             }
1636
1637             return [value];
1638         },
1639
1640         /**
1641          * Removes the specified item from the array if it exists
1642          *
1643          * @param {Array} array The array
1644          * @param {Mixed} item The item to remove
1645          * @return {Array} The passed array itself
1646          */
1647         remove: function(array, item) {
1648             var index = ExtArray.indexOf(array, item);
1649
1650             if (index !== -1) {
1651                 array.splice(index, 1);
1652             }
1653
1654             return array;
1655         },
1656
1657         /**
1658          * Push an item into the array only if the array doesn't contain it yet
1659          *
1660          * @param {Array} array The array
1661          * @param {Mixed} item The item to include
1662          * @return {Array} The passed array itself
1663          */
1664         include: function(array, item) {
1665             if (!ExtArray.contains(array, item)) {
1666                 array.push(item);
1667             }
1668         },
1669
1670         /**
1671          * Clone a flat array without referencing the previous one. Note that this is different
1672          * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
1673          * for Array.prototype.slice.call(array)
1674          *
1675          * @param {Array} array The array
1676          * @return {Array} The clone array
1677          */
1678         clone: function(array) {
1679             return slice.call(array);
1680         },
1681
1682         /**
1683          * Merge multiple arrays into one with unique items. Alias to {@link Ext.Array#union}.
1684          *
1685          * @param {Array} array,...
1686          * @return {Array} merged
1687          */
1688         merge: function() {
1689             var args = slice.call(arguments),
1690                 array = [],
1691                 i, ln;
1692
1693             for (i = 0, ln = args.length; i < ln; i++) {
1694                 array = array.concat(args[i]);
1695             }
1696
1697             return ExtArray.unique(array);
1698         },
1699
1700         /**
1701          * Merge multiple arrays into one with unique items that exist in all of the arrays.
1702          *
1703          * @param {Array} array,...
1704          * @return {Array} intersect
1705          */
1706         intersect: function() {
1707             var intersect = [],
1708                 arrays = slice.call(arguments),
1709                 i, j, k, minArray, array, x, y, ln, arraysLn, arrayLn;
1710
1711             if (!arrays.length) {
1712                 return intersect;
1713             }
1714
1715             // Find the smallest array
1716             for (i = x = 0,ln = arrays.length; i < ln,array = arrays[i]; i++) {
1717                 if (!minArray || array.length < minArray.length) {
1718                     minArray = array;
1719                     x = i;
1720                 }
1721             }
1722
1723             minArray = Ext.Array.unique(minArray);
1724             arrays.splice(x, 1);
1725
1726             // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
1727             // an item in the small array, we're likely to find it before reaching the end
1728             // of the inner loop and can terminate the search early.
1729             for (i = 0,ln = minArray.length; i < ln,x = minArray[i]; i++) {
1730                 var count = 0;
1731
1732                 for (j = 0,arraysLn = arrays.length; j < arraysLn,array = arrays[j]; j++) {
1733                     for (k = 0,arrayLn = array.length; k < arrayLn,y = array[k]; k++) {
1734                         if (x === y) {
1735                             count++;
1736                             break;
1737                         }
1738                     }
1739                 }
1740
1741                 if (count === arraysLn) {
1742                     intersect.push(x);
1743                 }
1744             }
1745
1746             return intersect;
1747         },
1748
1749         /**
1750          * Perform a set difference A-B by subtracting all items in array B from array A.
1751          *
1752          * @param {Array} array A
1753          * @param {Array} array B
1754          * @return {Array} difference
1755          */
1756         difference: function(arrayA, arrayB) {
1757             var clone = slice.call(arrayA),
1758                 ln = clone.length,
1759                 i, j, lnB;
1760
1761             for (i = 0,lnB = arrayB.length; i < lnB; i++) {
1762                 for (j = 0; j < ln; j++) {
1763                     if (clone[j] === arrayB[i]) {
1764                         clone.splice(j, 1);
1765                         j--;
1766                         ln--;
1767                     }
1768                 }
1769             }
1770
1771             return clone;
1772         },
1773
1774         /**
1775          * Sorts the elements of an Array.
1776          * By default, this method sorts the elements alphabetically and ascending.
1777          *
1778          * @param {Array} array The array to sort.
1779          * @param {Function} sortFn (optional) The comparison function.
1780          * @return {Array} The sorted array.
1781          */
1782         sort: function(array, sortFn) {
1783             if (supportsSort) {
1784                 if (sortFn) {
1785                     return array.sort(sortFn);
1786                 } else {
1787                     return array.sort();
1788                 }
1789             }
1790
1791             var length = array.length,
1792                 i = 0,
1793                 comparison,
1794                 j, min, tmp;
1795
1796             for (; i < length; i++) {
1797                 min = i;
1798                 for (j = i + 1; j < length; j++) {
1799                     if (sortFn) {
1800                         comparison = sortFn(array[j], array[min]);
1801                         if (comparison < 0) {
1802                             min = j;
1803                         }
1804                     } else if (array[j] < array[min]) {
1805                         min = j;
1806                     }
1807                 }
1808                 if (min !== i) {
1809                     tmp = array[i];
1810                     array[i] = array[min];
1811                     array[min] = tmp;
1812                 }
1813             }
1814
1815             return array;
1816         },
1817
1818         /**
1819          * Recursively flattens into 1-d Array. Injects Arrays inline.
1820          * @param {Array} array The array to flatten
1821          * @return {Array} The new, flattened array.
1822          */
1823         flatten: function(array) {
1824             var worker = [];
1825
1826             function rFlatten(a) {
1827                 var i, ln, v;
1828
1829                 for (i = 0, ln = a.length; i < ln; i++) {
1830                     v = a[i];
1831
1832                     if (Ext.isArray(v)) {
1833                         rFlatten(v);
1834                     } else {
1835                         worker.push(v);
1836                     }
1837                 }
1838
1839                 return worker;
1840             }
1841
1842             return rFlatten(array);
1843         },
1844
1845         /**
1846          * Returns the minimum value in the Array.
1847          * @param {Array|NodeList} array The Array from which to select the minimum value.
1848          * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
1849          *                   If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
1850          * @return {Mixed} minValue The minimum value
1851          */
1852         min: function(array, comparisonFn) {
1853             var min = array[0],
1854                 i, ln, item;
1855
1856             for (i = 0, ln = array.length; i < ln; i++) {
1857                 item = array[i];
1858
1859                 if (comparisonFn) {
1860                     if (comparisonFn(min, item) === 1) {
1861                         min = item;
1862                     }
1863                 }
1864                 else {
1865                     if (item < min) {
1866                         min = item;
1867                     }
1868                 }
1869             }
1870
1871             return min;
1872         },
1873
1874         /**
1875          * Returns the maximum value in the Array
1876          * @param {Array|NodeList} array The Array from which to select the maximum value.
1877          * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
1878          *                   If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
1879          * @return {Mixed} maxValue The maximum value
1880          */
1881         max: function(array, comparisonFn) {
1882             var max = array[0],
1883                 i, ln, item;
1884
1885             for (i = 0, ln = array.length; i < ln; i++) {
1886                 item = array[i];
1887
1888                 if (comparisonFn) {
1889                     if (comparisonFn(max, item) === -1) {
1890                         max = item;
1891                     }
1892                 }
1893                 else {
1894                     if (item > max) {
1895                         max = item;
1896                     }
1897                 }
1898             }
1899
1900             return max;
1901         },
1902
1903         /**
1904          * Calculates the mean of all items in the array
1905          * @param {Array} array The Array to calculate the mean value of.
1906          * @return {Number} The mean.
1907          */
1908         mean: function(array) {
1909             return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
1910         },
1911
1912         /**
1913          * Calculates the sum of all items in the given array
1914          * @param {Array} array The Array to calculate the sum value of.
1915          * @return {Number} The sum.
1916          */
1917         sum: function(array) {
1918             var sum = 0,
1919                 i, ln, item;
1920
1921             for (i = 0,ln = array.length; i < ln; i++) {
1922                 item = array[i];
1923
1924                 sum += item;
1925             }
1926
1927             return sum;
1928         }
1929
1930     };
1931
1932     /**
1933      * Convenient alias to {@link Ext.Array#each}
1934      * @member Ext
1935      * @method each
1936      */
1937     Ext.each = Ext.Array.each;
1938
1939     /**
1940      * Alias to {@link Ext.Array#merge}.
1941      * @member Ext.Array
1942      * @method union
1943      */
1944     Ext.Array.union = Ext.Array.merge;
1945
1946     /**
1947      * Old alias to {@link Ext.Array#min}
1948      * @deprecated 4.0.0 Use {@link Ext.Array#min} instead
1949      * @member Ext
1950      * @method min
1951      */
1952     Ext.min = Ext.Array.min;
1953
1954     /**
1955      * Old alias to {@link Ext.Array#max}
1956      * @deprecated 4.0.0 Use {@link Ext.Array#max} instead
1957      * @member Ext
1958      * @method max
1959      */
1960     Ext.max = Ext.Array.max;
1961
1962     /**
1963      * Old alias to {@link Ext.Array#sum}
1964      * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
1965      * @member Ext
1966      * @method sum
1967      */
1968     Ext.sum = Ext.Array.sum;
1969
1970     /**
1971      * Old alias to {@link Ext.Array#mean}
1972      * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
1973      * @member Ext
1974      * @method mean
1975      */
1976     Ext.mean = Ext.Array.mean;
1977
1978     /**
1979      * Old alias to {@link Ext.Array#flatten}
1980      * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
1981      * @member Ext
1982      * @method flatten
1983      */
1984     Ext.flatten = Ext.Array.flatten;
1985
1986     /**
1987      * Old alias to {@link Ext.Array#clean Ext.Array.clean}
1988      * @deprecated 4.0.0 Use {@link Ext.Array.clean} instead
1989      * @member Ext
1990      * @method clean
1991      */
1992     Ext.clean = Ext.Array.clean;
1993
1994     /**
1995      * Old alias to {@link Ext.Array#unique Ext.Array.unique}
1996      * @deprecated 4.0.0 Use {@link Ext.Array.unique} instead
1997      * @member Ext
1998      * @method unique
1999      */
2000     Ext.unique = Ext.Array.unique;
2001
2002     /**
2003      * Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
2004      * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
2005      * @member Ext
2006      * @method pluck
2007      */
2008     Ext.pluck = Ext.Array.pluck;
2009
2010     /**
2011      * Convenient alias to {@link Ext.Array#toArray Ext.Array.toArray}
2012      * @param {Iterable} the iterable object to be turned into a true Array.
2013      * @member Ext
2014      * @method toArray
2015      * @return {Array} array
2016      */
2017     Ext.toArray = function() {
2018         return ExtArray.toArray.apply(ExtArray, arguments);
2019     }
2020 })();
2021
2022 /**
2023  * @class Ext.Function
2024  *
2025  * A collection of useful static methods to deal with function callbacks
2026  * @singleton
2027  */
2028
2029 Ext.Function = {
2030
2031     /**
2032      * A very commonly used method throughout the framework. It acts as a wrapper around another method
2033      * which originally accepts 2 arguments for <code>name</code> and <code>value</code>.
2034      * The wrapped function then allows "flexible" value setting of either:
2035      *
2036      * <ul>
2037      *      <li><code>name</code> and <code>value</code> as 2 arguments</li>
2038      *      <li>one single object argument with multiple key - value pairs</li>
2039      * </ul>
2040      *
2041      * For example:
2042      * <pre><code>
2043 var setValue = Ext.Function.flexSetter(function(name, value) {
2044     this[name] = value;
2045 });
2046
2047 // Afterwards
2048 // Setting a single name - value
2049 setValue('name1', 'value1');
2050
2051 // Settings multiple name - value pairs
2052 setValue({
2053     name1: 'value1',
2054     name2: 'value2',
2055     name3: 'value3'
2056 });
2057      * </code></pre>
2058      * @param {Function} setter
2059      * @returns {Function} flexSetter
2060      */
2061     flexSetter: function(fn) {
2062         return function(a, b) {
2063             var k, i;
2064
2065             if (a === null) {
2066                 return this;
2067             }
2068
2069             if (typeof a !== 'string') {
2070                 for (k in a) {
2071                     if (a.hasOwnProperty(k)) {
2072                         fn.call(this, k, a[k]);
2073                     }
2074                 }
2075
2076                 if (Ext.enumerables) {
2077                     for (i = Ext.enumerables.length; i--;) {
2078                         k = Ext.enumerables[i];
2079                         if (a.hasOwnProperty(k)) {
2080                             fn.call(this, k, a[k]);
2081                         }
2082                     }
2083                 }
2084             } else {
2085                 fn.call(this, a, b);
2086             }
2087
2088             return this;
2089         };
2090     },
2091
2092    /**
2093      * Create a new function from the provided <code>fn</code>, change <code>this</code> to the provided scope, optionally
2094      * overrides arguments for the call. (Defaults to the arguments passed by the caller)
2095      *
2096      * @param {Function} fn The function to delegate.
2097      * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
2098      * <b>If omitted, defaults to the browser window.</b>
2099      * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
2100      * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
2101      * if a number the args are inserted at the specified position
2102      * @return {Function} The new function
2103      */
2104     bind: function(fn, scope, args, appendArgs) {
2105         var method = fn,
2106             applyArgs;
2107
2108         return function() {
2109             var callArgs = args || arguments;
2110
2111             if (appendArgs === true) {
2112                 callArgs = Array.prototype.slice.call(arguments, 0);
2113                 callArgs = callArgs.concat(args);
2114             }
2115             else if (Ext.isNumber(appendArgs)) {
2116                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
2117                 applyArgs = [appendArgs, 0].concat(args); // create method call params
2118                 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
2119             }
2120
2121             return method.apply(scope || window, callArgs);
2122         };
2123     },
2124
2125     /**
2126      * Create a new function from the provided <code>fn</code>, the arguments of which are pre-set to `args`.
2127      * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
2128      * This is especially useful when creating callbacks.
2129      * For example:
2130      *
2131     var originalFunction = function(){
2132         alert(Ext.Array.from(arguments).join(' '));
2133     };
2134
2135     var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
2136
2137     callback(); // alerts 'Hello World'
2138     callback('by Me'); // alerts 'Hello World by Me'
2139
2140      * @param {Function} fn The original function
2141      * @param {Array} args The arguments to pass to new callback
2142      * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
2143      * @return {Function} The new callback function
2144      */
2145     pass: function(fn, args, scope) {
2146         if (args) {
2147             args = Ext.Array.from(args);
2148         }
2149
2150         return function() {
2151             return fn.apply(scope, args.concat(Ext.Array.toArray(arguments)));
2152         };
2153     },
2154
2155     /**
2156      * Create an alias to the provided method property with name <code>methodName</code> of <code>object</code>.
2157      * Note that the execution scope will still be bound to the provided <code>object</code> itself.
2158      *
2159      * @param {Object/Function} object
2160      * @param {String} methodName
2161      * @return {Function} aliasFn
2162      */
2163     alias: function(object, methodName) {
2164         return function() {
2165             return object[methodName].apply(object, arguments);
2166         };
2167     },
2168
2169     /**
2170      * Creates an interceptor function. The passed function is called before the original one. If it returns false,
2171      * the original one is not called. The resulting function returns the results of the original function.
2172      * The passed function is called with the parameters of the original function. Example usage:
2173      * <pre><code>
2174 var sayHi = function(name){
2175     alert('Hi, ' + name);
2176 }
2177
2178 sayHi('Fred'); // alerts "Hi, Fred"
2179
2180 // create a new function that validates input without
2181 // directly modifying the original function:
2182 var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
2183     return name == 'Brian';
2184 });
2185
2186 sayHiToFriend('Fred');  // no alert
2187 sayHiToFriend('Brian'); // alerts "Hi, Brian"
2188      </code></pre>
2189      * @param {Function} origFn The original function.
2190      * @param {Function} newFn The function to call before the original
2191      * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed.
2192      * <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b>
2193      * @param {Mixed} returnValue (optional) The value to return if the passed function return false (defaults to null).
2194      * @return {Function} The new function
2195      */
2196     createInterceptor: function(origFn, newFn, scope, returnValue) {
2197         var method = origFn;
2198         if (!Ext.isFunction(newFn)) {
2199             return origFn;
2200         }
2201         else {
2202             return function() {
2203                 var me = this,
2204                     args = arguments;
2205                 newFn.target = me;
2206                 newFn.method = origFn;
2207                 return (newFn.apply(scope || me || window, args) !== false) ? origFn.apply(me || window, args) : returnValue || null;
2208             };
2209         }
2210     },
2211
2212     /**
2213     * Creates a delegate (callback) which, when called, executes after a specific delay.
2214     * @param {Function} fn The function which will be called on a delay when the returned function is called.
2215     * Optionally, a replacement (or additional) argument list may be specified.
2216     * @param {Number} delay The number of milliseconds to defer execution by whenever called.
2217     * @param {Object} scope (optional) The scope (<code>this</code> reference) used by the function at execution time.
2218     * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
2219     * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
2220     * if a number the args are inserted at the specified position.
2221     * @return {Function} A function which, when called, executes the original function after the specified delay.
2222     */
2223     createDelayed: function(fn, delay, scope, args, appendArgs) {
2224         if (scope || args) {
2225             fn = Ext.Function.bind(fn, scope, args, appendArgs);
2226         }
2227         return function() {
2228             var me = this;
2229             setTimeout(function() {
2230                 fn.apply(me, arguments);
2231             }, delay);
2232         };
2233     },
2234
2235     /**
2236      * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
2237      * <pre><code>
2238 var sayHi = function(name){
2239     alert('Hi, ' + name);
2240 }
2241
2242 // executes immediately:
2243 sayHi('Fred');
2244
2245 // executes after 2 seconds:
2246 Ext.Function.defer(sayHi, 2000, this, ['Fred']);
2247
2248 // this syntax is sometimes useful for deferring
2249 // execution of an anonymous function:
2250 Ext.Function.defer(function(){
2251     alert('Anonymous');
2252 }, 100);
2253      </code></pre>
2254      * @param {Function} fn The function to defer.
2255      * @param {Number} millis The number of milliseconds for the setTimeout call (if less than or equal to 0 the function is executed immediately)
2256      * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
2257      * <b>If omitted, defaults to the browser window.</b>
2258      * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
2259      * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
2260      * if a number the args are inserted at the specified position
2261      * @return {Number} The timeout id that can be used with clearTimeout
2262      */
2263     defer: function(fn, millis, obj, args, appendArgs) {
2264         fn = Ext.Function.bind(fn, obj, args, appendArgs);
2265         if (millis > 0) {
2266             return setTimeout(fn, millis);
2267         }
2268         fn();
2269         return 0;
2270     },
2271
2272     /**
2273      * Create a combined function call sequence of the original function + the passed function.
2274      * The resulting function returns the results of the original function.
2275      * The passed function is called with the parameters of the original function. Example usage:
2276      *
2277      * <pre><code>
2278 var sayHi = function(name){
2279     alert('Hi, ' + name);
2280 }
2281
2282 sayHi('Fred'); // alerts "Hi, Fred"
2283
2284 var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
2285     alert('Bye, ' + name);
2286 });
2287
2288 sayGoodbye('Fred'); // both alerts show
2289      * </code></pre>
2290      *
2291      * @param {Function} origFn The original function.
2292      * @param {Function} newFn The function to sequence
2293      * @param {Object} scope (optional) The scope (this reference) in which the passed function is executed.
2294      * If omitted, defaults to the scope in which the original function is called or the browser window.
2295      * @return {Function} The new function
2296      */
2297     createSequence: function(origFn, newFn, scope) {
2298         if (!Ext.isFunction(newFn)) {
2299             return origFn;
2300         }
2301         else {
2302             return function() {
2303                 var retval = origFn.apply(this || window, arguments);
2304                 newFn.apply(scope || this || window, arguments);
2305                 return retval;
2306             };
2307         }
2308     },
2309
2310     /**
2311      * <p>Creates a delegate function, optionally with a bound scope which, when called, buffers
2312      * the execution of the passed function for the configured number of milliseconds.
2313      * If called again within that period, the impending invocation will be canceled, and the
2314      * timeout period will begin again.</p>
2315      *
2316      * @param {Function} fn The function to invoke on a buffered timer.
2317      * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
2318      * function.
2319      * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which
2320      * the passed function is executed. If omitted, defaults to the scope specified by the caller.
2321      * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
2322      * passed by the caller.
2323      * @return {Function} A function which invokes the passed function after buffering for the specified time.
2324      */
2325     createBuffered: function(fn, buffer, scope, args) {
2326         return function(){
2327             var timerId;
2328             return function() {
2329                 var me = this;
2330                 if (timerId) {
2331                     clearInterval(timerId);
2332                     timerId = null;
2333                 }
2334                 timerId = setTimeout(function(){
2335                     fn.apply(scope || me, args || arguments);
2336                 }, buffer);
2337             };
2338         }();
2339     },
2340
2341     /**
2342      * <p>Creates a throttled version of the passed function which, when called repeatedly and
2343      * rapidly, invokes the passed function only after a certain interval has elapsed since the
2344      * previous invocation.</p>
2345      *
2346      * <p>This is useful for wrapping functions which may be called repeatedly, such as
2347      * a handler of a mouse move event when the processing is expensive.</p>
2348      *
2349      * @param fn {Function} The function to execute at a regular time interval.
2350      * @param interval {Number} The interval <b>in milliseconds</b> on which the passed function is executed.
2351      * @param scope (optional) The scope (<code><b>this</b></code> reference) in which
2352      * the passed function is executed. If omitted, defaults to the scope specified by the caller.
2353      * @returns {Function} A function which invokes the passed function at the specified interval.
2354      */
2355     createThrottled: function(fn, interval, scope) {
2356         var lastCallTime, elapsed, lastArgs, timer, execute = function() {
2357             fn.apply(scope || this, lastArgs);
2358             lastCallTime = new Date().getTime();
2359         };
2360
2361         return function() {
2362             elapsed = new Date().getTime() - lastCallTime;
2363             lastArgs = arguments;
2364
2365             clearTimeout(timer);
2366             if (!lastCallTime || (elapsed >= interval)) {
2367                 execute();
2368             } else {
2369                 timer = setTimeout(execute, interval - elapsed);
2370             }
2371         };
2372     }
2373 };
2374
2375 /**
2376  * Shorthand for {@link Ext.Function#defer}
2377  * @member Ext
2378  * @method defer
2379  */
2380 Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
2381
2382 /**
2383  * Shorthand for {@link Ext.Function#pass}
2384  * @member Ext
2385  * @method pass
2386  */
2387 Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
2388
2389 /**
2390  * Shorthand for {@link Ext.Function#bind}
2391  * @member Ext
2392  * @method bind
2393  */
2394 Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
2395
2396 /**
2397  * @author Jacky Nguyen <jacky@sencha.com>
2398  * @docauthor Jacky Nguyen <jacky@sencha.com>
2399  * @class Ext.Object
2400  *
2401  * A collection of useful static methods to deal with objects
2402  *
2403  * @singleton
2404  */
2405
2406 (function() {
2407
2408 var ExtObject = Ext.Object = {
2409
2410     /**
2411      * Convert a `name` - `value` pair to an array of objects with support for nested structures; useful to construct
2412      * query strings. For example:
2413
2414     var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
2415
2416     // objects then equals:
2417     [
2418         { name: 'hobbies', value: 'reading' },
2419         { name: 'hobbies', value: 'cooking' },
2420         { name: 'hobbies', value: 'swimming' },
2421     ];
2422
2423     var objects = Ext.Object.toQueryObjects('dateOfBirth', {
2424         day: 3,
2425         month: 8,
2426         year: 1987,
2427         extra: {
2428             hour: 4
2429             minute: 30
2430         }
2431     }, true); // Recursive
2432
2433     // objects then equals:
2434     [
2435         { name: 'dateOfBirth[day]', value: 3 },
2436         { name: 'dateOfBirth[month]', value: 8 },
2437         { name: 'dateOfBirth[year]', value: 1987 },
2438         { name: 'dateOfBirth[extra][hour]', value: 4 },
2439         { name: 'dateOfBirth[extra][minute]', value: 30 },
2440     ];
2441
2442      * @param {String} name
2443      * @param {Mixed} value
2444      * @param {Boolean} recursive
2445      * @markdown
2446      */
2447     toQueryObjects: function(name, value, recursive) {
2448         var self = ExtObject.toQueryObjects,
2449             objects = [],
2450             i, ln;
2451
2452         if (Ext.isArray(value)) {
2453             for (i = 0, ln = value.length; i < ln; i++) {
2454                 if (recursive) {
2455                     objects = objects.concat(self(name + '[' + i + ']', value[i], true));
2456                 }
2457                 else {
2458                     objects.push({
2459                         name: name,
2460                         value: value[i]
2461                     });
2462                 }
2463             }
2464         }
2465         else if (Ext.isObject(value)) {
2466             for (i in value) {
2467                 if (value.hasOwnProperty(i)) {
2468                     if (recursive) {
2469                         objects = objects.concat(self(name + '[' + i + ']', value[i], true));
2470                     }
2471                     else {
2472                         objects.push({
2473                             name: name,
2474                             value: value[i]
2475                         });
2476                     }
2477                 }
2478             }
2479         }
2480         else {
2481             objects.push({
2482                 name: name,
2483                 value: value
2484             });
2485         }
2486
2487         return objects;
2488     },
2489
2490     /**
2491      * Takes an object and converts it to an encoded query string
2492
2493 - Non-recursive:
2494
2495     Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
2496     Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
2497     Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
2498     Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
2499     Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
2500
2501 - Recursive:
2502
2503     Ext.Object.toQueryString({
2504         username: 'Jacky',
2505         dateOfBirth: {
2506             day: 1,
2507             month: 2,
2508             year: 1911
2509         },
2510         hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
2511     }, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
2512               // username=Jacky
2513               //    &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
2514               //    &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
2515
2516      *
2517      * @param {Object} object The object to encode
2518      * @param {Boolean} recursive (optional) Whether or not to interpret the object in recursive format.
2519      * (PHP / Ruby on Rails servers and similar). Defaults to false
2520      * @return {String} queryString
2521      * @markdown
2522      */
2523     toQueryString: function(object, recursive) {
2524         var paramObjects = [],
2525             params = [],
2526             i, j, ln, paramObject, value;
2527
2528         for (i in object) {
2529             if (object.hasOwnProperty(i)) {
2530                 paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
2531             }
2532         }
2533
2534         for (j = 0, ln = paramObjects.length; j < ln; j++) {
2535             paramObject = paramObjects[j];
2536             value = paramObject.value;
2537
2538             if (Ext.isEmpty(value)) {
2539                 value = '';
2540             }
2541             else if (Ext.isDate(value)) {
2542                 value = Ext.Date.toString(value);
2543             }
2544
2545             params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
2546         }
2547
2548         return params.join('&');
2549     },
2550
2551     /**
2552      * Converts a query string back into an object.
2553      *
2554 - Non-recursive:
2555
2556     Ext.Object.fromQueryString(foo=1&bar=2); // returns {foo: 1, bar: 2}
2557     Ext.Object.fromQueryString(foo=&bar=2); // returns {foo: null, bar: 2}
2558     Ext.Object.fromQueryString(some%20price=%24300); // returns {'some price': '$300'}
2559     Ext.Object.fromQueryString(colors=red&colors=green&colors=blue); // returns {colors: ['red', 'green', 'blue']}
2560
2561 - Recursive:
2562
2563     Ext.Object.fromQueryString("username=Jacky&dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff", true);
2564
2565     // returns
2566     {
2567         username: 'Jacky',
2568         dateOfBirth: {
2569             day: '1',
2570             month: '2',
2571             year: '1911'
2572         },
2573         hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
2574     }
2575
2576      * @param {String} queryString The query string to decode
2577      * @param {Boolean} recursive (Optional) Whether or not to recursively decode the string. This format is supported by
2578      * PHP / Ruby on Rails servers and similar. Defaults to false
2579      * @return {Object}
2580      */
2581     fromQueryString: function(queryString, recursive) {
2582         var parts = queryString.replace(/^\?/, '').split('&'),
2583             object = {},
2584             temp, components, name, value, i, ln,
2585             part, j, subLn, matchedKeys, matchedName,
2586             keys, key, nextKey;
2587
2588         for (i = 0, ln = parts.length; i < ln; i++) {
2589             part = parts[i];
2590
2591             if (part.length > 0) {
2592                 components = part.split('=');
2593                 name = decodeURIComponent(components[0]);
2594                 value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
2595
2596                 if (!recursive) {
2597                     if (object.hasOwnProperty(name)) {
2598                         if (!Ext.isArray(object[name])) {
2599                             object[name] = [object[name]];
2600                         }
2601
2602                         object[name].push(value);
2603                     }
2604                     else {
2605                         object[name] = value;
2606                     }
2607                 }
2608                 else {
2609                     matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
2610                     matchedName = name.match(/^([^\[]+)/);
2611
2612                     if (!matchedName) {
2613                         Ext.Error.raise({
2614                             sourceClass: "Ext.Object",
2615                             sourceMethod: "fromQueryString",
2616                             queryString: queryString,
2617                             recursive: recursive,
2618                             msg: 'Malformed query string given, failed parsing name from "' + part + '"'
2619                         });
2620                     }
2621
2622                     name = matchedName[0];
2623                     keys = [];
2624
2625                     if (matchedKeys === null) {
2626                         object[name] = value;
2627                         continue;
2628                     }
2629
2630                     for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
2631                         key = matchedKeys[j];
2632                         key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
2633                         keys.push(key);
2634                     }
2635
2636                     keys.unshift(name);
2637
2638                     temp = object;
2639
2640                     for (j = 0, subLn = keys.length; j < subLn; j++) {
2641                         key = keys[j];
2642
2643                         if (j === subLn - 1) {
2644                             if (Ext.isArray(temp) && key === '') {
2645                                 temp.push(value);
2646                             }
2647                             else {
2648                                 temp[key] = value;
2649                             }
2650                         }
2651                         else {
2652                             if (temp[key] === undefined || typeof temp[key] === 'string') {
2653                                 nextKey = keys[j+1];
2654
2655                                 temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
2656                             }
2657
2658                             temp = temp[key];
2659                         }
2660                     }
2661                 }
2662             }
2663         }
2664
2665         return object;
2666     },
2667
2668     /**
2669      * Iterate through an object and invoke the given callback function for each iteration. The iteration can be stop
2670      * by returning `false` in the callback function. For example:
2671
2672     var person = {
2673         name: 'Jacky'
2674         hairColor: 'black'
2675         loves: ['food', 'sleeping', 'wife']
2676     };
2677
2678     Ext.Object.each(person, function(key, value, myself) {
2679         console.log(key + ":" + value);
2680
2681         if (key === 'hairColor') {
2682             return false; // stop the iteration
2683         }
2684     });
2685
2686      * @param {Object} object The object to iterate
2687      * @param {Function} fn The callback function. Passed arguments for each iteration are:
2688
2689 - {String} `key`
2690 - {Mixed} `value`
2691 - {Object} `object` The object itself
2692
2693      * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
2694      * @markdown
2695      */
2696     each: function(object, fn, scope) {
2697         for (var property in object) {
2698             if (object.hasOwnProperty(property)) {
2699                 if (fn.call(scope || object, property, object[property], object) === false) {
2700                     return;
2701                 }
2702             }
2703         }
2704     },
2705
2706     /**
2707      * Merges any number of objects recursively without referencing them or their children.
2708
2709     var extjs = {
2710         companyName: 'Ext JS',
2711         products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
2712         isSuperCool: true
2713         office: {
2714             size: 2000,
2715             location: 'Palo Alto',
2716             isFun: true
2717         }
2718     };
2719
2720     var newStuff = {
2721         companyName: 'Sencha Inc.',
2722         products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
2723         office: {
2724             size: 40000,
2725             location: 'Redwood City'
2726         }
2727     };
2728
2729     var sencha = Ext.Object.merge(extjs, newStuff);
2730
2731     // extjs and sencha then equals to
2732     {
2733         companyName: 'Sencha Inc.',
2734         products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
2735         isSuperCool: true
2736         office: {
2737             size: 30000,
2738             location: 'Redwood City'
2739             isFun: true
2740         }
2741     }
2742
2743      * @param {Object} object,...
2744      * @return {Object} merged The object that is created as a result of merging all the objects passed in.
2745      * @markdown
2746      */
2747     merge: function(source, key, value) {
2748         if (typeof key === 'string') {
2749             if (value && value.constructor === Object) {
2750                 if (source[key] && source[key].constructor === Object) {
2751                     ExtObject.merge(source[key], value);
2752                 }
2753                 else {
2754                     source[key] = Ext.clone(value);
2755                 }
2756             }
2757             else {
2758                 source[key] = value;
2759             }
2760
2761             return source;
2762         }
2763
2764         var i = 1,
2765             ln = arguments.length,
2766             object, property;
2767
2768         for (; i < ln; i++) {
2769             object = arguments[i];
2770
2771             for (property in object) {
2772                 if (object.hasOwnProperty(property)) {
2773                     ExtObject.merge(source, property, object[property]);
2774                 }
2775             }
2776         }
2777
2778         return source;
2779     },
2780
2781     /**
2782      * Returns the first matching key corresponding to the given value.
2783      * If no matching value is found, null is returned.
2784
2785     var person = {
2786         name: 'Jacky',
2787         loves: 'food'
2788     };
2789
2790     alert(Ext.Object.getKey(sencha, 'loves')); // alerts 'food'
2791
2792      * @param {Object} object
2793      * @param {Object} value The value to find
2794      * @markdown
2795      */
2796     getKey: function(object, value) {
2797         for (var property in object) {
2798             if (object.hasOwnProperty(property) && object[property] === value) {
2799                 return property;
2800             }
2801         }
2802
2803         return null;
2804     },
2805
2806     /**
2807      * Gets all values of the given object as an array.
2808
2809     var values = Ext.Object.getValues({
2810         name: 'Jacky',
2811         loves: 'food'
2812     }); // ['Jacky', 'food']
2813
2814      * @param {Object} object
2815      * @return {Array} An array of values from the object
2816      * @markdown
2817      */
2818     getValues: function(object) {
2819         var values = [],
2820             property;
2821
2822         for (property in object) {
2823             if (object.hasOwnProperty(property)) {
2824                 values.push(object[property]);
2825             }
2826         }
2827
2828         return values;
2829     },
2830
2831     /**
2832      * Gets all keys of the given object as an array.
2833
2834     var values = Ext.Object.getKeys({
2835         name: 'Jacky',
2836         loves: 'food'
2837     }); // ['name', 'loves']
2838
2839      * @param {Object} object
2840      * @return {Array} An array of keys from the object
2841      */
2842     getKeys: ('keys' in Object.prototype) ? Object.keys : function(object) {
2843         var keys = [],
2844             property;
2845
2846         for (property in object) {
2847             if (object.hasOwnProperty(property)) {
2848                 keys.push(property);
2849             }
2850         }
2851
2852         return keys;
2853     },
2854
2855     /**
2856      * Gets the total number of this object's own properties
2857
2858     var size = Ext.Object.getSize({
2859         name: 'Jacky',
2860         loves: 'food'
2861     }); // size equals 2
2862
2863      * @param {Object} object
2864      * @return {Number} size
2865      * @markdown
2866      */
2867     getSize: function(object) {
2868         var size = 0,
2869             property;
2870
2871         for (property in object) {
2872             if (object.hasOwnProperty(property)) {
2873                 size++;
2874             }
2875         }
2876
2877         return size;
2878     }
2879 };
2880
2881
2882 /**
2883  * A convenient alias method for {@link Ext.Object#merge}
2884  *
2885  * @member Ext
2886  * @method merge
2887  */
2888 Ext.merge = Ext.Object.merge;
2889
2890 /**
2891  * A convenient alias method for {@link Ext.Object#toQueryString}
2892  *
2893  * @member Ext
2894  * @method urlEncode
2895  * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString Ext.Object.toQueryString} instead
2896  */
2897 Ext.urlEncode = function() {
2898     var args = Ext.Array.from(arguments),
2899         prefix = '';
2900
2901     // Support for the old `pre` argument
2902     if ((typeof args[1] === 'string')) {
2903         prefix = args[1] + '&';
2904         args[1] = false;
2905     }
2906
2907     return prefix + Ext.Object.toQueryString.apply(Ext.Object, args);
2908 };
2909
2910 /**
2911  * A convenient alias method for {@link Ext.Object#fromQueryString}
2912  *
2913  * @member Ext
2914  * @method urlDecode
2915  * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString Ext.Object.fromQueryString} instead
2916  */
2917 Ext.urlDecode = function() {
2918     return Ext.Object.fromQueryString.apply(Ext.Object, arguments);
2919 };
2920
2921 })();
2922
2923 /**
2924  * @class Ext.Date
2925  * A set of useful static methods to deal with date
2926  * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
2927  * this object for convenience
2928  *
2929  * The date parsing and formatting syntax contains a subset of
2930  * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
2931  * supported will provide results equivalent to their PHP versions.
2932  *
2933  * The following is a list of all currently supported formats:
2934  * <pre class="">
2935 Format  Description                                                               Example returned values
2936 ------  -----------------------------------------------------------------------   -----------------------
2937   d     Day of the month, 2 digits with leading zeros                             01 to 31
2938   D     A short textual representation of the day of the week                     Mon to Sun
2939   j     Day of the month without leading zeros                                    1 to 31
2940   l     A full textual representation of the day of the week                      Sunday to Saturday
2941   N     ISO-8601 numeric representation of the day of the week                    1 (for Monday) through 7 (for Sunday)
2942   S     English ordinal suffix for the day of the month, 2 characters             st, nd, rd or th. Works well with j
2943   w     Numeric representation of the day of the week                             0 (for Sunday) to 6 (for Saturday)
2944   z     The day of the year (starting from 0)                                     0 to 364 (365 in leap years)
2945   W     ISO-8601 week number of year, weeks starting on Monday                    01 to 53
2946   F     A full textual representation of a month, such as January or March        January to December
2947   m     Numeric representation of a month, with leading zeros                     01 to 12
2948   M     A short textual representation of a month                                 Jan to Dec
2949   n     Numeric representation of a month, without leading zeros                  1 to 12
2950   t     Number of days in the given month                                         28 to 31
2951   L     Whether it&#39;s a leap year                                                  1 if it is a leap year, 0 otherwise.
2952   o     ISO-8601 year number (identical to (Y), but if the ISO week number (W)    Examples: 1998 or 2004
2953         belongs to the previous or next year, that year is used instead)
2954   Y     A full numeric representation of a year, 4 digits                         Examples: 1999 or 2003
2955   y     A two digit representation of a year                                      Examples: 99 or 03
2956   a     Lowercase Ante meridiem and Post meridiem                                 am or pm
2957   A     Uppercase Ante meridiem and Post meridiem                                 AM or PM
2958   g     12-hour format of an hour without leading zeros                           1 to 12
2959   G     24-hour format of an hour without leading zeros                           0 to 23
2960   h     12-hour format of an hour with leading zeros                              01 to 12
2961   H     24-hour format of an hour with leading zeros                              00 to 23
2962   i     Minutes, with leading zeros                                               00 to 59
2963   s     Seconds, with leading zeros                                               00 to 59
2964   u     Decimal fraction of a second                                              Examples:
2965         (minimum 1 digit, arbitrary number of digits allowed)                     001 (i.e. 0.001s) or
2966                                                                                   100 (i.e. 0.100s) or
2967                                                                                   999 (i.e. 0.999s) or
2968                                                                                   999876543210 (i.e. 0.999876543210s)
2969   O     Difference to Greenwich time (GMT) in hours and minutes                   Example: +1030
2970   P     Difference to Greenwich time (GMT) with colon between hours and minutes   Example: -08:00
2971   T     Timezone abbreviation of the machine running the code                     Examples: EST, MDT, PDT ...
2972   Z     Timezone offset in seconds (negative if west of UTC, positive if east)    -43200 to 50400
2973   c     ISO 8601 date
2974         Notes:                                                                    Examples:
2975         1) If unspecified, the month / day defaults to the current month / day,   1991 or
2976            the time defaults to midnight, while the timezone defaults to the      1992-10 or
2977            browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
2978            and minutes. The "T" delimiter, seconds, milliseconds and timezone     1994-08-19T16:20+01:00 or
2979            are optional.                                                          1995-07-18T17:21:28-02:00 or
2980         2) The decimal fraction of a second, if specified, must contain at        1996-06-17T18:22:29.98765+03:00 or
2981            least 1 digit (there is no limit to the maximum number                 1997-05-16T19:23:30,12345-0400 or
2982            of digits allowed), and may be delimited by either a '.' or a ','      1998-04-15T20:24:31.2468Z or
2983         Refer to the examples on the right for the various levels of              1999-03-14T20:24:32Z or
2984         date-time granularity which are supported, or see                         2000-02-13T21:25:33
2985         http://www.w3.org/TR/NOTE-datetime for more info.                         2001-01-12 22:26:34
2986   U     Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)                1193432466 or -2138434463
2987   MS    Microsoft AJAX serialized dates                                           \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
2988                                                                                   \/Date(1238606590509+0800)\/
2989 </pre>
2990  *
2991  * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
2992  * <pre><code>
2993 // Sample date:
2994 // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
2995
2996 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
2997 console.log(Ext.Date.format(dt, 'Y-m-d'));                          // 2007-01-10
2998 console.log(Ext.Date.format(dt, 'F j, Y, g:i a'));                  // January 10, 2007, 3:05 pm
2999 console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
3000 </code></pre>
3001  *
3002  * Here are some standard date/time patterns that you might find helpful.  They
3003  * are not part of the source of Ext.Date, but to use them you can simply copy this
3004  * block of code into any script that is included after Ext.Date and they will also become
3005  * globally available on the Date object.  Feel free to add or remove patterns as needed in your code.
3006  * <pre><code>
3007 Ext.Date.patterns = {
3008     ISO8601Long:"Y-m-d H:i:s",
3009     ISO8601Short:"Y-m-d",
3010     ShortDate: "n/j/Y",
3011     LongDate: "l, F d, Y",
3012     FullDateTime: "l, F d, Y g:i:s A",
3013     MonthDay: "F d",
3014     ShortTime: "g:i A",
3015     LongTime: "g:i:s A",
3016     SortableDateTime: "Y-m-d\\TH:i:s",
3017     UniversalSortableDateTime: "Y-m-d H:i:sO",
3018     YearMonth: "F, Y"
3019 };
3020 </code></pre>
3021  *
3022  * Example usage:
3023  * <pre><code>
3024 var dt = new Date();
3025 console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
3026 </code></pre>
3027  * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
3028  * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
3029  * @singleton
3030  */
3031
3032 /*
3033  * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
3034  * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
3035  * They generate precompiled functions from format patterns instead of parsing and
3036  * processing each pattern every time a date is formatted. These functions are available
3037  * on every Date object.
3038  */
3039
3040 (function() {
3041
3042 // create private copy of Ext's Ext.util.Format.format() method
3043 // - to remove unnecessary dependency
3044 // - to resolve namespace conflict with MS-Ajax's implementation
3045 function xf(format) {
3046     var args = Array.prototype.slice.call(arguments, 1);
3047     return format.replace(/\{(\d+)\}/g, function(m, i) {
3048         return args[i];
3049     });
3050 }
3051
3052 Ext.Date = {
3053     /**
3054      * Returns the current timestamp
3055      * @return {Date} The current timestamp
3056      */
3057     now: Date.now || function() {
3058         return +new Date();
3059     },
3060
3061     /**
3062      * @private
3063      * Private for now
3064      */
3065     toString: function(date) {
3066         var pad = Ext.String.leftPad;
3067
3068         return date.getFullYear() + "-"
3069             + pad(date.getMonth() + 1, 2, '0') + "-"
3070             + pad(date.getDate(), 2, '0') + "T"
3071             + pad(date.getHours(), 2, '0') + ":"
3072             + pad(date.getMinutes(), 2, '0') + ":"
3073             + pad(date.getSeconds(), 2, '0');
3074     },
3075
3076     /**
3077      * Returns the number of milliseconds between two dates
3078      * @param {Date} dateA The first date
3079      * @param {Date} dateB (optional) The second date, defaults to now
3080      * @return {Number} The difference in milliseconds
3081      */
3082     getElapsed: function(dateA, dateB) {
3083         return Math.abs(dateA - (dateB || new Date()));
3084     },
3085
3086     /**
3087      * Global flag which determines if strict date parsing should be used.
3088      * Strict date parsing will not roll-over invalid dates, which is the
3089      * default behaviour of javascript Date objects.
3090      * (see {@link #parse} for more information)
3091      * Defaults to <tt>false</tt>.
3092      * @static
3093      * @type Boolean
3094     */
3095     useStrict: false,
3096
3097     // private
3098     formatCodeToRegex: function(character, currentGroup) {
3099         // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
3100         var p = utilDate.parseCodes[character];
3101
3102         if (p) {
3103           p = typeof p == 'function'? p() : p;
3104           utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
3105         }
3106
3107         return p ? Ext.applyIf({
3108           c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
3109         }, p) : {
3110             g: 0,
3111             c: null,
3112             s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
3113         };
3114     },
3115
3116     /**
3117      * <p>An object hash in which each property is a date parsing function. The property name is the
3118      * format string which that function parses.</p>
3119      * <p>This object is automatically populated with date parsing functions as
3120      * date formats are requested for Ext standard formatting strings.</p>
3121      * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
3122      * may be used as a format string to {@link #parse}.<p>
3123      * <p>Example:</p><pre><code>
3124 Ext.Date.parseFunctions['x-date-format'] = myDateParser;
3125 </code></pre>
3126      * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
3127      * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
3128      * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
3129      * (i.e. prevent javascript Date "rollover") (The default must be false).
3130      * Invalid date strings should return null when parsed.</div></li>
3131      * </ul></div></p>
3132      * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
3133      * formatting function must be placed into the {@link #formatFunctions} property.
3134      * @property parseFunctions
3135      * @static
3136      * @type Object
3137      */
3138     parseFunctions: {
3139         "MS": function(input, strict) {
3140             // note: the timezone offset is ignored since the MS Ajax server sends
3141             // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
3142             var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
3143             var r = (input || '').match(re);
3144             return r? new Date(((r[1] || '') + r[2]) * 1) : null;
3145         }
3146     },
3147     parseRegexes: [],
3148
3149     /**
3150      * <p>An object hash in which each property is a date formatting function. The property name is the
3151      * format string which corresponds to the produced formatted date string.</p>
3152      * <p>This object is automatically populated with date formatting functions as
3153      * date formats are requested for Ext standard formatting strings.</p>
3154      * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
3155      * may be used as a format string to {@link #format}. Example:</p><pre><code>
3156 Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
3157 </code></pre>
3158      * <p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
3159      * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
3160      * </ul></div></p>
3161      * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
3162      * parsing function must be placed into the {@link #parseFunctions} property.
3163      * @property formatFunctions
3164      * @static
3165      * @type Object
3166      */
3167     formatFunctions: {
3168         "MS": function() {
3169             // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
3170             return '\\/Date(' + this.getTime() + ')\\/';
3171         }
3172     },
3173
3174     y2kYear : 50,
3175
3176     /**
3177      * Date interval constant
3178      * @static
3179      * @type String
3180      */
3181     MILLI : "ms",
3182
3183     /**
3184      * Date interval constant
3185      * @static
3186      * @type String
3187      */
3188     SECOND : "s",
3189
3190     /**
3191      * Date interval constant
3192      * @static
3193      * @type String
3194      */
3195     MINUTE : "mi",
3196
3197     /** Date interval constant
3198      * @static
3199      * @type String
3200      */
3201     HOUR : "h",
3202
3203     /**
3204      * Date interval constant
3205      * @static
3206      * @type String
3207      */
3208     DAY : "d",
3209
3210     /**
3211      * Date interval constant
3212      * @static
3213      * @type String
3214      */
3215     MONTH : "mo",
3216
3217     /**
3218      * Date interval constant
3219      * @static
3220      * @type String
3221      */
3222     YEAR : "y",
3223
3224     /**
3225      * <p>An object hash containing default date values used during date parsing.</p>
3226      * <p>The following properties are available:<div class="mdetail-params"><ul>
3227      * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
3228      * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
3229      * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
3230      * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
3231      * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
3232      * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
3233      * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
3234      * </ul></div></p>
3235      * <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
3236      * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
3237      * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
3238      * It is the responsiblity of the developer to account for this.</b></p>
3239      * Example Usage:
3240      * <pre><code>
3241 // set default day value to the first day of the month
3242 Ext.Date.defaults.d = 1;
3243
3244 // parse a February date string containing only year and month values.
3245 // setting the default day value to 1 prevents weird date rollover issues
3246 // when attempting to parse the following date string on, for example, March 31st 2009.
3247 Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
3248 </code></pre>
3249      * @property defaults
3250      * @static
3251      * @type Object
3252      */
3253     defaults: {},
3254
3255     /**
3256      * An array of textual day names.
3257      * Override these values for international dates.
3258      * Example:
3259      * <pre><code>
3260 Ext.Date.dayNames = [
3261     'SundayInYourLang',
3262     'MondayInYourLang',
3263     ...
3264 ];
3265 </code></pre>
3266      * @type Array
3267      * @static
3268      */
3269     dayNames : [
3270         "Sunday",
3271         "Monday",
3272         "Tuesday",
3273         "Wednesday",
3274         "Thursday",
3275         "Friday",
3276         "Saturday"
3277     ],
3278
3279     /**
3280      * An array of textual month names.
3281      * Override these values for international dates.
3282      * Example:
3283      * <pre><code>
3284 Ext.Date.monthNames = [
3285     'JanInYourLang',
3286     'FebInYourLang',
3287     ...
3288 ];
3289 </code></pre>
3290      * @type Array
3291      * @static
3292      */
3293     monthNames : [
3294         "January",
3295         "February",
3296         "March",
3297         "April",
3298         "May",
3299         "June",
3300         "July",
3301         "August",
3302         "September",
3303         "October",
3304         "November",
3305         "December"
3306     ],
3307
3308     /**
3309      * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
3310      * Override these values for international dates.
3311      * Example:
3312      * <pre><code>
3313 Ext.Date.monthNumbers = {
3314     'ShortJanNameInYourLang':0,
3315     'ShortFebNameInYourLang':1,
3316     ...
3317 };
3318 </code></pre>
3319      * @type Object
3320      * @static
3321      */
3322     monthNumbers : {
3323         Jan:0,
3324         Feb:1,
3325         Mar:2,
3326         Apr:3,
3327         May:4,
3328         Jun:5,
3329         Jul:6,
3330         Aug:7,
3331         Sep:8,
3332         Oct:9,
3333         Nov:10,
3334         Dec:11
3335     },
3336     /**
3337      * <p>The date format string that the {@link #dateRenderer} and {@link #date} functions use.
3338      * see {@link #Date} for details.</p>
3339      * <p>This defaults to <code>m/d/Y</code>, but may be overridden in a locale file.</p>
3340      * @property defaultFormat
3341      * @static
3342      * @type String
3343      */
3344     defaultFormat : "m/d/Y",
3345     /**
3346      * Get the short month name for the given month number.
3347      * Override this function for international dates.
3348      * @param {Number} month A zero-based javascript month number.
3349      * @return {String} The short month name.
3350      * @static
3351      */
3352     getShortMonthName : function(month) {
3353         return utilDate.monthNames[month].substring(0, 3);
3354     },
3355
3356     /**
3357      * Get the short day name for the given day number.
3358      * Override this function for international dates.
3359      * @param {Number} day A zero-based javascript day number.
3360      * @return {String} The short day name.
3361      * @static
3362      */
3363     getShortDayName : function(day) {
3364         return utilDate.dayNames[day].substring(0, 3);
3365     },
3366
3367     /**
3368      * Get the zero-based javascript month number for the given short/full month name.
3369      * Override this function for international dates.
3370      * @param {String} name The short/full month name.
3371      * @return {Number} The zero-based javascript month number.
3372      * @static
3373      */
3374     getMonthNumber : function(name) {
3375         // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
3376         return utilDate.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
3377     },
3378
3379     /**
3380      * Checks if the specified format contains hour information
3381      * @param {String} format The format to check
3382      * @return {Boolean} True if the format contains hour information
3383      * @static
3384      */
3385     formatContainsHourInfo : (function(){
3386         var stripEscapeRe = /(\\.)/g,
3387             hourInfoRe = /([gGhHisucUOPZ]|MS)/;
3388         return function(format){
3389             return hourInfoRe.test(format.replace(stripEscapeRe, ''));
3390         };
3391     })(),
3392
3393     /**
3394      * Checks if the specified format contains information about
3395      * anything other than the time.
3396      * @param {String} format The format to check
3397      * @return {Boolean} True if the format contains information about
3398      * date/day information.
3399      * @static
3400      */
3401     formatContainsDateInfo : (function(){
3402         var stripEscapeRe = /(\\.)/g,
3403             dateInfoRe = /([djzmnYycU]|MS)/;
3404
3405         return function(format){
3406             return dateInfoRe.test(format.replace(stripEscapeRe, ''));
3407         };
3408     })(),
3409
3410     /**
3411      * The base format-code to formatting-function hashmap used by the {@link #format} method.
3412      * Formatting functions are strings (or functions which return strings) which
3413      * will return the appropriate value when evaluated in the context of the Date object
3414      * from which the {@link #format} method is called.
3415      * Add to / override these mappings for custom date formatting.
3416      * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
3417      * Example:
3418      * <pre><code>
3419 Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
3420 console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
3421 </code></pre>
3422      * @type Object
3423      * @static
3424      */
3425     formatCodes : {
3426         d: "Ext.String.leftPad(this.getDate(), 2, '0')",
3427         D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
3428         j: "this.getDate()",
3429         l: "Ext.Date.dayNames[this.getDay()]",
3430         N: "(this.getDay() ? this.getDay() : 7)",
3431         S: "Ext.Date.getSuffix(this)",
3432         w: "this.getDay()",
3433         z: "Ext.Date.getDayOfYear(this)",
3434         W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
3435         F: "Ext.Date.monthNames[this.getMonth()]",
3436         m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
3437         M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
3438         n: "(this.getMonth() + 1)",
3439         t: "Ext.Date.getDaysInMonth(this)",
3440         L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
3441         o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
3442         Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
3443         y: "('' + this.getFullYear()).substring(2, 4)",
3444         a: "(this.getHours() < 12 ? 'am' : 'pm')",
3445         A: "(this.getHours() < 12 ? 'AM' : 'PM')",
3446         g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
3447         G: "this.getHours()",
3448         h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
3449         H: "Ext.String.leftPad(this.getHours(), 2, '0')",
3450         i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
3451         s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
3452         u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
3453         O: "Ext.Date.getGMTOffset(this)",
3454         P: "Ext.Date.getGMTOffset(this, true)",
3455         T: "Ext.Date.getTimezone(this)",
3456         Z: "(this.getTimezoneOffset() * -60)",
3457
3458         c: function() { // ISO-8601 -- GMT format
3459             for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
3460                 var e = c.charAt(i);
3461                 code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
3462             }
3463             return code.join(" + ");
3464         },
3465         /*
3466         c: function() { // ISO-8601 -- UTC format
3467             return [
3468               "this.getUTCFullYear()", "'-'",
3469               "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
3470               "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
3471               "'T'",
3472               "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
3473               "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
3474               "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
3475               "'Z'"
3476             ].join(" + ");
3477         },
3478         */
3479
3480         U: "Math.round(this.getTime() / 1000)"
3481     },
3482
3483     /**
3484      * Checks if the passed Date parameters will cause a javascript Date "rollover".
3485      * @param {Number} year 4-digit year
3486      * @param {Number} month 1-based month-of-year
3487      * @param {Number} day Day of month
3488      * @param {Number} hour (optional) Hour
3489      * @param {Number} minute (optional) Minute
3490      * @param {Number} second (optional) Second
3491      * @param {Number} millisecond (optional) Millisecond
3492      * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
3493      * @static
3494      */
3495     isValid : function(y, m, d, h, i, s, ms) {
3496         // setup defaults
3497         h = h || 0;
3498         i = i || 0;
3499         s = s || 0;
3500         ms = ms || 0;
3501
3502         // Special handling for year < 100
3503         var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
3504
3505         return y == dt.getFullYear() &&
3506             m == dt.getMonth() + 1 &&
3507             d == dt.getDate() &&
3508             h == dt.getHours() &&
3509             i == dt.getMinutes() &&
3510             s == dt.getSeconds() &&
3511             ms == dt.getMilliseconds();
3512     },
3513
3514     /**
3515      * Parses the passed string using the specified date format.
3516      * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
3517      * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
3518      * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
3519      * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
3520      * Keep in mind that the input date string must precisely match the specified format string
3521      * in order for the parse operation to be successful (failed parse operations return a null value).
3522      * <p>Example:</p><pre><code>
3523 //dt = Fri May 25 2007 (current date)
3524 var dt = new Date();
3525
3526 //dt = Thu May 25 2006 (today&#39;s month/day in 2006)
3527 dt = Ext.Date.parse("2006", "Y");
3528
3529 //dt = Sun Jan 15 2006 (all date parts specified)
3530 dt = Ext.Date.parse("2006-01-15", "Y-m-d");
3531
3532 //dt = Sun Jan 15 2006 15:20:01
3533 dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
3534
3535 // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
3536 dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
3537 </code></pre>
3538      * @param {String} input The raw date string.
3539      * @param {String} format The expected date string format.
3540      * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
3541                         (defaults to false). Invalid date strings will return null when parsed.
3542      * @return {Date} The parsed Date.
3543      * @static
3544      */
3545     parse : function(input, format, strict) {
3546         var p = utilDate.parseFunctions;
3547         if (p[format] == null) {
3548             utilDate.createParser(format);
3549         }
3550         return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
3551     },
3552
3553     // Backwards compat
3554     parseDate: function(input, format, strict){
3555         return utilDate.parse(input, format, strict);
3556     },
3557
3558
3559     // private
3560     getFormatCode : function(character) {
3561         var f = utilDate.formatCodes[character];
3562
3563         if (f) {
3564           f = typeof f == 'function'? f() : f;
3565           utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
3566         }
3567
3568         // note: unknown characters are treated as literals
3569         return f || ("'" + Ext.String.escape(character) + "'");
3570     },
3571
3572     // private
3573     createFormat : function(format) {
3574         var code = [],
3575             special = false,
3576             ch = '';
3577
3578         for (var i = 0; i < format.length; ++i) {
3579             ch = format.charAt(i);
3580             if (!special && ch == "\\") {
3581                 special = true;
3582             } else if (special) {
3583                 special = false;
3584                 code.push("'" + Ext.String.escape(ch) + "'");
3585             } else {
3586                 code.push(utilDate.getFormatCode(ch));
3587             }
3588         }
3589         utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
3590     },
3591
3592     // private
3593     createParser : (function() {
3594         var code = [
3595             "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
3596                 "def = Ext.Date.defaults,",
3597                 "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
3598
3599             "if(results){",
3600                 "{1}",
3601
3602                 "if(u != null){", // i.e. unix time is defined
3603                     "v = new Date(u * 1000);", // give top priority to UNIX time
3604                 "}else{",
3605                     // create Date object representing midnight of the current day;
3606                     // this will provide us with our date defaults
3607                     // (note: clearTime() handles Daylight Saving Time automatically)
3608                     "dt = Ext.Date.clearTime(new Date);",
3609
3610                     // date calculations (note: these calculations create a dependency on Ext.Number.from())
3611                     "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
3612                     "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
3613                     "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
3614
3615                     // time calculations (note: these calculations create a dependency on Ext.Number.from())
3616                     "h  = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
3617                     "i  = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
3618                     "s  = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
3619                     "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
3620
3621                     "if(z >= 0 && y >= 0){",
3622                         // both the year and zero-based day of year are defined and >= 0.
3623                         // these 2 values alone provide sufficient info to create a full date object
3624
3625                         // create Date object representing January 1st for the given year
3626                         // handle years < 100 appropriately
3627                         "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
3628
3629                         // then add day of year, checking for Date "rollover" if necessary
3630                         "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
3631                     "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
3632                         "v = null;", // invalid date, so return null
3633                     "}else{",
3634                         // plain old Date object
3635                         // handle years < 100 properly
3636                         "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
3637                     "}",
3638                 "}",
3639             "}",
3640
3641             "if(v){",
3642                 // favour UTC offset over GMT offset
3643                 "if(zz != null){",
3644                     // reset to UTC, then add offset
3645                     "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
3646                 "}else if(o){",
3647                     // reset to GMT, then add offset
3648                     "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
3649                 "}",
3650             "}",
3651
3652             "return v;"
3653         ].join('\n');
3654
3655         return function(format) {
3656             var regexNum = utilDate.parseRegexes.length,
3657                 currentGroup = 1,
3658                 calc = [],
3659                 regex = [],
3660                 special = false,
3661                 ch = "";
3662
3663             for (var i = 0; i < format.length; ++i) {
3664                 ch = format.charAt(i);
3665                 if (!special && ch == "\\") {
3666                     special = true;
3667                 } else if (special) {
3668                     special = false;
3669                     regex.push(Ext.String.escape(ch));
3670                 } else {
3671                     var obj = utilDate.formatCodeToRegex(ch, currentGroup);
3672                     currentGroup += obj.g;
3673                     regex.push(obj.s);
3674                     if (obj.g && obj.c) {
3675                         calc.push(obj.c);
3676                     }
3677                 }
3678             }
3679
3680             utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
3681             utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
3682         };
3683     })(),
3684
3685     // private
3686     parseCodes : {
3687         /*
3688          * Notes:
3689          * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
3690          * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
3691          * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
3692          */
3693         d: {
3694             g:1,
3695             c:"d = parseInt(results[{0}], 10);\n",
3696             s:"(\\d{2})" // day of month with leading zeroes (01 - 31)
3697         },
3698         j: {
3699             g:1,
3700             c:"d = parseInt(results[{0}], 10);\n",
3701             s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
3702         },
3703         D: function() {
3704             for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
3705             return {
3706                 g:0,
3707                 c:null,
3708                 s:"(?:" + a.join("|") +")"
3709             };
3710         },
3711         l: function() {
3712             return {
3713                 g:0,
3714                 c:null,
3715                 s:"(?:" + utilDate.dayNames.join("|") + ")"
3716             };
3717         },
3718         N: {
3719             g:0,
3720             c:null,
3721             s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
3722         },
3723         S: {
3724             g:0,
3725             c:null,
3726             s:"(?:st|nd|rd|th)"
3727         },
3728         w: {
3729             g:0,
3730             c:null,
3731             s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
3732         },
3733         z: {
3734             g:1,
3735             c:"z = parseInt(results[{0}], 10);\n",
3736             s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
3737         },
3738         W: {
3739             g:0,
3740             c:null,
3741             s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
3742         },
3743         F: function() {
3744             return {
3745                 g:1,
3746                 c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
3747                 s:"(" + utilDate.monthNames.join("|") + ")"
3748             };
3749         },
3750         M: function() {
3751             for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
3752             return Ext.applyIf({
3753                 s:"(" + a.join("|") + ")"
3754             }, utilDate.formatCodeToRegex("F"));
3755         },
3756         m: {
3757             g:1,
3758             c:"m = parseInt(results[{0}], 10) - 1;\n",
3759             s:"(\\d{2})" // month number with leading zeros (01 - 12)
3760         },
3761         n: {
3762             g:1,
3763             c:"m = parseInt(results[{0}], 10) - 1;\n",
3764             s:"(\\d{1,2})" // month number without leading zeros (1 - 12)
3765         },
3766         t: {
3767             g:0,
3768             c:null,
3769             s:"(?:\\d{2})" // no. of days in the month (28 - 31)
3770         },
3771         L: {
3772             g:0,
3773             c:null,
3774             s:"(?:1|0)"
3775         },
3776         o: function() {
3777             return utilDate.formatCodeToRegex("Y");
3778         },
3779         Y: {
3780             g:1,
3781             c:"y = parseInt(results[{0}], 10);\n",
3782             s:"(\\d{4})" // 4-digit year
3783         },
3784         y: {
3785             g:1,
3786             c:"var ty = parseInt(results[{0}], 10);\n"
3787                 + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
3788             s:"(\\d{1,2})"
3789         },
3790         /**
3791          * In the am/pm parsing routines, we allow both upper and lower case
3792          * even though it doesn't exactly match the spec. It gives much more flexibility
3793          * in being able to specify case insensitive regexes.
3794          */
3795         a: {
3796             g:1,
3797             c:"if (/(am)/i.test(results[{0}])) {\n"
3798                 + "if (!h || h == 12) { h = 0; }\n"
3799                 + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
3800             s:"(am|pm|AM|PM)"
3801         },
3802         A: {
3803             g:1,
3804             c:"if (/(am)/i.test(results[{0}])) {\n"
3805                 + "if (!h || h == 12) { h = 0; }\n"
3806                 + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
3807             s:"(AM|PM|am|pm)"
3808         },
3809         g: function() {
3810             return utilDate.formatCodeToRegex("G");
3811         },
3812         G: {
3813             g:1,
3814             c:"h = parseInt(results[{0}], 10);\n",
3815             s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
3816         },
3817         h: function() {
3818             return utilDate.formatCodeToRegex("H");
3819         },
3820         H: {
3821             g:1,
3822             c:"h = parseInt(results[{0}], 10);\n",
3823             s:"(\\d{2})" //  24-hr format of an hour with leading zeroes (00 - 23)
3824         },
3825         i: {
3826             g:1,
3827             c:"i = parseInt(results[{0}], 10);\n",
3828             s:"(\\d{2})" // minutes with leading zeros (00 - 59)
3829         },
3830         s: {
3831             g:1,
3832             c:"s = parseInt(results[{0}], 10);\n",
3833             s:"(\\d{2})" // seconds with leading zeros (00 - 59)
3834         },
3835         u: {
3836             g:1,
3837             c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
3838             s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
3839         },
3840         O: {
3841             g:1,
3842             c:[
3843                 "o = results[{0}];",
3844                 "var sn = o.substring(0,1),", // get + / - sign
3845                     "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
3846                     "mn = o.substring(3,5) % 60;", // get minutes
3847                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
3848             ].join("\n"),
3849             s: "([+\-]\\d{4})" // GMT offset in hrs and mins
3850         },
3851         P: {
3852             g:1,
3853             c:[
3854                 "o = results[{0}];",
3855                 "var sn = o.substring(0,1),", // get + / - sign
3856                     "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
3857                     "mn = o.substring(4,6) % 60;", // get minutes
3858                 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
3859             ].join("\n"),
3860             s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
3861         },
3862         T: {
3863             g:0,
3864             c:null,
3865             s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
3866         },
3867         Z: {
3868             g:1,
3869             c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
3870                   + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
3871             s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
3872         },
3873         c: function() {
3874             var calc = [],
3875                 arr = [
3876                     utilDate.formatCodeToRegex("Y", 1), // year
3877                     utilDate.formatCodeToRegex("m", 2), // month
3878                     utilDate.formatCodeToRegex("d", 3), // day
3879                     utilDate.formatCodeToRegex("h", 4), // hour
3880                     utilDate.formatCodeToRegex("i", 5), // minute
3881                     utilDate.formatCodeToRegex("s", 6), // second
3882                     {c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
3883                     {c:[ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified
3884                         "if(results[8]) {", // timezone specified
3885                             "if(results[8] == 'Z'){",
3886                                 "zz = 0;", // UTC
3887                             "}else if (results[8].indexOf(':') > -1){",
3888                                 utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
3889                             "}else{",
3890                                 utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
3891                             "}",
3892                         "}"
3893                     ].join('\n')}
3894                 ];
3895
3896             for (var i = 0, l = arr.length; i < l; ++i) {
3897                 calc.push(arr[i].c);
3898             }
3899
3900             return {
3901                 g:1,
3902                 c:calc.join(""),
3903                 s:[
3904                     arr[0].s, // year (required)
3905                     "(?:", "-", arr[1].s, // month (optional)
3906                         "(?:", "-", arr[2].s, // day (optional)
3907                             "(?:",
3908                                 "(?:T| )?", // time delimiter -- either a "T" or a single blank space
3909                                 arr[3].s, ":", arr[4].s,  // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space
3910                                 "(?::", arr[5].s, ")?", // seconds (optional)
3911                                 "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
3912                                 "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
3913                             ")?",
3914                         ")?",
3915                     ")?"
3916                 ].join("")
3917             };
3918         },
3919         U: {
3920             g:1,
3921             c:"u = parseInt(results[{0}], 10);\n",
3922             s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
3923         }
3924     },
3925
3926     //Old Ext.Date prototype methods.
3927     // private
3928     dateFormat: function(date, format) {
3929         return utilDate.format(date, format);
3930     },
3931
3932     /**
3933      * Formats a date given the supplied format string.
3934      * @param {Date} date The date to format
3935      * @param {String} format The format string
3936      * @return {String} The formatted date
3937      */
3938     format: function(date, format) {
3939         if (utilDate.formatFunctions[format] == null) {
3940             utilDate.createFormat(format);
3941         }
3942         var result = utilDate.formatFunctions[format].call(date);
3943         return result + '';
3944     },
3945
3946     /**
3947      * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
3948      *
3949      * Note: The date string returned by the javascript Date object's toString() method varies
3950      * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
3951      * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
3952      * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
3953      * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
3954      * from the GMT offset portion of the date string.
3955      * @param {Date} date The date
3956      * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
3957      */
3958     getTimezone : function(date) {
3959         // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
3960         //
3961         // Opera  : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
3962         // Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF)
3963         // FF     : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
3964         // IE     : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
3965         // IE     : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
3966         //
3967         // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
3968         // step 1: (?:\((.*)\) -- find timezone in parentheses
3969         // step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string
3970         // step 3: remove all non uppercase characters found in step 1 and 2
3971         return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
3972     },
3973
3974     /**
3975      * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
3976      * @param {Date} date The date
3977      * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
3978      * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
3979      */
3980     getGMTOffset : function(date, colon) {
3981         var offset = date.getTimezoneOffset();
3982         return (offset > 0 ? "-" : "+")
3983             + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
3984             + (colon ? ":" : "")
3985             + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
3986     },
3987
3988     /**
3989      * Get the numeric day number of the year, adjusted for leap year.
3990      * @param {Date} date The date
3991      * @return {Number} 0 to 364 (365 in leap years).
3992      */
3993     getDayOfYear: function(date) {
3994         var num = 0,
3995             d = Ext.Date.clone(date),
3996             m = date.getMonth(),
3997             i;
3998
3999         for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
4000             num += utilDate.getDaysInMonth(d);
4001         }
4002         return num + date.getDate() - 1;
4003     },
4004
4005     /**
4006      * Get the numeric ISO-8601 week number of the year.
4007      * (equivalent to the format specifier 'W', but without a leading zero).
4008      * @param {Date} date The date
4009      * @return {Number} 1 to 53
4010      */
4011     getWeekOfYear : (function() {
4012         // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
4013         var ms1d = 864e5, // milliseconds in a day
4014             ms7d = 7 * ms1d; // milliseconds in a week
4015
4016         return function(date) { // return a closure so constants get calculated only once
4017             var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
4018                 AWN = Math.floor(DC3 / 7), // an Absolute Week Number
4019                 Wyr = new Date(AWN * ms7d).getUTCFullYear();
4020
4021             return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
4022         };
4023     })(),
4024
4025     /**
4026      * Checks if the current date falls within a leap year.
4027      * @param {Date} date The date
4028      * @return {Boolean} True if the current date falls within a leap year, false otherwise.
4029      */
4030     isLeapYear : function(date) {
4031         var year = date.getFullYear();
4032         return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
4033     },
4034
4035     /**
4036      * Get the first day of the current month, adjusted for leap year.  The returned value
4037      * is the numeric day index within the week (0-6) which can be used in conjunction with
4038      * the {@link #monthNames} array to retrieve the textual day name.
4039      * Example:
4040      * <pre><code>
4041 var dt = new Date('1/10/2007'),
4042     firstDay = Ext.Date.getFirstDayOfMonth(dt);
4043 console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
4044      * </code></pre>
4045      * @param {Date} date The date
4046      * @return {Number} The day number (0-6).
4047      */
4048     getFirstDayOfMonth : function(date) {
4049         var day = (date.getDay() - (date.getDate() - 1)) % 7;
4050         return (day < 0) ? (day + 7) : day;
4051     },
4052
4053     /**
4054      * Get the last day of the current month, adjusted for leap year.  The returned value
4055      * is the numeric day index within the week (0-6) which can be used in conjunction with
4056      * the {@link #monthNames} array to retrieve the textual day name.
4057      * Example:
4058      * <pre><code>
4059 var dt = new Date('1/10/2007'),
4060     lastDay = Ext.Date.getLastDayOfMonth(dt);
4061 console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
4062      * </code></pre>
4063      * @param {Date} date The date
4064      * @return {Number} The day number (0-6).
4065      */
4066     getLastDayOfMonth : function(date) {
4067         return utilDate.getLastDateOfMonth(date).getDay();
4068     },
4069
4070
4071     /**
4072      * Get the date of the first day of the month in which this date resides.
4073      * @param {Date} date The date
4074      * @return {Date}
4075      */
4076     getFirstDateOfMonth : function(date) {
4077         return new Date(date.getFullYear(), date.getMonth(), 1);
4078     },
4079
4080     /**
4081      * Get the date of the last day of the month in which this date resides.
4082      * @param {Date} date The date
4083      * @return {Date}
4084      */
4085     getLastDateOfMonth : function(date) {
4086         return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
4087     },
4088
4089     /**
4090      * Get the number of days in the current month, adjusted for leap year.
4091      * @param {Date} date The date
4092      * @return {Number} The number of days in the month.
4093      */
4094     getDaysInMonth: (function() {
4095         var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
4096
4097         return function(date) { // return a closure for efficiency
4098             var m = date.getMonth();
4099
4100             return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
4101         };
4102     })(),
4103
4104     /**
4105      * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
4106      * @param {Date} date The date
4107      * @return {String} 'st, 'nd', 'rd' or 'th'.
4108      */
4109     getSuffix : function(date) {
4110         switch (date.getDate()) {
4111             case 1:
4112             case 21:
4113             case 31:
4114                 return "st";
4115             case 2:
4116             case 22:
4117                 return "nd";
4118             case 3:
4119             case 23:
4120                 return "rd";
4121             default:
4122                 return "th";
4123         }
4124     },
4125
4126     /**
4127      * Creates and returns a new Date instance with the exact same date value as the called instance.
4128      * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
4129      * variable will also be changed.  When the intention is to create a new variable that will not
4130      * modify the original instance, you should create a clone.
4131      *
4132      * Example of correctly cloning a date:
4133      * <pre><code>
4134 //wrong way:
4135 var orig = new Date('10/1/2006');
4136 var copy = orig;
4137 copy.setDate(5);
4138 console.log(orig);  //returns 'Thu Oct 05 2006'!
4139
4140 //correct way:
4141 var orig = new Date('10/1/2006'),
4142     copy = Ext.Date.clone(orig);
4143 copy.setDate(5);
4144 console.log(orig);  //returns 'Thu Oct 01 2006'
4145      * </code></pre>
4146      * @param {Date} date The date
4147      * @return {Date} The new Date instance.
4148      */
4149     clone : function(date) {
4150         return new Date(date.getTime());
4151     },
4152
4153     /**
4154      * Checks if the current date is affected by Daylight Saving Time (DST).
4155      * @param {Date} date The date
4156      * @return {Boolean} True if the current date is affected by DST.
4157      */
4158     isDST : function(date) {
4159         // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
4160         // courtesy of @geoffrey.mcgill
4161         return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
4162     },
4163
4164     /**
4165      * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
4166      * automatically adjusting for Daylight Saving Time (DST) where applicable.
4167      * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
4168      * @param {Date} date The date
4169      * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
4170      * @return {Date} this or the clone.
4171      */
4172     clearTime : function(date, clone) {
4173         if (clone) {
4174             return Ext.Date.clearTime(Ext.Date.clone(date));
4175         }
4176
4177         // get current date before clearing time
4178         var d = date.getDate();
4179
4180         // clear time
4181         date.setHours(0);
4182         date.setMinutes(0);
4183         date.setSeconds(0);
4184         date.setMilliseconds(0);
4185
4186         if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
4187             // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
4188             // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
4189
4190             // increment hour until cloned date == current date
4191             for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
4192
4193             date.setDate(d);
4194             date.setHours(c.getHours());
4195         }
4196
4197         return date;
4198     },
4199
4200     /**
4201      * Provides a convenient method for performing basic date arithmetic. This method
4202      * does not modify the Date instance being called - it creates and returns
4203      * a new Date instance containing the resulting date value.
4204      *
4205      * Examples:
4206      * <pre><code>
4207 // Basic usage:
4208 var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
4209 console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
4210
4211 // Negative values will be subtracted:
4212 var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
4213 console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
4214
4215      * </code></pre>
4216      *
4217      * @param {Date} date The date to modify
4218      * @param {String} interval A valid date interval enum value.
4219      * @param {Number} value The amount to add to the current date.
4220      * @return {Date} The new Date instance.
4221      */
4222     add : function(date, interval, value) {
4223         var d = Ext.Date.clone(date),
4224             Date = Ext.Date;
4225         if (!interval || value === 0) return d;
4226
4227         switch(interval.toLowerCase()) {
4228             case Ext.Date.MILLI:
4229                 d.setMilliseconds(d.getMilliseconds() + value);
4230                 break;
4231             case Ext.Date.SECOND:
4232                 d.setSeconds(d.getSeconds() + value);
4233                 break;
4234             case Ext.Date.MINUTE:
4235                 d.setMinutes(d.getMinutes() + value);
4236                 break;
4237             case Ext.Date.HOUR:
4238                 d.setHours(d.getHours() + value);
4239                 break;
4240             case Ext.Date.DAY:
4241                 d.setDate(d.getDate() + value);
4242                 break;
4243             case Ext.Date.MONTH:
4244                 var day = date.getDate();
4245                 if (day > 28) {
4246                     day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), 'mo', value)).getDate());
4247                 }
4248                 d.setDate(day);
4249                 d.setMonth(date.getMonth() + value);
4250                 break;
4251             case Ext.Date.YEAR:
4252                 d.setFullYear(date.getFullYear() + value);
4253                 break;
4254         }
4255         return d;
4256     },
4257
4258     /**
4259      * Checks if a date falls on or between the given start and end dates.
4260      * @param {Date} date The date to check
4261      * @param {Date} start Start date
4262      * @param {Date} end End date
4263      * @return {Boolean} true if this date falls on or between the given start and end dates.
4264      */
4265     between : function(date, start, end) {
4266         var t = date.getTime();
4267         return start.getTime() <= t && t <= end.getTime();
4268     },
4269
4270     //Maintains compatibility with old static and prototype window.Date methods.
4271     compat: function() {
4272         var nativeDate = window.Date,
4273             p, u,
4274             statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'],
4275             proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
4276
4277         //Append statics
4278         Ext.Array.forEach(statics, function(s) {
4279             nativeDate[s] = utilDate[s];
4280         });
4281
4282         //Append to prototype
4283         Ext.Array.forEach(proto, function(s) {
4284             nativeDate.prototype[s] = function() {
4285                 var args = Array.prototype.slice.call(arguments);
4286                 args.unshift(this);
4287                 return utilDate[s].apply(utilDate, args);
4288             };
4289         });
4290     }
4291 };
4292
4293 var utilDate = Ext.Date;
4294
4295 })();
4296
4297 /**
4298  * @author Jacky Nguyen <jacky@sencha.com>
4299  * @docauthor Jacky Nguyen <jacky@sencha.com>
4300  * @class Ext.Base
4301  *
4302  * The root of all classes created with {@link Ext#define}
4303  * All prototype and static members of this class are inherited by any other class
4304  *
4305  */
4306 (function(flexSetter) {
4307
4308 var Base = Ext.Base = function() {};
4309     Base.prototype = {
4310         $className: 'Ext.Base',
4311
4312         $class: Base,
4313
4314         /**
4315          * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
4316          * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
4317          * for a detailed comparison
4318
4319     Ext.define('My.Cat', {
4320         statics: {
4321             speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
4322         },
4323
4324         constructor: function() {
4325             alert(this.self.speciesName); / dependent on 'this'
4326
4327             return this;
4328         },
4329
4330         clone: function() {
4331             return new this.self();
4332         }
4333     });
4334
4335
4336     Ext.define('My.SnowLeopard', {
4337         extend: 'My.Cat',
4338         statics: {
4339             speciesName: 'Snow Leopard'         // My.SnowLeopard.speciesName = 'Snow Leopard'
4340         }
4341     });
4342
4343     var cat = new My.Cat();                     // alerts 'Cat'
4344     var snowLeopard = new My.SnowLeopard();     // alerts 'Snow Leopard'
4345
4346     var clone = snowLeopard.clone();
4347     alert(Ext.getClassName(clone));             // alerts 'My.SnowLeopard'
4348
4349          * @type Class
4350          * @protected
4351          * @markdown
4352          */
4353         self: Base,
4354
4355         /**
4356          * Default constructor, simply returns `this`
4357          *
4358          * @constructor
4359          * @protected
4360          * @return {Object} this
4361          */
4362         constructor: function() {
4363             return this;
4364         },
4365
4366         /**
4367          * Initialize configuration for this class. a typical example:
4368
4369     Ext.define('My.awesome.Class', {
4370         // The default config
4371         config: {
4372             name: 'Awesome',
4373             isAwesome: true
4374         },
4375
4376         constructor: function(config) {
4377             this.initConfig(config);
4378
4379             return this;
4380         }
4381     });
4382
4383     var awesome = new My.awesome.Class({
4384         name: 'Super Awesome'
4385     });
4386
4387     alert(awesome.getName()); // 'Super Awesome'
4388
4389          * @protected
4390          * @param {Object} config
4391          * @return {Object} mixins The mixin prototypes as key - value pairs
4392          * @markdown
4393          */
4394         initConfig: function(config) {
4395             if (!this.$configInited) {
4396                 this.config = Ext.Object.merge({}, this.config || {}, config || {});
4397
4398                 this.applyConfig(this.config);
4399
4400                 this.$configInited = true;
4401             }
4402
4403             return this;
4404         },
4405
4406         /**
4407          * @private
4408          */
4409         setConfig: function(config) {
4410             this.applyConfig(config || {});
4411
4412             return this;
4413         },
4414
4415         /**
4416          * @private
4417          */
4418         applyConfig: flexSetter(function(name, value) {
4419             var setter = 'set' + Ext.String.capitalize(name);
4420
4421             if (typeof this[setter] === 'function') {
4422                 this[setter].call(this, value);
4423             }
4424
4425             return this;
4426         }),
4427
4428         /**
4429          * Call the parent's overridden method. For example:
4430
4431     Ext.define('My.own.A', {
4432         constructor: function(test) {
4433             alert(test);
4434         }
4435     });
4436
4437     Ext.define('My.own.B', {
4438         extend: 'My.own.A',
4439
4440         constructor: function(test) {
4441             alert(test);
4442
4443             this.callParent([test + 1]);
4444         }
4445     });
4446
4447     Ext.define('My.own.C', {
4448         extend: 'My.own.B',
4449
4450         constructor: function() {
4451             alert("Going to call parent's overriden constructor...");
4452
4453             this.callParent(arguments);
4454         }
4455     });
4456
4457     var a = new My.own.A(1); // alerts '1'
4458     var b = new My.own.B(1); // alerts '1', then alerts '2'
4459     var c = new My.own.C(2); // alerts "Going to call parent's overriden constructor..."
4460                              // alerts '2', then alerts '3'
4461
4462          * @protected
4463          * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
4464          * from the current method, for example: `this.callParent(arguments)`
4465          * @return {Mixed} Returns the result from the superclass' method
4466          * @markdown
4467          */
4468         callParent: function(args) {
4469             var method = this.callParent.caller,
4470                 parentClass, methodName;
4471
4472             if (!method.$owner) {
4473                 if (!method.caller) {
4474                     Ext.Error.raise({
4475                         sourceClass: Ext.getClassName(this),
4476                         sourceMethod: "callParent",
4477                         msg: "Attempting to call a protected method from the public scope, which is not allowed"
4478                     });
4479                 }
4480
4481                 method = method.caller;
4482             }
4483
4484             parentClass = method.$owner.superclass;
4485             methodName = method.$name;
4486
4487             if (!(methodName in parentClass)) {
4488                 Ext.Error.raise({
4489                     sourceClass: Ext.getClassName(this),
4490                     sourceMethod: methodName,
4491                     msg: "this.callParent() was called but there's no such method (" + methodName +
4492                          ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")"
4493                  });
4494             }
4495
4496             return parentClass[methodName].apply(this, args || []);
4497         },
4498
4499
4500         /**
4501          * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
4502          * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
4503          * `this` points to during run-time
4504
4505     Ext.define('My.Cat', {
4506         statics: {
4507             totalCreated: 0,
4508             speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
4509         },
4510
4511         constructor: function() {
4512             var statics = this.statics();
4513
4514             alert(statics.speciesName);     // always equals to 'Cat' no matter what 'this' refers to
4515                                             // equivalent to: My.Cat.speciesName
4516
4517             alert(this.self.speciesName);   // dependent on 'this'
4518
4519             statics.totalCreated++;
4520
4521             return this;
4522         },
4523
4524         clone: function() {
4525             var cloned = new this.self;                      // dependent on 'this'
4526
4527             cloned.groupName = this.statics().speciesName;   // equivalent to: My.Cat.speciesName
4528
4529             return cloned;
4530         }
4531     });
4532
4533
4534     Ext.define('My.SnowLeopard', {
4535         extend: 'My.Cat',
4536
4537         statics: {
4538             speciesName: 'Snow Leopard'     // My.SnowLeopard.speciesName = 'Snow Leopard'
4539         },
4540
4541         constructor: function() {
4542             this.callParent();
4543         }
4544     });
4545
4546     var cat = new My.Cat();                 // alerts 'Cat', then alerts 'Cat'
4547
4548     var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
4549
4550     var clone = snowLeopard.clone();
4551     alert(Ext.getClassName(clone));         // alerts 'My.SnowLeopard'
4552     alert(clone.groupName);                 // alerts 'Cat'
4553
4554     alert(My.Cat.totalCreated);             // alerts 3
4555
4556          * @protected
4557          * @return {Class}
4558          * @markdown
4559          */
4560         statics: function() {
4561             var method = this.statics.caller,
4562                 self = this.self;
4563
4564             if (!method) {
4565                 return self;
4566             }
4567
4568             return method.$owner;
4569         },
4570
4571         /**
4572          * Call the original method that was previously overridden with {@link Ext.Base#override}
4573
4574     Ext.define('My.Cat', {
4575         constructor: function() {
4576             alert("I'm a cat!");
4577
4578             return this;
4579         }
4580     });
4581
4582     My.Cat.override({
4583         constructor: function() {
4584             alert("I'm going to be a cat!");
4585
4586             var instance = this.callOverridden();
4587
4588             alert("Meeeeoooowwww");
4589
4590             return instance;
4591         }
4592     });
4593
4594     var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
4595                               // alerts "I'm a cat!"
4596                               // alerts "Meeeeoooowwww"
4597
4598          * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
4599          * @return {Mixed} Returns the result after calling the overridden method
4600          * @markdown
4601          */
4602         callOverridden: function(args) {
4603             var method = this.callOverridden.caller;
4604
4605             if (!method.$owner) {
4606                 Ext.Error.raise({
4607                     sourceClass: Ext.getClassName(this),
4608                     sourceMethod: "callOverridden",
4609                     msg: "Attempting to call a protected method from the public scope, which is not allowed"
4610                 });
4611             }
4612
4613             if (!method.$previous) {
4614                 Ext.Error.raise({
4615                     sourceClass: Ext.getClassName(this),
4616                     sourceMethod: "callOverridden",
4617                     msg: "this.callOverridden was called in '" + method.$name +
4618                          "' but this method has never been overridden"
4619                  });
4620             }
4621
4622             return method.$previous.apply(this, args || []);
4623         },
4624
4625         destroy: function() {}
4626     };
4627
4628     // These static properties will be copied to every newly created class with {@link Ext#define}
4629     Ext.apply(Ext.Base, {
4630         /**
4631          * Create a new instance of this Class.
4632 Ext.define('My.cool.Class', {
4633     ...
4634 });
4635
4636 My.cool.Class.create({
4637     someConfig: true
4638 });
4639          * @property create
4640          * @static
4641          * @type Function
4642          * @markdown
4643          */
4644         create: function() {
4645             return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
4646         },
4647
4648         /**
4649          * @private
4650          */
4651         own: flexSetter(function(name, value) {
4652             if (typeof value === 'function') {
4653                 this.ownMethod(name, value);
4654             }
4655             else {
4656                 this.prototype[name] = value;
4657             }
4658         }),
4659
4660         /**
4661          * @private
4662          */
4663         ownMethod: function(name, fn) {
4664             var originalFn;
4665
4666             if (fn.$owner !== undefined && fn !== Ext.emptyFn) {
4667                 originalFn = fn;
4668
4669                 fn = function() {
4670                     return originalFn.apply(this, arguments);
4671                 };
4672             }
4673
4674             var className;
4675             className = Ext.getClassName(this);
4676             if (className) {
4677                 fn.displayName = className + '#' + name;
4678             }
4679             fn.$owner = this;
4680             fn.$name = name;
4681
4682             this.prototype[name] = fn;
4683         },
4684
4685         /**
4686          * Add / override static properties of this class.
4687
4688     Ext.define('My.cool.Class', {
4689         ...
4690     });
4691
4692     My.cool.Class.addStatics({
4693         someProperty: 'someValue',      // My.cool.Class.someProperty = 'someValue'
4694         method1: function() { ... },    // My.cool.Class.method1 = function() { ... };
4695         method2: function() { ... }     // My.cool.Class.method2 = function() { ... };
4696     });
4697
4698          * @property addStatics
4699          * @static
4700          * @type Function
4701          * @param {Object} members
4702          * @markdown
4703          */
4704         addStatics: function(members) {
4705             for (var name in members) {
4706                 if (members.hasOwnProperty(name)) {
4707                     this[name] = members[name];
4708                 }
4709             }
4710
4711             return this;
4712         },
4713
4714         /**
4715          * Add methods / properties to the prototype of this class.
4716
4717     Ext.define('My.awesome.Cat', {
4718         constructor: function() {
4719             ...
4720         }
4721     });
4722
4723      My.awesome.Cat.implement({
4724          meow: function() {
4725             alert('Meowww...');
4726          }
4727      });
4728
4729      var kitty = new My.awesome.Cat;
4730      kitty.meow();
4731
4732          * @property implement
4733          * @static
4734          * @type Function
4735          * @param {Object} members
4736          * @markdown
4737          */
4738         implement: function(members) {
4739             var prototype = this.prototype,
4740                 name, i, member, previous;
4741             var className = Ext.getClassName(this);
4742             for (name in members) {
4743                 if (members.hasOwnProperty(name)) {
4744                     member = members[name];
4745
4746                     if (typeof member === 'function') {
4747                         member.$owner = this;
4748                         member.$name = name;
4749                         if (className) {
4750                             member.displayName = className + '#' + name;
4751                         }
4752                     }
4753
4754                     prototype[name] = member;
4755                 }
4756             }
4757
4758             if (Ext.enumerables) {
4759                 var enumerables = Ext.enumerables;
4760
4761                 for (i = enumerables.length; i--;) {
4762                     name = enumerables[i];
4763
4764                     if (members.hasOwnProperty(name)) {
4765                         member = members[name];
4766                         member.$owner = this;
4767                         member.$name = name;
4768                         prototype[name] = member;
4769                     }
4770                 }
4771             }
4772         },
4773
4774         /**
4775          * Borrow another class' members to the prototype of this class.
4776
4777 Ext.define('Bank', {
4778     money: '$$$',
4779     printMoney: function() {
4780         alert('$$$$$$$');
4781     }
4782 });
4783
4784 Ext.define('Thief', {
4785     ...
4786 });
4787
4788 Thief.borrow(Bank, ['money', 'printMoney']);
4789
4790 var steve = new Thief();
4791
4792 alert(steve.money); // alerts '$$$'
4793 steve.printMoney(); // alerts '$$$$$$$'
4794
4795          * @property borrow
4796          * @static
4797          * @type Function
4798          * @param {Ext.Base} fromClass The class to borrow members from
4799          * @param {Array/String} members The names of the members to borrow
4800          * @return {Ext.Base} this
4801          * @markdown
4802          */
4803         borrow: function(fromClass, members) {
4804             var fromPrototype = fromClass.prototype,
4805                 i, ln, member;
4806
4807             members = Ext.Array.from(members);
4808
4809             for (i = 0, ln = members.length; i < ln; i++) {
4810                 member = members[i];
4811
4812                 this.own(member, fromPrototype[member]);
4813             }
4814
4815             return this;
4816         },
4817
4818         /**
4819          * Override prototype members of this class. Overridden methods can be invoked via
4820          * {@link Ext.Base#callOverridden}
4821
4822     Ext.define('My.Cat', {
4823         constructor: function() {
4824             alert("I'm a cat!");
4825
4826             return this;
4827         }
4828     });
4829
4830     My.Cat.override({
4831         constructor: function() {
4832             alert("I'm going to be a cat!");
4833
4834             var instance = this.callOverridden();
4835
4836             alert("Meeeeoooowwww");
4837
4838             return instance;
4839         }
4840     });
4841
4842     var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
4843                               // alerts "I'm a cat!"
4844                               // alerts "Meeeeoooowwww"
4845
4846          * @property override
4847          * @static
4848          * @type Function
4849          * @param {Object} members
4850          * @return {Ext.Base} this
4851          * @markdown
4852          */
4853         override: function(members) {
4854             var prototype = this.prototype,
4855                 name, i, member, previous;
4856
4857             for (name in members) {
4858                 if (members.hasOwnProperty(name)) {
4859                     member = members[name];
4860
4861                     if (typeof member === 'function') {
4862                         if (typeof prototype[name] === 'function') {
4863                             previous = prototype[name];
4864                             member.$previous = previous;
4865                         }
4866
4867                         this.ownMethod(name, member);
4868                     }
4869                     else {
4870                         prototype[name] = member;
4871                     }
4872                 }
4873             }
4874
4875             if (Ext.enumerables) {
4876                 var enumerables = Ext.enumerables;
4877
4878                 for (i = enumerables.length; i--;) {
4879                     name = enumerables[i];
4880
4881                     if (members.hasOwnProperty(name)) {
4882                         if (prototype[name] !== undefined) {
4883                             previous = prototype[name];
4884                             members[name].$previous = previous;
4885                         }
4886
4887                         this.ownMethod(name, members[name]);
4888                     }
4889                 }
4890             }
4891
4892             return this;
4893         },
4894
4895         /**
4896          * Used internally by the mixins pre-processor
4897          * @private
4898          */
4899         mixin: flexSetter(function(name, cls) {
4900             var mixin = cls.prototype,
4901                 my = this.prototype,
4902                 i, fn;
4903
4904             for (i in mixin) {
4905                 if (mixin.hasOwnProperty(i)) {
4906                     if (my[i] === undefined) {
4907                         if (typeof mixin[i] === 'function') {
4908                             fn = mixin[i];
4909
4910                             if (fn.$owner === undefined) {
4911                                 this.ownMethod(i, fn);
4912                             }
4913                             else {
4914                                 my[i] = fn;
4915                             }
4916                         }
4917                         else {
4918                             my[i] = mixin[i];
4919                         }
4920                     }
4921                     else if (i === 'config' && my.config && mixin.config) {
4922                         Ext.Object.merge(my.config, mixin.config);
4923                     }
4924                 }
4925             }
4926
4927             if (my.mixins === undefined) {
4928                 my.mixins = {};
4929             }
4930
4931             my.mixins[name] = mixin;
4932         }),
4933
4934         /**
4935          * Get the current class' name in string format.
4936
4937     Ext.define('My.cool.Class', {
4938         constructor: function() {
4939             alert(this.self.getName()); // alerts 'My.cool.Class'
4940         }
4941     });
4942
4943     My.cool.Class.getName(); // 'My.cool.Class'
4944
4945          * @return {String} className
4946          * @markdown
4947          */
4948         getName: function() {
4949             return Ext.getClassName(this);
4950         },
4951
4952         /**
4953          * Create aliases for existing prototype methods. Example:
4954
4955     Ext.define('My.cool.Class', {
4956         method1: function() { ... },
4957         method2: function() { ... }
4958     });
4959
4960     var test = new My.cool.Class();
4961
4962     My.cool.Class.createAlias({
4963         method3: 'method1',
4964         method4: 'method2'
4965     });
4966
4967     test.method3(); // test.method1()
4968
4969     My.cool.Class.createAlias('method5', 'method3');
4970
4971     test.method5(); // test.method3() -> test.method1()
4972
4973          * @property createAlias
4974          * @static
4975          * @type Function
4976          * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
4977          * {@link Ext.Function#flexSetter flexSetter}
4978          * @param {String/Object} origin The original method name
4979          * @markdown
4980          */
4981         createAlias: flexSetter(function(alias, origin) {
4982             this.prototype[alias] = this.prototype[origin];
4983         })
4984     });
4985
4986 })(Ext.Function.flexSetter);
4987
4988 /**
4989  * @author Jacky Nguyen <jacky@sencha.com>
4990  * @docauthor Jacky Nguyen <jacky@sencha.com>
4991  * @class Ext.Class
4992  * 
4993  * Handles class creation throughout the whole framework. Note that most of the time {@link Ext#define Ext.define} should
4994  * be used instead, since it's a higher level wrapper that aliases to {@link Ext.ClassManager#create}
4995  * to enable namespacing and dynamic dependency resolution.
4996  * 
4997  * # Basic syntax: #
4998  * 
4999  *     Ext.define(className, properties);
5000  * 
5001  * in which `properties` is an object represent a collection of properties that apply to the class. See
5002  * {@link Ext.ClassManager#create} for more detailed instructions.
5003  * 
5004  *     Ext.define('Person', {
5005  *          name: 'Unknown',
5006  * 
5007  *          constructor: function(name) {
5008  *              if (name) {
5009  *                  this.name = name;
5010  *              }
5011  * 
5012  *              return this;
5013  *          },
5014  * 
5015  *          eat: function(foodType) {
5016  *              alert("I'm eating: " + foodType);
5017  * 
5018  *              return this;
5019  *          }
5020  *     });
5021  * 
5022  *     var aaron = new Person("Aaron");
5023  *     aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
5024  * 
5025  * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
5026  * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
5027  * 
5028  * # Inheritance: #
5029  * 
5030  *     Ext.define('Developer', {
5031  *          extend: 'Person',
5032  * 
5033  *          constructor: function(name, isGeek) {
5034  *              this.isGeek = isGeek;
5035  * 
5036  *              // Apply a method from the parent class' prototype
5037  *              this.callParent([name]);
5038  * 
5039  *              return this;
5040  * 
5041  *          },
5042  * 
5043  *          code: function(language) {
5044  *              alert("I'm coding in: " + language);
5045  * 
5046  *              this.eat("Bugs");
5047  * 
5048  *              return this;
5049  *          }
5050  *     });
5051  * 
5052  *     var jacky = new Developer("Jacky", true);
5053  *     jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
5054  *                               // alert("I'm eating: Bugs");
5055  * 
5056  * See {@link Ext.Base#callParent} for more details on calling superclass' methods
5057  * 
5058  * # Mixins: #
5059  * 
5060  *     Ext.define('CanPlayGuitar', {
5061  *          playGuitar: function() {
5062  *             alert("F#...G...D...A");
5063  *          }
5064  *     });
5065  * 
5066  *     Ext.define('CanComposeSongs', {
5067  *          composeSongs: function() { ... }
5068  *     });
5069  * 
5070  *     Ext.define('CanSing', {
5071  *          sing: function() {
5072  *              alert("I'm on the highway to hell...")
5073  *          }
5074  *     });
5075  * 
5076  *     Ext.define('Musician', {
5077  *          extend: 'Person',
5078  * 
5079  *          mixins: {
5080  *              canPlayGuitar: 'CanPlayGuitar',
5081  *              canComposeSongs: 'CanComposeSongs',
5082  *              canSing: 'CanSing'
5083  *          }
5084  *     })
5085  * 
5086  *     Ext.define('CoolPerson', {
5087  *          extend: 'Person',
5088  * 
5089  *          mixins: {
5090  *              canPlayGuitar: 'CanPlayGuitar',
5091  *              canSing: 'CanSing'
5092  *          },
5093  * 
5094  *          sing: function() {
5095  *              alert("Ahem....");
5096  * 
5097  *              this.mixins.canSing.sing.call(this);
5098  * 
5099  *              alert("[Playing guitar at the same time...]");
5100  * 
5101  *              this.playGuitar();
5102  *          }
5103  *     });
5104  * 
5105  *     var me = new CoolPerson("Jacky");
5106  * 
5107  *     me.sing(); // alert("Ahem...");
5108  *                // alert("I'm on the highway to hell...");
5109  *                // alert("[Playing guitar at the same time...]");
5110  *                // alert("F#...G...D...A");
5111  * 
5112  * # Config: #
5113  * 
5114  *     Ext.define('SmartPhone', {
5115  *          config: {
5116  *              hasTouchScreen: false,
5117  *              operatingSystem: 'Other',
5118  *              price: 500
5119  *          },
5120  * 
5121  *          isExpensive: false,
5122  * 
5123  *          constructor: function(config) {
5124  *              this.initConfig(config);
5125  * 
5126  *              return this;
5127  *          },
5128  * 
5129  *          applyPrice: function(price) {
5130  *              this.isExpensive = (price > 500);
5131  * 
5132  *              return price;
5133  *          },
5134  * 
5135  *          applyOperatingSystem: function(operatingSystem) {
5136  *              if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
5137  *                  return 'Other';
5138  *              }
5139  * 
5140  *              return operatingSystem;
5141  *          }
5142  *     });
5143  * 
5144  *     var iPhone = new SmartPhone({
5145  *          hasTouchScreen: true,
5146  *          operatingSystem: 'iOS'
5147  *     });
5148  * 
5149  *     iPhone.getPrice(); // 500;
5150  *     iPhone.getOperatingSystem(); // 'iOS'
5151  *     iPhone.getHasTouchScreen(); // true;
5152  *     iPhone.hasTouchScreen(); // true
5153  * 
5154  *     iPhone.isExpensive; // false;
5155  *     iPhone.setPrice(600);
5156  *     iPhone.getPrice(); // 600
5157  *     iPhone.isExpensive; // true;
5158  * 
5159  *     iPhone.setOperatingSystem('AlienOS');
5160  *     iPhone.getOperatingSystem(); // 'Other'
5161  * 
5162  * # Statics: #
5163  * 
5164  *     Ext.define('Computer', {
5165  *          statics: {
5166  *              factory: function(brand) {
5167  *                 // 'this' in static methods refer to the class itself
5168  *                  return new this(brand);
5169  *              }
5170  *          },
5171  * 
5172  *          constructor: function() { ... }
5173  *     });
5174  * 
5175  *     var dellComputer = Computer.factory('Dell');
5176  * 
5177  * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
5178  * static properties within class methods
5179  *
5180  */
5181 (function() {
5182
5183     var Class,
5184         Base = Ext.Base,
5185         baseStaticProperties = [],
5186         baseStaticProperty;
5187
5188     for (baseStaticProperty in Base) {
5189         if (Base.hasOwnProperty(baseStaticProperty)) {
5190             baseStaticProperties.push(baseStaticProperty);
5191         }
5192     }
5193
5194     /**
5195      * @constructor
5196      * @param {Object} classData An object represent the properties of this class
5197      * @param {Function} createdFn Optional, the callback function to be executed when this class is fully created.
5198      * Note that the creation process can be asynchronous depending on the pre-processors used.
5199      * @return {Ext.Base} The newly created class
5200      */
5201     Ext.Class = Class = function(newClass, classData, onClassCreated) {
5202         if (typeof newClass !== 'function') {
5203             onClassCreated = classData;
5204             classData = newClass;
5205             newClass = function() {
5206                 return this.constructor.apply(this, arguments);
5207             };
5208         }
5209
5210         if (!classData) {
5211             classData = {};
5212         }
5213
5214         var preprocessorStack = classData.preprocessors || Class.getDefaultPreprocessors(),
5215             registeredPreprocessors = Class.getPreprocessors(),
5216             index = 0,
5217             preprocessors = [],
5218             preprocessor, preprocessors, staticPropertyName, process, i, j, ln;
5219
5220         for (i = 0, ln = baseStaticProperties.length; i < ln; i++) {
5221             staticPropertyName = baseStaticProperties[i];
5222             newClass[staticPropertyName] = Base[staticPropertyName];
5223         }
5224
5225         delete classData.preprocessors;
5226
5227         for (j = 0, ln = preprocessorStack.length; j < ln; j++) {
5228             preprocessor = preprocessorStack[j];
5229
5230             if (typeof preprocessor === 'string') {
5231                 preprocessor = registeredPreprocessors[preprocessor];
5232
5233                 if (!preprocessor.always) {
5234                     if (classData.hasOwnProperty(preprocessor.name)) {
5235                         preprocessors.push(preprocessor.fn);
5236                     }
5237                 }
5238                 else {
5239                     preprocessors.push(preprocessor.fn);
5240                 }
5241             }
5242             else {
5243                 preprocessors.push(preprocessor);
5244             }
5245         }
5246
5247         classData.onClassCreated = onClassCreated;
5248
5249         classData.onBeforeClassCreated = function(cls, data) {
5250             onClassCreated = data.onClassCreated;
5251
5252             delete data.onBeforeClassCreated;
5253             delete data.onClassCreated;
5254
5255             cls.implement(data);
5256
5257             if (onClassCreated) {
5258                 onClassCreated.call(cls, cls);
5259             }
5260         };
5261
5262         process = function(cls, data) {
5263             preprocessor = preprocessors[index++];
5264
5265             if (!preprocessor) {
5266                 data.onBeforeClassCreated.apply(this, arguments);
5267                 return;
5268             }
5269
5270             if (preprocessor.call(this, cls, data, process) !== false) {
5271                 process.apply(this, arguments);
5272             }
5273         };
5274
5275         process.call(Class, newClass, classData);
5276
5277         return newClass;
5278     };
5279
5280     Ext.apply(Class, {
5281
5282         /** @private */
5283         preprocessors: {},
5284
5285         /**
5286          * Register a new pre-processor to be used during the class creation process
5287          *
5288          * @member Ext.Class registerPreprocessor
5289          * @param {String} name The pre-processor's name
5290          * @param {Function} fn The callback function to be executed. Typical format:
5291
5292     function(cls, data, fn) {
5293         // Your code here
5294
5295         // Execute this when the processing is finished.
5296         // Asynchronous processing is perfectly ok
5297         if (fn) {
5298             fn.call(this, cls, data);
5299         }
5300     });
5301
5302          * Passed arguments for this function are:
5303          *
5304          * - `{Function} cls`: The created class
5305          * - `{Object} data`: The set of properties passed in {@link Ext.Class} constructor
5306          * - `{Function} fn`: The callback function that <b>must</b> to be executed when this pre-processor finishes,
5307          * regardless of whether the processing is synchronous or aynchronous
5308          *
5309          * @return {Ext.Class} this
5310          * @markdown
5311          */
5312         registerPreprocessor: function(name, fn, always) {
5313             this.preprocessors[name] = {
5314                 name: name,
5315                 always: always ||  false,
5316                 fn: fn
5317             };
5318
5319             return this;
5320         },
5321
5322         /**
5323          * Retrieve a pre-processor callback function by its name, which has been registered before
5324          *
5325          * @param {String} name
5326          * @return {Function} preprocessor
5327          */
5328         getPreprocessor: function(name) {
5329             return this.preprocessors[name];
5330         },
5331
5332         getPreprocessors: function() {
5333             return this.preprocessors;
5334         },
5335
5336         /**
5337          * Retrieve the array stack of default pre-processors
5338          *
5339          * @return {Function} defaultPreprocessors
5340          */
5341         getDefaultPreprocessors: function() {
5342             return this.defaultPreprocessors || [];
5343         },
5344
5345         /**
5346          * Set the default array stack of default pre-processors
5347          *
5348          * @param {Array} preprocessors
5349          * @return {Ext.Class} this
5350          */
5351         setDefaultPreprocessors: function(preprocessors) {
5352             this.defaultPreprocessors = Ext.Array.from(preprocessors);
5353
5354             return this;
5355         },
5356
5357         /**
5358          * Insert this pre-processor at a specific position in the stack, optionally relative to
5359          * any existing pre-processor. For example:
5360
5361     Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
5362         // Your code here
5363
5364         if (fn) {
5365             fn.call(this, cls, data);
5366         }
5367     }).insertDefaultPreprocessor('debug', 'last');
5368
5369          * @param {String} name The pre-processor name. Note that it needs to be registered with
5370          * {@link Ext#registerPreprocessor registerPreprocessor} before this
5371          * @param {String} offset The insertion position. Four possible values are:
5372          * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
5373          * @param {String} relativeName
5374          * @return {Ext.Class} this
5375          * @markdown
5376          */
5377         setDefaultPreprocessorPosition: function(name, offset, relativeName) {
5378             var defaultPreprocessors = this.defaultPreprocessors,
5379                 index;
5380
5381             if (typeof offset === 'string') {
5382                 if (offset === 'first') {
5383                     defaultPreprocessors.unshift(name);
5384
5385                     return this;
5386                 }
5387                 else if (offset === 'last') {
5388                     defaultPreprocessors.push(name);
5389
5390                     return this;
5391                 }
5392
5393                 offset = (offset === 'after') ? 1 : -1;
5394             }
5395
5396             index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
5397
5398             if (index !== -1) {
5399                 defaultPreprocessors.splice(Math.max(0, index + offset), 0, name);
5400             }
5401
5402             return this;
5403         }
5404     });
5405
5406     Class.registerPreprocessor('extend', function(cls, data) {
5407         var extend = data.extend,
5408             base = Ext.Base,
5409             basePrototype = base.prototype,
5410             prototype = function() {},
5411             parent, i, k, ln, staticName, parentStatics,
5412             parentPrototype, clsPrototype;
5413
5414         if (extend && extend !== Object) {
5415             parent = extend;
5416         }
5417         else {
5418             parent = base;
5419         }
5420
5421         parentPrototype = parent.prototype;
5422
5423         prototype.prototype = parentPrototype;
5424         clsPrototype = cls.prototype = new prototype();
5425
5426         if (!('$class' in parent)) {
5427             for (i in basePrototype) {
5428                 if (!parentPrototype[i]) {
5429                     parentPrototype[i] = basePrototype[i];
5430                 }
5431             }
5432         }
5433
5434         clsPrototype.self = cls;
5435
5436         cls.superclass = clsPrototype.superclass = parentPrototype;
5437
5438         delete data.extend;
5439
5440         // Statics inheritance
5441         parentStatics = parentPrototype.$inheritableStatics;
5442
5443         if (parentStatics) {
5444             for (k = 0, ln = parentStatics.length; k < ln; k++) {
5445                 staticName = parentStatics[k];
5446
5447                 if (!cls.hasOwnProperty(staticName)) {
5448                     cls[staticName] = parent[staticName];
5449                 }
5450             }
5451         }
5452
5453         // Merge the parent class' config object without referencing it
5454         if (parentPrototype.config) {
5455             clsPrototype.config = Ext.Object.merge({}, parentPrototype.config);
5456         }
5457         else {
5458             clsPrototype.config = {};
5459         }
5460
5461         if (clsPrototype.$onExtended) {
5462             clsPrototype.$onExtended.call(cls, cls, data);
5463         }
5464
5465         if (data.onClassExtended) {
5466             clsPrototype.$onExtended = data.onClassExtended;
5467             delete data.onClassExtended;
5468         }
5469
5470     }, true);
5471
5472     Class.registerPreprocessor('statics', function(cls, data) {
5473         var statics = data.statics,
5474             name;
5475
5476         for (name in statics) {
5477             if (statics.hasOwnProperty(name)) {
5478                 cls[name] = statics[name];
5479             }
5480         }
5481
5482         delete data.statics;
5483     });
5484
5485     Class.registerPreprocessor('inheritableStatics', function(cls, data) {
5486         var statics = data.inheritableStatics,
5487             inheritableStatics,
5488             prototype = cls.prototype,
5489             name;
5490
5491         inheritableStatics = prototype.$inheritableStatics;
5492
5493         if (!inheritableStatics) {
5494             inheritableStatics = prototype.$inheritableStatics = [];
5495         }
5496
5497         for (name in statics) {
5498             if (statics.hasOwnProperty(name)) {
5499                 cls[name] = statics[name];
5500                 inheritableStatics.push(name);
5501             }
5502         }
5503
5504         delete data.inheritableStatics;
5505     });
5506
5507     Class.registerPreprocessor('mixins', function(cls, data) {
5508         cls.mixin(data.mixins);
5509
5510         delete data.mixins;
5511     });
5512
5513     Class.registerPreprocessor('config', function(cls, data) {
5514         var prototype = cls.prototype;
5515
5516         Ext.Object.each(data.config, function(name) {
5517             var cName = name.charAt(0).toUpperCase() + name.substr(1),
5518                 pName = name,
5519                 apply = 'apply' + cName,
5520                 setter = 'set' + cName,
5521                 getter = 'get' + cName;
5522
5523             if (!(apply in prototype) && !data.hasOwnProperty(apply)) {
5524                 data[apply] = function(val) {
5525                     return val;
5526                 };
5527             }
5528
5529             if (!(setter in prototype) && !data.hasOwnProperty(setter)) {
5530                 data[setter] = function(val) {
5531                     var ret = this[apply].call(this, val, this[pName]);
5532
5533                     if (ret !== undefined) {
5534                         this[pName] = ret;
5535                     }
5536
5537                     return this;
5538                 };
5539             }
5540
5541             if (!(getter in prototype) && !data.hasOwnProperty(getter)) {
5542                 data[getter] = function() {
5543                     return this[pName];
5544                 };
5545             }
5546         });
5547
5548         Ext.Object.merge(prototype.config, data.config);
5549         delete data.config;
5550     });
5551
5552     Class.setDefaultPreprocessors(['extend', 'statics', 'inheritableStatics', 'mixins', 'config']);
5553
5554     // Backwards compatible
5555     Ext.extend = function(subclass, superclass, members) {
5556         if (arguments.length === 2 && Ext.isObject(superclass)) {
5557             members = superclass;
5558             superclass = subclass;
5559             subclass = null;
5560         }
5561
5562         var cls;
5563
5564         if (!superclass) {
5565             Ext.Error.raise("Attempting to extend from a class which has not been loaded on the page.");
5566         }
5567
5568         members.extend = superclass;
5569         members.preprocessors = ['extend', 'mixins', 'config', 'statics'];
5570
5571         if (subclass) {
5572             cls = new Class(subclass, members);
5573         }
5574         else {
5575             cls = new Class(members);
5576         }
5577
5578         cls.prototype.override = function(o) {
5579             for (var m in o) {
5580                 if (o.hasOwnProperty(m)) {
5581                     this[m] = o[m];
5582                 }
5583             }
5584         };
5585
5586         return cls;
5587     };
5588
5589 })();
5590
5591 /**
5592  * @author Jacky Nguyen <jacky@sencha.com>
5593  * @docauthor Jacky Nguyen <jacky@sencha.com>
5594  * @class Ext.ClassManager
5595
5596 Ext.ClassManager manages all classes and handles mapping from string class name to
5597 actual class objects throughout the whole framework. It is not generally accessed directly, rather through
5598 these convenient shorthands:
5599
5600 - {@link Ext#define Ext.define}
5601 - {@link Ext#create Ext.create}
5602 - {@link Ext#widget Ext.widget}
5603 - {@link Ext#getClass Ext.getClass}
5604 - {@link Ext#getClassName Ext.getClassName}
5605
5606  * @singleton
5607  * @markdown
5608  */
5609 (function(Class, alias) {
5610
5611     var slice = Array.prototype.slice;
5612
5613     var Manager = Ext.ClassManager = {
5614
5615         /**
5616          * @property classes
5617          * @type Object
5618          * All classes which were defined through the ClassManager. Keys are the
5619          * name of the classes and the values are references to the classes.
5620          * @private
5621          */
5622         classes: {},
5623
5624         /**
5625          * @private
5626          */
5627         existCache: {},
5628
5629         /**
5630          * @private
5631          */
5632         namespaceRewrites: [{
5633             from: 'Ext.',
5634             to: Ext
5635         }],
5636
5637         /**
5638          * @private
5639          */
5640         maps: {
5641             alternateToName: {},
5642             aliasToName: {},
5643             nameToAliases: {}
5644         },
5645
5646         /** @private */
5647         enableNamespaceParseCache: true,
5648
5649         /** @private */
5650         namespaceParseCache: {},
5651
5652         /** @private */
5653         instantiators: [],
5654
5655         /** @private */
5656         instantiationCounts: {},
5657
5658         /**
5659          * Checks if a class has already been created.
5660          *
5661          * @param {String} className
5662          * @return {Boolean} exist
5663          */
5664         isCreated: function(className) {
5665             var i, ln, part, root, parts;
5666
5667             if (typeof className !== 'string' || className.length < 1) {
5668                 Ext.Error.raise({
5669                     sourceClass: "Ext.ClassManager",
5670                     sourceMethod: "exist",
5671                     msg: "Invalid classname, must be a string and must not be empty"
5672                 });
5673             }
5674
5675             if (this.classes.hasOwnProperty(className) || this.existCache.hasOwnProperty(className)) {
5676                 return true;
5677             }
5678
5679             root = Ext.global;
5680             parts = this.parseNamespace(className);
5681
5682             for (i = 0, ln = parts.length; i < ln; i++) {
5683                 part = parts[i];
5684
5685                 if (typeof part !== 'string') {
5686                     root = part;
5687                 } else {
5688                     if (!root || !root[part]) {
5689                         return false;
5690                     }
5691
5692                     root = root[part];
5693                 }
5694             }
5695
5696             Ext.Loader.historyPush(className);
5697
5698             this.existCache[className] = true;
5699
5700             return true;
5701         },
5702
5703         /**
5704          * Supports namespace rewriting
5705          * @private
5706          */
5707         parseNamespace: function(namespace) {
5708             if (typeof namespace !== 'string') {
5709                 Ext.Error.raise({
5710                     sourceClass: "Ext.ClassManager",
5711                     sourceMethod: "parseNamespace",
5712                     msg: "Invalid namespace, must be a string"
5713                 });
5714             }
5715
5716             var cache = this.namespaceParseCache;
5717
5718             if (this.enableNamespaceParseCache) {
5719                 if (cache.hasOwnProperty(namespace)) {
5720                     return cache[namespace];
5721                 }
5722             }
5723
5724             var parts = [],
5725                 rewrites = this.namespaceRewrites,
5726                 rewrite, from, to, i, ln, root = Ext.global;
5727
5728             for (i = 0, ln = rewrites.length; i < ln; i++) {
5729                 rewrite = rewrites[i];
5730                 from = rewrite.from;
5731                 to = rewrite.to;
5732
5733                 if (namespace === from || namespace.substring(0, from.length) === from) {
5734                     namespace = namespace.substring(from.length);
5735
5736                     if (typeof to !== 'string') {
5737                         root = to;
5738                     } else {
5739                         parts = parts.concat(to.split('.'));
5740                     }
5741
5742                     break;
5743                 }
5744             }
5745
5746             parts.push(root);
5747
5748             parts = parts.concat(namespace.split('.'));
5749
5750             if (this.enableNamespaceParseCache) {
5751                 cache[namespace] = parts;
5752             }
5753
5754             return parts;
5755         },
5756
5757         /**
5758          * Creates a namespace and assign the `value` to the created object
5759
5760     Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
5761
5762     alert(MyCompany.pkg.Example === someObject); // alerts true
5763
5764          * @param {String} name
5765          * @param {Mixed} value
5766          * @markdown
5767          */
5768         setNamespace: function(name, value) {
5769             var root = Ext.global,
5770                 parts = this.parseNamespace(name),
5771                 leaf = parts.pop(),
5772                 i, ln, part;
5773
5774             for (i = 0, ln = parts.length; i < ln; i++) {
5775                 part = parts[i];
5776
5777                 if (typeof part !== 'string') {
5778                     root = part;
5779                 } else {
5780                     if (!root[part]) {
5781                         root[part] = {};
5782                     }
5783
5784                     root = root[part];
5785                 }
5786             }
5787
5788             root[leaf] = value;
5789
5790             return root[leaf];
5791         },
5792
5793         /**
5794          * The new Ext.ns, supports namespace rewriting
5795          * @private
5796          */
5797         createNamespaces: function() {
5798             var root = Ext.global,
5799                 parts, part, i, j, ln, subLn;
5800
5801             for (i = 0, ln = arguments.length; i < ln; i++) {
5802                 parts = this.parseNamespace(arguments[i]);
5803
5804                 for (j = 0, subLn = parts.length; j < subLn; j++) {
5805                     part = parts[j];
5806
5807                     if (typeof part !== 'string') {
5808                         root = part;
5809                     } else {
5810                         if (!root[part]) {
5811                             root[part] = {};
5812                         }
5813
5814                         root = root[part];
5815                     }
5816                 }
5817             }
5818
5819             return root;
5820         },
5821
5822         /**
5823          * Sets a name reference to a class.
5824          *
5825          * @param {String} name
5826          * @param {Object} value
5827          * @return {Ext.ClassManager} this
5828          */
5829         set: function(name, value) {
5830             var targetName = this.getName(value);
5831
5832             this.classes[name] = this.setNamespace(name, value);
5833
5834             if (targetName && targetName !== name) {
5835                 this.maps.alternateToName[name] = targetName;
5836             }
5837
5838             return this;
5839         },
5840
5841         /**
5842          * Retrieve a class by its name.
5843          *
5844          * @param {String} name
5845          * @return {Class} class
5846          */
5847         get: function(name) {
5848             if (this.classes.hasOwnProperty(name)) {
5849                 return this.classes[name];
5850             }
5851
5852             var root = Ext.global,
5853                 parts = this.parseNamespace(name),
5854                 part, i, ln;
5855
5856             for (i = 0, ln = parts.length; i < ln; i++) {
5857                 part = parts[i];
5858
5859                 if (typeof part !== 'string') {
5860                     root = part;
5861                 } else {
5862                     if (!root || !root[part]) {
5863                         return null;
5864                     }
5865
5866                     root = root[part];
5867                 }
5868             }
5869
5870             return root;
5871         },
5872
5873         /**
5874          * Register the alias for a class.
5875          *
5876          * @param {Class/String} cls a reference to a class or a className
5877          * @param {String} alias Alias to use when referring to this class
5878          */
5879         setAlias: function(cls, alias) {
5880             var aliasToNameMap = this.maps.aliasToName,
5881                 nameToAliasesMap = this.maps.nameToAliases,
5882                 className;
5883
5884             if (typeof cls === 'string') {
5885                 className = cls;
5886             } else {
5887                 className = this.getName(cls);
5888             }
5889
5890             if (alias && aliasToNameMap[alias] !== className) {
5891                 if (aliasToNameMap.hasOwnProperty(alias) && Ext.isDefined(Ext.global.console)) {
5892                     Ext.global.console.log("[Ext.ClassManager] Overriding existing alias: '" + alias + "' " +
5893                         "of: '" + aliasToNameMap[alias] + "' with: '" + className + "'. Be sure it's intentional.");
5894                 }
5895
5896                 aliasToNameMap[alias] = className;
5897             }
5898
5899             if (!nameToAliasesMap[className]) {
5900                 nameToAliasesMap[className] = [];
5901             }
5902
5903             if (alias) {
5904                 Ext.Array.include(nameToAliasesMap[className], alias);
5905             }
5906
5907             return this;
5908         },
5909
5910         /**
5911          * Get a reference to the class by its alias.
5912          *
5913          * @param {String} alias
5914          * @return {Class} class
5915          */
5916         getByAlias: function(alias) {
5917             return this.get(this.getNameByAlias(alias));
5918         },
5919
5920         /**
5921          * Get the name of a class by its alias.
5922          *
5923          * @param {String} alias
5924          * @return {String} className
5925          */
5926         getNameByAlias: function(alias) {
5927             return this.maps.aliasToName[alias] || '';
5928         },
5929
5930         /**
5931          * Get the name of a class by its alternate name.
5932          *
5933          * @param {String} alternate
5934          * @return {String} className
5935          */
5936         getNameByAlternate: function(alternate) {
5937             return this.maps.alternateToName[alternate] || '';
5938         },
5939
5940         /**
5941          * Get the aliases of a class by the class name
5942          *
5943          * @param {String} name
5944          * @return {Array} aliases
5945          */
5946         getAliasesByName: function(name) {
5947             return this.maps.nameToAliases[name] || [];
5948         },
5949
5950         /**
5951          * Get the name of the class by its reference or its instance;
5952          * usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName}
5953
5954     Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
5955
5956          * @param {Class/Object} object
5957          * @return {String} className
5958          * @markdown
5959          */
5960         getName: function(object) {
5961             return object && object.$className || '';
5962         },
5963
5964         /**
5965          * Get the class of the provided object; returns null if it's not an instance
5966          * of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass}
5967          *
5968     var component = new Ext.Component();
5969
5970     Ext.ClassManager.getClass(component); // returns Ext.Component
5971              *
5972          * @param {Object} object
5973          * @return {Class} class
5974          * @markdown
5975          */
5976         getClass: function(object) {
5977             return object && object.self || null;
5978         },
5979
5980         /**
5981          * Defines a class. This is usually invoked via the alias {@link Ext#define Ext.define}
5982
5983     Ext.ClassManager.create('My.awesome.Class', {
5984         someProperty: 'something',
5985         someMethod: function() { ... }
5986         ...
5987
5988     }, function() {
5989         alert('Created!');
5990         alert(this === My.awesome.Class); // alerts true
5991
5992         var myInstance = new this();
5993     });
5994
5995          * @param {String} className The class name to create in string dot-namespaced format, for example:
5996          * 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager'
5997          * It is highly recommended to follow this simple convention:
5998
5999 - The root and the class name are 'CamelCased'
6000 - Everything else is lower-cased
6001
6002          * @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of any valid
6003          * strings, except those in the reserved listed below:
6004
6005 - `mixins`
6006 - `statics`
6007 - `config`
6008 - `alias`
6009 - `self`
6010 - `singleton`
6011 - `alternateClassName`
6012          *
6013          * @param {Function} createdFn Optional callback to execute after the class is created, the execution scope of which
6014          * (`this`) will be the newly created class itself.
6015          * @return {Ext.Base}
6016          * @markdown
6017          */
6018         create: function(className, data, createdFn) {
6019             var manager = this;
6020
6021             if (typeof className !== 'string') {
6022                 Ext.Error.raise({
6023                     sourceClass: "Ext",
6024                     sourceMethod: "define",
6025                     msg: "Invalid class name '" + className + "' specified, must be a non-empty string"
6026                 });
6027             }
6028
6029             data.$className = className;
6030
6031             return new Class(data, function() {
6032                 var postprocessorStack = data.postprocessors || manager.defaultPostprocessors,
6033                     registeredPostprocessors = manager.postprocessors,
6034                     index = 0,
6035                     postprocessors = [],
6036                     postprocessor, postprocessors, process, i, ln;
6037
6038                 delete data.postprocessors;
6039
6040                 for (i = 0, ln = postprocessorStack.length; i < ln; i++) {
6041                     postprocessor = postprocessorStack[i];
6042
6043                     if (typeof postprocessor === 'string') {
6044                         postprocessor = registeredPostprocessors[postprocessor];
6045
6046                         if (!postprocessor.always) {
6047                             if (data[postprocessor.name] !== undefined) {
6048                                 postprocessors.push(postprocessor.fn);
6049                             }
6050                         }
6051                         else {
6052                             postprocessors.push(postprocessor.fn);
6053                         }
6054                     }
6055                     else {
6056                         postprocessors.push(postprocessor);
6057                     }
6058                 }
6059
6060                 process = function(clsName, cls, clsData) {
6061                     postprocessor = postprocessors[index++];
6062
6063                     if (!postprocessor) {
6064                         manager.set(className, cls);
6065
6066                         Ext.Loader.historyPush(className);
6067
6068                         if (createdFn) {
6069                             createdFn.call(cls, cls);
6070                         }
6071
6072                         return;
6073                     }
6074
6075                     if (postprocessor.call(this, clsName, cls, clsData, process) !== false) {
6076                         process.apply(this, arguments);
6077                     }
6078                 };
6079
6080                 process.call(manager, className, this, data);
6081             });
6082         },
6083
6084         /**
6085          * Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias}
6086          * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
6087          * attempt to load the class via synchronous loading.
6088
6089     var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
6090
6091          * @param {String} alias
6092          * @param {Mixed} args,... Additional arguments after the alias will be passed to the
6093          * class constructor.
6094          * @return {Object} instance
6095          * @markdown
6096          */
6097         instantiateByAlias: function() {
6098             var alias = arguments[0],
6099                 args = slice.call(arguments),
6100                 className = this.getNameByAlias(alias);
6101
6102             if (!className) {
6103                 className = this.maps.aliasToName[alias];
6104
6105                 if (!className) {
6106                     Ext.Error.raise({
6107                         sourceClass: "Ext",
6108                         sourceMethod: "createByAlias",
6109                         msg: "Cannot create an instance of unrecognized alias: " + alias
6110                     });
6111                 }
6112
6113                 if (Ext.global.console) {
6114                     Ext.global.console.warn("[Ext.Loader] Synchronously loading '" + className + "'; consider adding " +
6115                          "Ext.require('" + alias + "') above Ext.onReady");
6116                 }
6117
6118                 Ext.syncRequire(className);
6119             }
6120
6121             args[0] = className;
6122
6123             return this.instantiate.apply(this, args);
6124         },
6125
6126         /**
6127          * Instantiate a class by either full name, alias or alternate name; usually invoked by the convenient
6128          * shorthand {@link Ext#create Ext.create}
6129          *
6130          * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
6131          * attempt to load the class via synchronous loading.
6132          *
6133          * For example, all these three lines return the same result:
6134
6135     // alias
6136     var window = Ext.ClassManager.instantiate('widget.window', { width: 600, height: 800, ... });
6137
6138     // alternate name
6139     var window = Ext.ClassManager.instantiate('Ext.Window', { width: 600, height: 800, ... });
6140
6141     // full class name
6142     var window = Ext.ClassManager.instantiate('Ext.window.Window', { width: 600, height: 800, ... });
6143
6144          * @param {String} name
6145          * @param {Mixed} args,... Additional arguments after the name will be passed to the class' constructor.
6146          * @return {Object} instance
6147          * @markdown
6148          */
6149         instantiate: function() {
6150             var name = arguments[0],
6151                 args = slice.call(arguments, 1),
6152                 alias = name,
6153                 possibleName, cls;
6154
6155             if (typeof name !== 'function') {
6156                 if ((typeof name !== 'string' || name.length < 1)) {
6157                     Ext.Error.raise({
6158                         sourceClass: "Ext",
6159                         sourceMethod: "create",
6160                         msg: "Invalid class name or alias '" + name + "' specified, must be a non-empty string"
6161                     });
6162                 }
6163
6164                 cls = this.get(name);
6165             }
6166             else {
6167                 cls = name;
6168             }
6169
6170             // No record of this class name, it's possibly an alias, so look it up
6171             if (!cls) {
6172                 possibleName = this.getNameByAlias(name);
6173
6174                 if (possibleName) {
6175                     name = possibleName;
6176
6177                     cls = this.get(name);
6178                 }
6179             }
6180
6181             // Still no record of this class name, it's possibly an alternate name, so look it up
6182             if (!cls) {
6183                 possibleName = this.getNameByAlternate(name);
6184
6185                 if (possibleName) {
6186                     name = possibleName;
6187
6188                     cls = this.get(name);
6189                 }
6190             }
6191
6192             // Still not existing at this point, try to load it via synchronous mode as the last resort
6193             if (!cls) {
6194                 if (Ext.global.console) {
6195                     Ext.global.console.warn("[Ext.Loader] Synchronously loading '" + name + "'; consider adding " +
6196                          "Ext.require('" + ((possibleName) ? alias : name) + "') above Ext.onReady");
6197                 }
6198
6199                 Ext.syncRequire(name);
6200
6201                 cls = this.get(name);
6202             }
6203
6204             if (!cls) {
6205                 Ext.Error.raise({
6206                     sourceClass: "Ext",
6207                     sourceMethod: "create",
6208                     msg: "Cannot create an instance of unrecognized class name / alias: " + alias
6209                 });
6210             }
6211
6212             if (typeof cls !== 'function') {
6213                 Ext.Error.raise({
6214                     sourceClass: "Ext",
6215                     sourceMethod: "create",
6216                     msg: "'" + name + "' is a singleton and cannot be instantiated"
6217                 });
6218             }
6219
6220             if (!this.instantiationCounts[name]) {
6221                 this.instantiationCounts[name] = 0;
6222             }
6223
6224             this.instantiationCounts[name]++;
6225
6226             return this.getInstantiator(args.length)(cls, args);
6227         },
6228
6229         /**
6230          * @private
6231          * @param name
6232          * @param args
6233          */
6234         dynInstantiate: function(name, args) {
6235             args = Ext.Array.from(args, true);
6236             args.unshift(name);
6237
6238             return this.instantiate.apply(this, args);
6239         },
6240
6241         /**
6242          * @private
6243          * @param length
6244          */
6245         getInstantiator: function(length) {
6246             if (!this.instantiators[length]) {
6247                 var i = length,
6248                     args = [];
6249
6250                 for (i = 0; i < length; i++) {
6251                     args.push('a['+i+']');
6252                 }
6253
6254                 this.instantiators[length] = new Function('c', 'a', 'return new c('+args.join(',')+')');
6255             }
6256
6257             return this.instantiators[length];
6258         },
6259
6260         /**
6261          * @private
6262          */
6263         postprocessors: {},
6264
6265         /**
6266          * @private
6267          */
6268         defaultPostprocessors: [],
6269
6270         /**
6271          * Register a post-processor function.
6272          *
6273          * @param {String} name
6274          * @param {Function} postprocessor
6275          */
6276         registerPostprocessor: function(name, fn, always) {
6277             this.postprocessors[name] = {
6278                 name: name,
6279                 always: always ||  false,
6280                 fn: fn
6281             };
6282
6283             return this;
6284         },
6285
6286         /**
6287          * Set the default post processors array stack which are applied to every class.
6288          *
6289          * @param {String/Array} The name of a registered post processor or an array of registered names.
6290          * @return {Ext.ClassManager} this
6291          */
6292         setDefaultPostprocessors: function(postprocessors) {
6293             this.defaultPostprocessors = Ext.Array.from(postprocessors);
6294
6295             return this;
6296         },
6297
6298         /**
6299          * Insert this post-processor at a specific position in the stack, optionally relative to
6300          * any existing post-processor
6301          *
6302          * @param {String} name The post-processor name. Note that it needs to be registered with
6303          * {@link Ext.ClassManager#registerPostprocessor} before this
6304          * @param {String} offset The insertion position. Four possible values are:
6305          * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
6306          * @param {String} relativeName
6307          * @return {Ext.ClassManager} this
6308          */
6309         setDefaultPostprocessorPosition: function(name, offset, relativeName) {
6310             var defaultPostprocessors = this.defaultPostprocessors,
6311                 index;
6312
6313             if (typeof offset === 'string') {
6314                 if (offset === 'first') {
6315                     defaultPostprocessors.unshift(name);
6316
6317                     return this;
6318                 }
6319                 else if (offset === 'last') {
6320                     defaultPostprocessors.push(name);
6321
6322                     return this;
6323                 }
6324
6325                 offset = (offset === 'after') ? 1 : -1;
6326             }
6327
6328             index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
6329
6330             if (index !== -1) {
6331                 defaultPostprocessors.splice(Math.max(0, index + offset), 0, name);
6332             }
6333
6334             return this;
6335         },
6336
6337         /**
6338          * Converts a string expression to an array of matching class names. An expression can either refers to class aliases
6339          * or class names. Expressions support wildcards:
6340
6341      // returns ['Ext.window.Window']
6342     var window = Ext.ClassManager.getNamesByExpression('widget.window');
6343
6344     // returns ['widget.panel', 'widget.window', ...]
6345     var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
6346
6347     // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
6348     var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
6349
6350          * @param {String} expression
6351          * @return {Array} classNames
6352          * @markdown
6353          */
6354         getNamesByExpression: function(expression) {
6355             var nameToAliasesMap = this.maps.nameToAliases,
6356                 names = [],
6357                 name, alias, aliases, possibleName, regex, i, ln;
6358
6359             if (typeof expression !== 'string' || expression.length < 1) {
6360                 Ext.Error.raise({
6361                     sourceClass: "Ext.ClassManager",
6362                     sourceMethod: "getNamesByExpression",
6363                     msg: "Expression " + expression + " is invalid, must be a non-empty string"
6364                 });
6365             }
6366
6367             if (expression.indexOf('*') !== -1) {
6368                 expression = expression.replace(/\*/g, '(.*?)');
6369                 regex = new RegExp('^' + expression + '$');
6370
6371                 for (name in nameToAliasesMap) {
6372                     if (nameToAliasesMap.hasOwnProperty(name)) {
6373                         aliases = nameToAliasesMap[name];
6374
6375                         if (name.search(regex) !== -1) {
6376                             names.push(name);
6377                         }
6378                         else {
6379                             for (i = 0, ln = aliases.length; i < ln; i++) {
6380                                 alias = aliases[i];
6381
6382                                 if (alias.search(regex) !== -1) {
6383                                     names.push(name);
6384                                     break;
6385                                 }
6386                             }
6387                         }
6388                     }
6389                 }
6390
6391             } else {
6392                 possibleName = this.getNameByAlias(expression);
6393
6394                 if (possibleName) {
6395                     names.push(possibleName);
6396                 } else {
6397                     possibleName = this.getNameByAlternate(expression);
6398
6399                     if (possibleName) {
6400                         names.push(possibleName);
6401                     } else {
6402                         names.push(expression);
6403                     }
6404                 }
6405             }
6406
6407             return names;
6408         }
6409     };
6410
6411     Manager.registerPostprocessor('alias', function(name, cls, data) {
6412         var aliases = data.alias,
6413             widgetPrefix = 'widget.',
6414             i, ln, alias;
6415
6416         if (!(aliases instanceof Array)) {
6417             aliases = [aliases];
6418         }
6419
6420         for (i = 0, ln = aliases.length; i < ln; i++) {
6421             alias = aliases[i];
6422
6423             if (typeof alias !== 'string') {
6424                 Ext.Error.raise({
6425                     sourceClass: "Ext",
6426                     sourceMethod: "define",
6427                     msg: "Invalid alias of: '" + alias + "' for class: '" + name + "'; must be a valid string"
6428                 });
6429             }
6430
6431             this.setAlias(cls, alias);
6432         }
6433
6434         // This is ugly, will change to make use of parseNamespace for alias later on
6435         for (i = 0, ln = aliases.length; i < ln; i++) {
6436             alias = aliases[i];
6437
6438             if (alias.substring(0, widgetPrefix.length) === widgetPrefix) {
6439                 // Only the first alias with 'widget.' prefix will be used for xtype
6440                 cls.xtype = cls.$xtype = alias.substring(widgetPrefix.length);
6441                 break;
6442             }
6443         }
6444     });
6445
6446     Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
6447         fn.call(this, name, new cls(), data);
6448         return false;
6449     });
6450
6451     Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
6452         var alternates = data.alternateClassName,
6453             i, ln, alternate;
6454
6455         if (!(alternates instanceof Array)) {
6456             alternates = [alternates];
6457         }
6458
6459         for (i = 0, ln = alternates.length; i < ln; i++) {
6460             alternate = alternates[i];
6461
6462             if (typeof alternate !== 'string') {
6463                 Ext.Error.raise({
6464                     sourceClass: "Ext",
6465                     sourceMethod: "define",
6466                     msg: "Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string"
6467                 });
6468             }
6469
6470             this.set(alternate, cls);
6471         }
6472     });
6473
6474     Manager.setDefaultPostprocessors(['alias', 'singleton', 'alternateClassName']);
6475
6476     Ext.apply(Ext, {
6477         /**
6478          * Convenient shorthand, see {@link Ext.ClassManager#instantiate}
6479          * @member Ext
6480          * @method create
6481          */
6482         create: alias(Manager, 'instantiate'),
6483
6484         /**
6485          * @private
6486          * API to be stablized
6487          *
6488          * @param {Mixed} item
6489          * @param {String} namespace
6490          */
6491         factory: function(item, namespace) {
6492             if (item instanceof Array) {
6493                 var i, ln;
6494
6495                 for (i = 0, ln = item.length; i < ln; i++) {
6496                     item[i] = Ext.factory(item[i], namespace);
6497                 }
6498
6499                 return item;
6500             }
6501
6502             var isString = (typeof item === 'string');
6503
6504             if (isString || (item instanceof Object && item.constructor === Object)) {
6505                 var name, config = {};
6506
6507                 if (isString) {
6508                     name = item;
6509                 }
6510                 else {
6511                     name = item.className;
6512                     config = item;
6513                     delete config.className;
6514                 }
6515
6516                 if (namespace !== undefined && name.indexOf(namespace) === -1) {
6517                     name = namespace + '.' + Ext.String.capitalize(name);
6518                 }
6519
6520                 return Ext.create(name, config);
6521             }
6522
6523             if (typeof item === 'function') {
6524                 return Ext.create(item);
6525             }
6526
6527             return item;
6528         },
6529
6530         /**
6531          * Convenient shorthand to create a widget by its xtype, also see {@link Ext.ClassManager#instantiateByAlias}
6532
6533     var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button')
6534     var panel = Ext.widget('panel'); // Equivalent to Ext.create('widget.panel')
6535
6536          * @member Ext
6537          * @method widget
6538          * @markdown
6539          */
6540         widget: function(name) {
6541             var args = slice.call(arguments);
6542             args[0] = 'widget.' + name;
6543
6544             return Manager.instantiateByAlias.apply(Manager, args);
6545         },
6546
6547         /**
6548          * Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias}
6549          * @member Ext
6550          * @method createByAlias
6551          */
6552         createByAlias: alias(Manager, 'instantiateByAlias'),
6553
6554         /**
6555          * Convenient shorthand for {@link Ext.ClassManager#create}, see detailed {@link Ext.Class explanation}
6556          * @member Ext
6557          * @method define
6558          */
6559         define: alias(Manager, 'create'),
6560
6561         /**
6562          * Convenient shorthand, see {@link Ext.ClassManager#getName}
6563          * @member Ext
6564          * @method getClassName
6565          */
6566         getClassName: alias(Manager, 'getName'),
6567
6568         /**
6569          *
6570          * @param {Mixed} object
6571          */
6572         getDisplayName: function(object) {
6573             if (object.displayName) {
6574                 return object.displayName;
6575             }
6576
6577             if (object.$name && object.$class) {
6578                 return Ext.getClassName(object.$class) + '#' + object.$name;
6579             }
6580
6581             if (object.$className) {
6582                 return object.$className;
6583             }
6584
6585             return 'Anonymous';
6586         },
6587
6588         /**
6589          * Convenient shorthand, see {@link Ext.ClassManager#getClass}
6590          * @member Ext
6591          * @method getClassName
6592          */
6593         getClass: alias(Manager, 'getClass'),
6594
6595         /**
6596          * Creates namespaces to be used for scoping variables and classes so that they are not global.
6597          * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
6598
6599     Ext.namespace('Company', 'Company.data');
6600
6601      // equivalent and preferable to the above syntax
6602     Ext.namespace('Company.data');
6603
6604     Company.Widget = function() { ... };
6605
6606     Company.data.CustomStore = function(config) { ... };
6607
6608          * @param {String} namespace1
6609          * @param {String} namespace2
6610          * @param {String} etc
6611          * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
6612          * @function
6613          * @member Ext
6614          * @method namespace
6615          * @markdown
6616          */
6617         namespace: alias(Manager, 'createNamespaces')
6618     });
6619
6620     Ext.createWidget = Ext.widget;
6621
6622     /**
6623      * Convenient alias for {@link Ext#namespace Ext.namespace}
6624      * @member Ext
6625      * @method ns
6626      */
6627     Ext.ns = Ext.namespace;
6628
6629     Class.registerPreprocessor('className', function(cls, data) {
6630         if (data.$className) {
6631             cls.$className = data.$className;
6632             cls.displayName = cls.$className;
6633         }
6634     }, true);
6635
6636     Class.setDefaultPreprocessorPosition('className', 'first');
6637
6638 })(Ext.Class, Ext.Function.alias);
6639
6640 /**
6641  * @author Jacky Nguyen <jacky@sencha.com>
6642  * @docauthor Jacky Nguyen <jacky@sencha.com>
6643  * @class Ext.Loader
6644  *
6645
6646 Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
6647 via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading
6648 approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:
6649
6650 # Asynchronous Loading #
6651
6652 - Advantages:
6653         + Cross-domain
6654         + No web server needed: you can run the application via the file system protocol (i.e: `file://path/to/your/index
6655  .html`)
6656         + Best possible debugging experience: error messages come with the exact file name and line number
6657
6658 - Disadvantages:
6659         + Dependencies need to be specified before-hand
6660
6661 ### Method 1: Explicitly include what you need: ###
6662
6663     // Syntax
6664     Ext.require({String/Array} expressions);
6665
6666     // Example: Single alias
6667     Ext.require('widget.window');
6668
6669     // Example: Single class name
6670     Ext.require('Ext.window.Window');
6671
6672     // Example: Multiple aliases / class names mix
6673     Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
6674
6675     // Wildcards
6676     Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
6677
6678 ### Method 2: Explicitly exclude what you don't need: ###
6679
6680     // Syntax: Note that it must be in this chaining format.
6681     Ext.exclude({String/Array} expressions)
6682        .require({String/Array} expressions);
6683
6684     // Include everything except Ext.data.*
6685     Ext.exclude('Ext.data.*').require('*'); 
6686
6687     // Include all widgets except widget.checkbox*,
6688     // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
6689     Ext.exclude('widget.checkbox*').require('widget.*');
6690
6691 # Synchronous Loading on Demand #
6692
6693 - *Advantages:*
6694         + There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js
6695  before
6696
6697 - *Disadvantages:*
6698         + Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
6699         + Must be from the same domain due to XHR restriction
6700         + Need a web server, same reason as above
6701
6702 There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword
6703
6704     Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
6705
6706     Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
6707
6708     Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
6709
6710 Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already
6711  existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given
6712  class and all its dependencies.
6713
6714 # Hybrid Loading - The Best of Both Worlds #
6715
6716 It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:
6717
6718 ### Step 1: Start writing your application using synchronous approach. Ext.Loader will automatically fetch all
6719  dependencies on demand as they're needed during run-time. For example: ###
6720
6721     Ext.onReady(function(){
6722         var window = Ext.createWidget('window', {
6723             width: 500,
6724             height: 300,
6725             layout: {
6726                 type: 'border',
6727                 padding: 5
6728             },
6729             title: 'Hello Dialog',
6730             items: [{
6731                 title: 'Navigation',
6732                 collapsible: true,
6733                 region: 'west',
6734                 width: 200,
6735                 html: 'Hello',
6736                 split: true
6737             }, {
6738                 title: 'TabPanel',
6739                 region: 'center'
6740             }]
6741         });
6742
6743         window.show();
6744     })
6745
6746 ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these: ###
6747
6748     [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code
6749     ClassManager.js:432
6750     [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
6751
6752 Simply copy and paste the suggested code above `Ext.onReady`, i.e:
6753
6754     Ext.require('Ext.window.Window');
6755     Ext.require('Ext.layout.container.Border');
6756
6757     Ext.onReady(...);
6758
6759 Everything should now load via asynchronous mode.
6760
6761 # Deployment #
6762
6763 It's important to note that dynamic loading should only be used during development on your local machines.
6764 During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes
6765 the whole process of transitioning from / to between development / maintenance and production as easy as
6766 possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies your application
6767 needs in the exact loading sequence. It's as simple as concatenating all files in this array into one,
6768 then include it on top of your application.
6769
6770 This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.
6771
6772  * @singleton
6773  * @markdown
6774  */
6775
6776 (function(Manager, Class, flexSetter, alias) {
6777
6778     var
6779         dependencyProperties = ['extend', 'mixins', 'requires'],
6780         Loader;
6781
6782     Loader = Ext.Loader = {
6783         /**
6784          * @private
6785          */
6786         documentHead: typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
6787
6788         /**
6789          * Flag indicating whether there are still files being loaded
6790          * @private
6791          */
6792         isLoading: false,
6793
6794         /**
6795          * Maintain the queue for all dependencies. Each item in the array is an object of the format:
6796          * {
6797          *      requires: [...], // The required classes for this queue item
6798          *      callback: function() { ... } // The function to execute when all classes specified in requires exist
6799          * }
6800          * @private
6801          */
6802         queue: [],
6803
6804         /**
6805          * Maintain the list of files that have already been handled so that they never get double-loaded
6806          * @private
6807          */
6808         isFileLoaded: {},
6809
6810         /**
6811          * Maintain the list of listeners to execute when all required scripts are fully loaded
6812          * @private
6813          */
6814         readyListeners: [],
6815
6816         /**
6817          * Contains optional dependencies to be loaded last
6818          * @private
6819          */
6820         optionalRequires: [],
6821
6822         /**
6823          * Map of fully qualified class names to an array of dependent classes.
6824          * @private
6825          */
6826         requiresMap: {},
6827
6828         /**
6829          * @private
6830          */
6831         numPendingFiles: 0,
6832
6833         /**
6834          * @private
6835          */
6836         numLoadedFiles: 0,
6837
6838         /** @private */
6839         hasFileLoadError: false,
6840
6841         /**
6842          * @private
6843          */
6844         classNameToFilePathMap: {},
6845
6846         /**
6847          * An array of class names to keep track of the dependency loading order.
6848          * This is not guaranteed to be the same everytime due to the asynchronous
6849          * nature of the Loader.
6850          *
6851          * @property history
6852          * @type Array
6853          */
6854         history: [],
6855
6856         /**
6857          * Configuration
6858          * @private
6859          */
6860         config: {
6861             /**
6862              * Whether or not to enable the dynamic dependency loading feature
6863              * Defaults to false
6864              * @cfg {Boolean} enabled
6865              */
6866             enabled: false,
6867
6868             /**
6869              * @cfg {Boolean} disableCaching
6870              * Appends current timestamp to script files to prevent caching
6871              * Defaults to true
6872              */
6873             disableCaching: true,
6874
6875             /**
6876              * @cfg {String} disableCachingParam
6877              * The get parameter name for the cache buster's timestamp.
6878              * Defaults to '_dc'
6879              */
6880             disableCachingParam: '_dc',
6881
6882             /**
6883              * @cfg {Object} paths
6884              * The mapping from namespaces to file paths
6885     {
6886         'Ext': '.', // This is set by default, Ext.layout.container.Container will be
6887                     // loaded from ./layout/Container.js
6888
6889         'My': './src/my_own_folder' // My.layout.Container will be loaded from
6890                                     // ./src/my_own_folder/layout/Container.js
6891     }
6892              * Note that all relative paths are relative to the current HTML document.
6893              * If not being specified, for example, <code>Other.awesome.Class</code>
6894              * will simply be loaded from <code>./Other/awesome/Class.js</code>
6895              */
6896             paths: {
6897                 'Ext': '.'
6898             }
6899         },
6900
6901         /**
6902          * Set the configuration for the loader. This should be called right after ext-core.js
6903          * (or ext-core-debug.js) is included in the page, i.e:
6904
6905     <script type="text/javascript" src="ext-core-debug.js"></script>
6906     <script type="text/javascript">
6907       Ext.Loader.setConfig({
6908           enabled: true,
6909           paths: {
6910               'My': 'my_own_path'
6911           }
6912       });
6913     <script>
6914     <script type="text/javascript">
6915       Ext.require(...);
6916
6917       Ext.onReady(function() {
6918           // application code here
6919       });
6920     </script>
6921
6922          * Refer to {@link Ext.Loader#configs} for the list of possible properties
6923          *
6924          * @param {Object} config The config object to override the default values in {@link Ext.Loader#config}
6925          * @return {Ext.Loader} this
6926          * @markdown
6927          */
6928         setConfig: function(name, value) {
6929             if (Ext.isObject(name) && arguments.length === 1) {
6930                 Ext.Object.merge(this.config, name);
6931             }
6932             else {
6933                 this.config[name] = (Ext.isObject(value)) ? Ext.Object.merge(this.config[name], value) : value;
6934             }
6935
6936             return this;
6937         },
6938
6939         /**
6940          * Get the config value corresponding to the specified name. If no name is given, will return the config object
6941          * @param {String} name The config property name
6942          * @return {Object/Mixed}
6943          */
6944         getConfig: function(name) {
6945             if (name) {
6946                 return this.config[name];
6947             }
6948
6949             return this.config;
6950         },
6951
6952         /**
6953          * Sets the path of a namespace.
6954          * For Example:
6955
6956     Ext.Loader.setPath('Ext', '.');
6957
6958          * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter}
6959          * @param {String} path See {@link Ext.Function#flexSetter flexSetter}
6960          * @return {Ext.Loader} this
6961          * @markdown
6962          */
6963         setPath: flexSetter(function(name, path) {
6964             this.config.paths[name] = path;
6965
6966             return this;
6967         }),
6968
6969         /**
6970          * Translates a className to a file path by adding the
6971          * the proper prefix and converting the .'s to /'s. For example:
6972
6973     Ext.Loader.setPath('My', '/path/to/My');
6974
6975     alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
6976
6977          * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
6978
6979     Ext.Loader.setPath({
6980         'My': '/path/to/lib',
6981         'My.awesome': '/other/path/for/awesome/stuff',
6982         'My.awesome.more': '/more/awesome/path'
6983     });
6984
6985     alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
6986
6987     alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
6988
6989     alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
6990
6991     alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
6992
6993          * @param {String} className
6994          * @return {String} path
6995          * @markdown
6996          */
6997         getPath: function(className) {
6998             var path = '',
6999                 paths = this.config.paths,
7000                 prefix = this.getPrefix(className);
7001
7002             if (prefix.length > 0) {
7003                 if (prefix === className) {
7004                     return paths[prefix];
7005                 }
7006
7007                 path = paths[prefix];
7008                 className = className.substring(prefix.length + 1);
7009             }
7010
7011             if (path.length > 0) {
7012                 path += '/';
7013             }
7014
7015             return path.replace(/\/\.\//g, '/') + className.replace(/\./g, "/") + '.js';
7016         },
7017
7018         /**
7019          * @private
7020          * @param {String} className
7021          */
7022         getPrefix: function(className) {
7023             var paths = this.config.paths,
7024                 prefix, deepestPrefix = '';
7025
7026             if (paths.hasOwnProperty(className)) {
7027                 return className;
7028             }
7029
7030             for (prefix in paths) {
7031                 if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) {
7032                     if (prefix.length > deepestPrefix.length) {
7033                         deepestPrefix = prefix;
7034                     }
7035                 }
7036             }
7037
7038             return deepestPrefix;
7039         },
7040
7041         /**
7042          * Refresh all items in the queue. If all dependencies for an item exist during looping,
7043          * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
7044          * empty
7045          * @private
7046          */
7047         refreshQueue: function() {
7048             var ln = this.queue.length,
7049                 i, item, j, requires;
7050
7051             if (ln === 0) {
7052                 this.triggerReady();
7053                 return;
7054             }
7055
7056             for (i = 0; i < ln; i++) {
7057                 item = this.queue[i];
7058
7059                 if (item) {
7060                     requires = item.requires;
7061
7062                     // Don't bother checking when the number of files loaded
7063                     // is still less than the array length
7064                     if (requires.length > this.numLoadedFiles) {
7065                         continue;
7066                     }
7067
7068                     j = 0;
7069
7070                     do {
7071                         if (Manager.isCreated(requires[j])) {
7072                             // Take out from the queue
7073                             requires.splice(j, 1);
7074                         }
7075                         else {
7076                             j++;
7077                         }
7078                     } while (j < requires.length);
7079
7080                     if (item.requires.length === 0) {
7081                         this.queue.splice(i, 1);
7082                         item.callback.call(item.scope);
7083                         this.refreshQueue();
7084                         break;
7085                     }
7086                 }
7087             }
7088
7089             return this;
7090         },
7091
7092         /**
7093          * Inject a script element to document's head, call onLoad and onError accordingly
7094          * @private
7095          */
7096         injectScriptElement: function(url, onLoad, onError, scope) {
7097             var script = document.createElement('script'),
7098                 me = this,
7099                 onLoadFn = function() {
7100                     me.cleanupScriptElement(script);
7101                     onLoad.call(scope);
7102                 },
7103                 onErrorFn = function() {
7104                     me.cleanupScriptElement(script);
7105                     onError.call(scope);
7106                 };
7107
7108             script.type = 'text/javascript';
7109             script.src = url;
7110             script.onload = onLoadFn;
7111             script.onerror = onErrorFn;
7112             script.onreadystatechange = function() {
7113                 if (this.readyState === 'loaded' || this.readyState === 'complete') {
7114                     onLoadFn();
7115                 }
7116             };
7117
7118             this.documentHead.appendChild(script);
7119
7120             return script;
7121         },
7122
7123         /**
7124          * @private
7125          */
7126         cleanupScriptElement: function(script) {
7127             script.onload = null;
7128             script.onreadystatechange = null;
7129             script.onerror = null;
7130
7131             return this;
7132         },
7133
7134         /**
7135          * Load a script file, supports both asynchronous and synchronous approaches
7136          *
7137          * @param {String} url
7138          * @param {Function} onLoad
7139          * @param {Scope} scope
7140          * @param {Boolean} synchronous
7141          * @private
7142          */
7143         loadScriptFile: function(url, onLoad, onError, scope, synchronous) {
7144             var me = this,
7145                 noCacheUrl = url + (this.getConfig('disableCaching') ? ('?' + this.getConfig('disableCachingParam') + '=' + Ext.Date.now()) : ''),
7146                 fileName = url.split('/').pop(),
7147                 isCrossOriginRestricted = false,
7148                 xhr, status, onScriptError;
7149
7150             scope = scope || this;
7151
7152             this.isLoading = true;
7153
7154             if (!synchronous) {
7155                 onScriptError = function() {
7156                     onError.call(scope, "Failed loading '" + url + "', please verify that the file exists", synchronous);
7157                 };
7158
7159                 if (!Ext.isReady && Ext.onDocumentReady) {
7160                     Ext.onDocumentReady(function() {
7161                         me.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
7162                     });
7163                 }
7164                 else {
7165                     this.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
7166                 }
7167             }
7168             else {
7169                 if (typeof XMLHttpRequest !== 'undefined') {
7170                     xhr = new XMLHttpRequest();
7171                 } else {
7172                     xhr = new ActiveXObject('Microsoft.XMLHTTP');
7173                 }
7174
7175                 try {
7176                     xhr.open('GET', noCacheUrl, false);
7177                     xhr.send(null);
7178                 } catch (e) {
7179                     isCrossOriginRestricted = true;
7180                 }
7181
7182                 status = (xhr.status === 1223) ? 204 : xhr.status;
7183
7184                 if (!isCrossOriginRestricted) {
7185                     isCrossOriginRestricted = (status === 0);
7186                 }
7187
7188                 if (isCrossOriginRestricted
7189                 ) {
7190                     onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; It's likely that the file is either " +
7191                                        "being loaded from a different domain or from the local file system whereby cross origin " +
7192                                        "requests are not allowed due to security reasons. Use asynchronous loading with " +
7193                                        "Ext.require instead.", synchronous);
7194                 }
7195                 else if (status >= 200 && status < 300
7196                 ) {
7197                     // Firebug friendly, file names are still shown even though they're eval'ed code
7198                     new Function(xhr.responseText + "\n//@ sourceURL=" + fileName)();
7199
7200                     onLoad.call(scope);
7201                 }
7202                 else {
7203                     onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; please " +
7204                                        "verify that the file exists. " +
7205                                        "XHR status code: " + status, synchronous);
7206                 }
7207
7208                 // Prevent potential IE memory leak
7209                 xhr = null;
7210             }
7211         },
7212
7213         /**
7214          * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
7215          * Can be chained with more `require` and `exclude` methods, eg:
7216
7217     Ext.exclude('Ext.data.*').require('*');
7218
7219     Ext.exclude('widget.button*').require('widget.*');
7220
7221          * @param {Array} excludes
7222          * @return {Object} object contains `require` method for chaining
7223          * @markdown
7224          */
7225         exclude: function(excludes) {
7226             var me = this;
7227
7228             return {
7229                 require: function(expressions, fn, scope) {
7230                     return me.require(expressions, fn, scope, excludes);
7231                 },
7232
7233                 syncRequire: function(expressions, fn, scope) {
7234                     return me.syncRequire(expressions, fn, scope, excludes);
7235                 }
7236             };
7237         },
7238
7239         /**
7240          * Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by {@link Ext#syncRequire} for convenience
7241          * @param {String/Array} expressions Can either be a string or an array of string
7242          * @param {Function} fn (Optional) The callback function
7243          * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
7244          * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
7245          * @markdown
7246          */
7247         syncRequire: function() {
7248             this.syncModeEnabled = true;
7249             this.require.apply(this, arguments);
7250             this.refreshQueue();
7251             this.syncModeEnabled = false;
7252         },
7253
7254         /**
7255          * Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when
7256          * finishes, within the optional scope. This method is aliased by {@link Ext#require Ext.require} for convenience
7257          * @param {String/Array} expressions Can either be a string or an array of string
7258          * @param {Function} fn (Optional) The callback function
7259          * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
7260          * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
7261          * @markdown
7262          */
7263         require: function(expressions, fn, scope, excludes) {
7264             var filePath, expression, exclude, className, excluded = {},
7265                 excludedClassNames = [],
7266                 possibleClassNames = [],
7267                 possibleClassName, classNames = [],
7268                 i, j, ln, subLn;
7269
7270             expressions = Ext.Array.from(expressions);
7271             excludes = Ext.Array.from(excludes);
7272
7273             fn = fn || Ext.emptyFn;
7274
7275             scope = scope || Ext.global;
7276
7277             for (i = 0, ln = excludes.length; i < ln; i++) {
7278                 exclude = excludes[i];
7279
7280                 if (typeof exclude === 'string' && exclude.length > 0) {
7281                     excludedClassNames = Manager.getNamesByExpression(exclude);
7282
7283                     for (j = 0, subLn = excludedClassNames.length; j < subLn; j++) {
7284                         excluded[excludedClassNames[j]] = true;
7285                     }
7286                 }
7287             }
7288
7289             for (i = 0, ln = expressions.length; i < ln; i++) {
7290                 expression = expressions[i];
7291
7292                 if (typeof expression === 'string' && expression.length > 0) {
7293                     possibleClassNames = Manager.getNamesByExpression(expression);
7294
7295                     for (j = 0, subLn = possibleClassNames.length; j < subLn; j++) {
7296                         possibleClassName = possibleClassNames[j];
7297
7298                         if (!excluded.hasOwnProperty(possibleClassName) && !Manager.isCreated(possibleClassName)) {
7299                             Ext.Array.include(classNames, possibleClassName);
7300                         }
7301                     }
7302                 }
7303             }
7304
7305             // If the dynamic dependency feature is not being used, throw an error
7306             // if the dependencies are not defined
7307             if (!this.config.enabled) {
7308                 if (classNames.length > 0) {
7309                     Ext.Error.raise({
7310                         sourceClass: "Ext.Loader",
7311                         sourceMethod: "require",
7312                         msg: "Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " +
7313                              "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', ')
7314                     });
7315                 }
7316             }
7317
7318             if (classNames.length === 0) {
7319                 fn.call(scope);
7320                 return this;
7321             }
7322
7323             this.queue.push({
7324                 requires: classNames,
7325                 callback: fn,
7326                 scope: scope
7327             });
7328
7329             classNames = classNames.slice();
7330
7331             for (i = 0, ln = classNames.length; i < ln; i++) {
7332                 className = classNames[i];
7333
7334                 if (!this.isFileLoaded.hasOwnProperty(className)) {
7335                     this.isFileLoaded[className] = false;
7336
7337                     filePath = this.getPath(className);
7338
7339                     this.classNameToFilePathMap[className] = filePath;
7340
7341                     this.numPendingFiles++;
7342
7343                     this.loadScriptFile(
7344                         filePath,
7345                         Ext.Function.pass(this.onFileLoaded, [className, filePath], this),
7346                         Ext.Function.pass(this.onFileLoadError, [className, filePath]),
7347                         this,
7348                         this.syncModeEnabled
7349                     );
7350                 }
7351             }
7352
7353             return this;
7354         },
7355
7356         /**
7357          * @private
7358          * @param {String} className
7359          * @param {String} filePath
7360          */
7361         onFileLoaded: function(className, filePath) {
7362             this.numLoadedFiles++;
7363
7364             this.isFileLoaded[className] = true;
7365
7366             this.numPendingFiles--;
7367
7368             if (this.numPendingFiles === 0) {
7369                 this.refreshQueue();
7370             }
7371
7372             if (this.numPendingFiles <= 1) {
7373                 window.status = "Finished loading all dependencies, onReady fired!";
7374             }
7375             else {
7376                 window.status = "Loading dependencies, " + this.numPendingFiles + " files left...";
7377             }
7378
7379             if (!this.syncModeEnabled && this.numPendingFiles === 0 && this.isLoading && !this.hasFileLoadError) {
7380                 var queue = this.queue,
7381                     requires,
7382                     i, ln, j, subLn, missingClasses = [], missingPaths = [];
7383
7384                 for (i = 0, ln = queue.length; i < ln; i++) {
7385                     requires = queue[i].requires;
7386
7387                     for (j = 0, subLn = requires.length; j < ln; j++) {
7388                         if (this.isFileLoaded[requires[j]]) {
7389                             missingClasses.push(requires[j]);
7390                         }
7391                     }
7392                 }
7393
7394                 if (missingClasses.length < 1) {
7395                     return;
7396                 }
7397
7398                 missingClasses = Ext.Array.filter(missingClasses, function(item) {
7399                     return !this.requiresMap.hasOwnProperty(item);
7400                 }, this);
7401
7402                 for (i = 0,ln = missingClasses.length; i < ln; i++) {
7403                     missingPaths.push(this.classNameToFilePathMap[missingClasses[i]]);
7404                 }
7405
7406                 Ext.Error.raise({
7407                     sourceClass: "Ext.Loader",
7408                     sourceMethod: "onFileLoaded",
7409                     msg: "The following classes are not declared even if their files have been " +
7410                             "loaded: '" + missingClasses.join("', '") + "'. Please check the source code of their " +
7411                             "corresponding files for possible typos: '" + missingPaths.join("', '") + "'"
7412                 });
7413             }
7414         },
7415
7416         /**
7417          * @private
7418          */
7419         onFileLoadError: function(className, filePath, errorMessage, isSynchronous) {
7420             this.numPendingFiles--;
7421             this.hasFileLoadError = true;
7422
7423             Ext.Error.raise({
7424                 sourceClass: "Ext.Loader",
7425                 classToLoad: className,
7426                 loadPath: filePath,
7427                 loadingType: isSynchronous ? 'synchronous' : 'async',
7428                 msg: errorMessage
7429             });
7430         },
7431
7432         /**
7433          * @private
7434          */
7435         addOptionalRequires: function(requires) {
7436             var optionalRequires = this.optionalRequires,
7437                 i, ln, require;
7438
7439             requires = Ext.Array.from(requires);
7440
7441             for (i = 0, ln = requires.length; i < ln; i++) {
7442                 require = requires[i];
7443
7444                 Ext.Array.include(optionalRequires, require);
7445             }
7446
7447             return this;
7448         },
7449
7450         /**
7451          * @private
7452          */
7453         triggerReady: function(force) {
7454             var readyListeners = this.readyListeners,
7455                 optionalRequires, listener;
7456
7457             if (this.isLoading || force) {
7458                 this.isLoading = false;
7459
7460                 if (this.optionalRequires.length) {
7461                     // Clone then empty the array to eliminate potential recursive loop issue
7462                     optionalRequires = Ext.Array.clone(this.optionalRequires);
7463
7464                     // Empty the original array
7465                     this.optionalRequires.length = 0;
7466
7467                     this.require(optionalRequires, Ext.Function.pass(this.triggerReady, [true], this), this);
7468                     return this;
7469                 }
7470
7471                 while (readyListeners.length) {
7472                     listener = readyListeners.shift();
7473                     listener.fn.call(listener.scope);
7474
7475                     if (this.isLoading) {
7476                         return this;
7477                     }
7478                 }
7479             }
7480
7481             return this;
7482         },
7483
7484         /**
7485          * Add a new listener to be executed when all required scripts are fully loaded
7486          *
7487          * @param {Function} fn The function callback to be executed
7488          * @param {Object} scope The execution scope (<code>this</code>) of the callback function
7489          * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well
7490          */
7491         onReady: function(fn, scope, withDomReady, options) {
7492             var oldFn;
7493
7494             if (withDomReady !== false && Ext.onDocumentReady) {
7495                 oldFn = fn;
7496
7497                 fn = function() {
7498                     Ext.onDocumentReady(oldFn, scope, options);
7499                 };
7500             }
7501
7502             if (!this.isLoading) {
7503                 fn.call(scope);
7504             }
7505             else {
7506                 this.readyListeners.push({
7507                     fn: fn,
7508                     scope: scope
7509                 });
7510             }
7511         },
7512
7513         /**
7514          * @private
7515          * @param {String} className
7516          */
7517         historyPush: function(className) {
7518             if (className && this.isFileLoaded.hasOwnProperty(className)) {
7519                 Ext.Array.include(this.history, className);
7520             }
7521
7522             return this;
7523         }
7524     };
7525
7526     /**
7527      * Convenient alias of {@link Ext.Loader#require}. Please see the introduction documentation of
7528      * {@link Ext.Loader} for examples.
7529      * @member Ext
7530      * @method require
7531      */
7532     Ext.require = alias(Loader, 'require');
7533
7534     /**
7535      * Synchronous version of {@link Ext#require}, convenient alias of {@link Ext.Loader#syncRequire}.
7536      *
7537      * @member Ext
7538      * @method syncRequire
7539      */
7540     Ext.syncRequire = alias(Loader, 'syncRequire');
7541
7542     /**
7543      * Convenient shortcut to {@link Ext.Loader#exclude}
7544      * @member Ext
7545      * @method exclude
7546      */
7547     Ext.exclude = alias(Loader, 'exclude');
7548
7549     /**
7550      * @member Ext
7551      * @method onReady
7552      */
7553     Ext.onReady = function(fn, scope, options) {
7554         Loader.onReady(fn, scope, true, options);
7555     };
7556
7557     Class.registerPreprocessor('loader', function(cls, data, continueFn) {
7558         var me = this,
7559             dependencies = [],
7560             className = Manager.getName(cls),
7561             i, j, ln, subLn, value, propertyName, propertyValue;
7562
7563         /*
7564         Basically loop through the dependencyProperties, look for string class names and push
7565         them into a stack, regardless of whether the property's value is a string, array or object. For example:
7566         {
7567               extend: 'Ext.MyClass',
7568               requires: ['Ext.some.OtherClass'],
7569               mixins: {
7570                   observable: 'Ext.util.Observable';
7571               }
7572         }
7573         which will later be transformed into:
7574         {
7575               extend: Ext.MyClass,
7576               requires: [Ext.some.OtherClass],
7577               mixins: {
7578                   observable: Ext.util.Observable;
7579               }
7580         }
7581         */
7582
7583         for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
7584             propertyName = dependencyProperties[i];
7585
7586             if (data.hasOwnProperty(propertyName)) {
7587                 propertyValue = data[propertyName];
7588
7589                 if (typeof propertyValue === 'string') {
7590                     dependencies.push(propertyValue);
7591                 }
7592                 else if (propertyValue instanceof Array) {
7593                     for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
7594                         value = propertyValue[j];
7595
7596                         if (typeof value === 'string') {
7597                             dependencies.push(value);
7598                         }
7599                     }
7600                 }
7601                 else {
7602                     for (j in propertyValue) {
7603                         if (propertyValue.hasOwnProperty(j)) {
7604                             value = propertyValue[j];
7605
7606                             if (typeof value === 'string') {
7607                                 dependencies.push(value);
7608                             }
7609                         }
7610                     }
7611                 }
7612             }
7613         }
7614
7615         if (dependencies.length === 0) {
7616 //            Loader.historyPush(className);
7617             return;
7618         }
7619
7620         var deadlockPath = [],
7621             requiresMap = Loader.requiresMap,
7622             detectDeadlock;
7623
7624         /*
7625         Automatically detect deadlocks before-hand,
7626         will throw an error with detailed path for ease of debugging. Examples of deadlock cases:
7627
7628         - A extends B, then B extends A
7629         - A requires B, B requires C, then C requires A
7630
7631         The detectDeadlock function will recursively transverse till the leaf, hence it can detect deadlocks
7632         no matter how deep the path is.
7633         */
7634
7635         if (className) {
7636             requiresMap[className] = dependencies;
7637
7638             detectDeadlock = function(cls) {
7639                 deadlockPath.push(cls);
7640
7641                 if (requiresMap[cls]) {
7642                     if (Ext.Array.contains(requiresMap[cls], className)) {
7643                         Ext.Error.raise({
7644                             sourceClass: "Ext.Loader",
7645                             msg: "Deadlock detected while loading dependencies! '" + className + "' and '" +
7646                                 deadlockPath[1] + "' " + "mutually require each other. Path: " +
7647                                 deadlockPath.join(' -> ') + " -> " + deadlockPath[0]
7648                         });
7649                     }
7650
7651                     for (i = 0, ln = requiresMap[cls].length; i < ln; i++) {
7652                         detectDeadlock(requiresMap[cls][i]);
7653                     }
7654                 }
7655             };
7656
7657             detectDeadlock(className);
7658         }
7659
7660
7661         Loader.require(dependencies, function() {
7662             for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
7663                 propertyName = dependencyProperties[i];
7664
7665                 if (data.hasOwnProperty(propertyName)) {
7666                     propertyValue = data[propertyName];
7667
7668                     if (typeof propertyValue === 'string') {
7669                         data[propertyName] = Manager.get(propertyValue);
7670                     }
7671                     else if (propertyValue instanceof Array) {
7672                         for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
7673                             value = propertyValue[j];
7674
7675                             if (typeof value === 'string') {
7676                                 data[propertyName][j] = Manager.get(value);
7677                             }
7678                         }
7679                     }
7680                     else {
7681                         for (var k in propertyValue) {
7682                             if (propertyValue.hasOwnProperty(k)) {
7683                                 value = propertyValue[k];
7684
7685                                 if (typeof value === 'string') {
7686                                     data[propertyName][k] = Manager.get(value);
7687                                 }
7688                             }
7689                         }
7690                     }
7691                 }
7692             }
7693
7694             continueFn.call(me, cls, data);
7695         });
7696
7697         return false;
7698     }, true);
7699
7700     Class.setDefaultPreprocessorPosition('loader', 'after', 'className');
7701
7702     Manager.registerPostprocessor('uses', function(name, cls, data) {
7703         var uses = Ext.Array.from(data.uses),
7704             items = [],
7705             i, ln, item;
7706
7707         for (i = 0, ln = uses.length; i < ln; i++) {
7708             item = uses[i];
7709
7710             if (typeof item === 'string') {
7711                 items.push(item);
7712             }
7713         }
7714
7715         Loader.addOptionalRequires(items);
7716     });
7717
7718     Manager.setDefaultPostprocessorPosition('uses', 'last');
7719
7720 })(Ext.ClassManager, Ext.Class, Ext.Function.flexSetter, Ext.Function.alias);
7721
7722 /**
7723  * @class Ext.Error
7724  * @private
7725  * @extends Error
7726
7727 A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling
7728 errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that
7729 uses the Ext 4 class system, the Error class can automatically add the source class and method from which
7730 the error was raised. It also includes logic to automatically log the eroor to the console, if available, 
7731 with additional metadata about the error. In all cases, the error will always be thrown at the end so that
7732 execution will halt.
7733
7734 Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to 
7735 handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether,
7736 although in a real application it's usually a better idea to override the handling function and perform
7737 logging or some other method of reporting the errors in a way that is meaningful to the application.
7738
7739 At its simplest you can simply raise an error as a simple string from within any code:
7740
7741 #Example usage:#
7742
7743     Ext.Error.raise('Something bad happened!');
7744     
7745 If raised from plain JavaScript code, the error will be logged to the console (if available) and the message
7746 displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add
7747 additional metadata about the error being raised.  The {@link #raise} method can also take a config object.
7748 In this form the `msg` attribute becomes the error description, and any other data added to the config gets
7749 added to the error object and, if the console is available, logged to the console for inspection.
7750
7751 #Example usage:#
7752  
7753     Ext.define('Ext.Foo', {
7754         doSomething: function(option){
7755             if (someCondition === false) {
7756                 Ext.Error.raise({
7757                     msg: 'You cannot do that!',
7758                     option: option,   // whatever was passed into the method
7759                     'error code': 100 // other arbitrary info
7760                 });
7761             }
7762         }
7763     });
7764
7765 If a console is available (that supports the `console.dir` function) you'll see console output like:
7766
7767     An error was raised with the following data:
7768     option:         Object { foo: "bar"}
7769         foo:        "bar"
7770     error code:     100
7771     msg:            "You cannot do that!"
7772     sourceClass:   "Ext.Foo"
7773     sourceMethod:  "doSomething"
7774     
7775     uncaught exception: You cannot do that!
7776
7777 As you can see, the error will report exactly where it was raised and will include as much information as the 
7778 raising code can usefully provide.
7779
7780 If you want to handle all application errors globally you can simply override the static {@link handle} method
7781 and provide whatever handling logic you need. If the method returns true then the error is considered handled
7782 and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.
7783
7784 #Example usage:#
7785
7786     Ext.Error.handle = function(err) {
7787         if (err.someProperty == 'NotReallyAnError') {
7788             // maybe log something to the application here if applicable
7789             return true;
7790         }
7791         // any non-true return value (including none) will cause the error to be thrown
7792     }
7793
7794  * Create a new Error object
7795  * @param {Object} config The config object
7796  * @markdown
7797  * @author Brian Moeskau <brian@sencha.com>
7798  * @docauthor Brian Moeskau <brian@sencha.com>
7799  */
7800 Ext.Error = Ext.extend(Error, {
7801     statics: {
7802         /**
7803          * @property ignore
7804 Static flag that can be used to globally disable error reporting to the browser if set to true
7805 (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail
7806 and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably
7807 be preferable to supply a custom error {@link #handle handling} function instead.
7808
7809 #Example usage:#
7810
7811     Ext.Error.ignore = true;
7812
7813          * @markdown
7814          * @static
7815          */
7816         ignore: false,
7817
7818         /**
7819 Raise an error that can include additional data and supports automatic console logging if available. 
7820 You can pass a string error message or an object with the `msg` attribute which will be used as the 
7821 error message. The object can contain any other name-value attributes (or objects) to be logged 
7822 along with the error.
7823
7824 Note that after displaying the error message a JavaScript error will ultimately be thrown so that 
7825 execution will halt.
7826
7827 #Example usage:#
7828
7829     Ext.Error.raise('A simple string error message');
7830
7831     // or...
7832
7833     Ext.define('Ext.Foo', {
7834         doSomething: function(option){
7835             if (someCondition === false) {
7836                 Ext.Error.raise({
7837                     msg: 'You cannot do that!',
7838                     option: option,   // whatever was passed into the method
7839                     'error code': 100 // other arbitrary info
7840                 });
7841             }
7842         }
7843     });
7844          * @param {String/Object} err The error message string, or an object containing the 
7845          * attribute "msg" that will be used as the error message. Any other data included in
7846          * the object will also be logged to the browser console, if available.
7847          * @static
7848          * @markdown
7849          */
7850         raise: function(err){
7851             err = err || {};
7852             if (Ext.isString(err)) {
7853                 err = { msg: err };
7854             }
7855
7856             var method = this.raise.caller;
7857
7858             if (method) {
7859                 if (method.$name) {
7860                     err.sourceMethod = method.$name;
7861                 }
7862                 if (method.$owner) {
7863                     err.sourceClass = method.$owner.$className;
7864                 }
7865             }
7866
7867             if (Ext.Error.handle(err) !== true) {
7868                 var global = Ext.global,
7869                     con = global.console,
7870                     msg = Ext.Error.prototype.toString.call(err),
7871                     noConsoleMsg = 'An uncaught error was raised: "' + msg + 
7872                         '". Use Firebug or Webkit console for additional details.';
7873
7874                 if (con) {
7875                     if (con.dir) {
7876                         con.warn('An uncaught error was raised with the following data:');
7877                         con.dir(err);
7878                     }
7879                     else {
7880                         con.warn(noConsoleMsg);
7881                     }
7882                     if (con.error) {
7883                         con.error(msg);
7884                     }
7885                 }
7886                 else if (global.alert){
7887                     global.alert(noConsoleMsg);
7888                 }
7889                 
7890                 throw new Ext.Error(err);
7891             }
7892         },
7893
7894         /**
7895 Globally handle any Ext errors that may be raised, optionally providing custom logic to
7896 handle different errors individually. Return true from the function to bypass throwing the
7897 error to the browser, otherwise the error will be thrown and execution will halt.
7898
7899 #Example usage:#
7900
7901     Ext.Error.handle = function(err) {
7902         if (err.someProperty == 'NotReallyAnError') {
7903             // maybe log something to the application here if applicable
7904             return true;
7905         }
7906         // any non-true return value (including none) will cause the error to be thrown
7907     }
7908
7909          * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes
7910          * that were originally raised with it, plus properties about the method and class from which
7911          * the error originated (if raised from a class that uses the Ext 4 class system).
7912          * @static
7913          * @markdown
7914          */
7915         handle: function(){
7916             return Ext.Error.ignore;
7917         }
7918     },
7919
7920     /**
7921      * @constructor
7922      * @param {String/Object} config The error message string, or an object containing the 
7923      * attribute "msg" that will be used as the error message. Any other data included in
7924      * the object will be applied to the error instance and logged to the browser console, if available.
7925      */
7926     constructor: function(config){
7927         if (Ext.isString(config)) {
7928             config = { msg: config };
7929         }
7930         Ext.apply(this, config);
7931     },
7932
7933     /**
7934 Provides a custom string representation of the error object. This is an override of the base JavaScript 
7935 `Object.toString` method, which is useful so that when logged to the browser console, an error object will 
7936 be displayed with a useful message instead of `[object Object]`, the default `toString` result.
7937
7938 The default implementation will include the error message along with the raising class and method, if available,
7939 but this can be overridden with a custom implementation either at the prototype level (for all errors) or on
7940 a particular error instance, if you want to provide a custom description that will show up in the console.
7941      * @markdown
7942      * @return {String} The error message. If raised from within the Ext 4 class system, the error message
7943      * will also include the raising class and method names, if available.
7944      */
7945     toString: function(){
7946         var me = this,
7947             className = me.className ? me.className  : '',
7948             methodName = me.methodName ? '.' + me.methodName + '(): ' : '',
7949             msg = me.msg || '(No description provided)';
7950
7951         return className + methodName + msg;
7952     }
7953 });
7954
7955
7956 /*
7957 Ext JS - JavaScript Library
7958 Copyright (c) 2006-2011, Sencha Inc.
7959 All rights reserved.
7960 licensing@sencha.com
7961 */
7962 /**
7963  * @class Ext.JSON
7964  * Modified version of Douglas Crockford"s json.js that doesn"t
7965  * mess with the Object prototype
7966  * http://www.json.org/js.html
7967  * @singleton
7968  */
7969 Ext.JSON = new(function() {
7970     var useHasOwn = !! {}.hasOwnProperty,
7971     isNative = function() {
7972         var useNative = null;
7973
7974         return function() {
7975             if (useNative === null) {
7976                 useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
7977             }
7978
7979             return useNative;
7980         };
7981     }(),
7982     pad = function(n) {
7983         return n < 10 ? "0" + n : n;
7984     },
7985     doDecode = function(json) {
7986         return eval("(" + json + ')');
7987     },
7988     doEncode = function(o) {
7989         if (!Ext.isDefined(o) || o === null) {
7990             return "null";
7991         } else if (Ext.isArray(o)) {
7992             return encodeArray(o);
7993         } else if (Ext.isDate(o)) {
7994             return Ext.JSON.encodeDate(o);
7995         } else if (Ext.isString(o)) {
7996             return encodeString(o);
7997         } else if (typeof o == "number") {
7998             //don't use isNumber here, since finite checks happen inside isNumber
7999             return isFinite(o) ? String(o) : "null";
8000         } else if (Ext.isBoolean(o)) {
8001             return String(o);
8002         } else if (Ext.isObject(o)) {
8003             return encodeObject(o);
8004         } else if (typeof o === "function") {
8005             return "null";
8006         }
8007         return 'undefined';
8008     },
8009     m = {
8010         "\b": '\\b',
8011         "\t": '\\t',
8012         "\n": '\\n',
8013         "\f": '\\f',
8014         "\r": '\\r',
8015         '"': '\\"',
8016         "\\": '\\\\',
8017         '\x0b': '\\u000b' //ie doesn't handle \v
8018     },
8019     charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g,
8020     encodeString = function(s) {
8021         return '"' + s.replace(charToReplace, function(a) {
8022             var c = m[a];
8023             return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
8024         }) + '"';
8025     },
8026     encodeArray = function(o) {
8027         var a = ["[", ""],
8028         // Note empty string in case there are no serializable members.
8029         len = o.length,
8030         i;
8031         for (i = 0; i < len; i += 1) {
8032             a.push(doEncode(o[i]), ',');
8033         }
8034         // Overwrite trailing comma (or empty string)
8035         a[a.length - 1] = ']';
8036         return a.join("");
8037     },
8038     encodeObject = function(o) {
8039         var a = ["{", ""],
8040         // Note empty string in case there are no serializable members.
8041         i;
8042         for (i in o) {
8043             if (!useHasOwn || o.hasOwnProperty(i)) {
8044                 a.push(doEncode(i), ":", doEncode(o[i]), ',');
8045             }
8046         }
8047         // Overwrite trailing comma (or empty string)
8048         a[a.length - 1] = '}';
8049         return a.join("");
8050     };
8051
8052     /**
8053      * <p>Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression.
8054      * <b>The returned value includes enclosing double quotation marks.</b></p>
8055      * <p>The default return format is "yyyy-mm-ddThh:mm:ss".</p>
8056      * <p>To override this:</p><pre><code>
8057      Ext.JSON.encodeDate = function(d) {
8058      return d.format('"Y-m-d"');
8059      };
8060      </code></pre>
8061      * @param {Date} d The Date to encode
8062      * @return {String} The string literal to use in a JSON string.
8063      */
8064     this.encodeDate = function(o) {
8065         return '"' + o.getFullYear() + "-" 
8066         + pad(o.getMonth() + 1) + "-"
8067         + pad(o.getDate()) + "T"
8068         + pad(o.getHours()) + ":"
8069         + pad(o.getMinutes()) + ":"
8070         + pad(o.getSeconds()) + '"';
8071     };
8072
8073     /**
8074      * Encodes an Object, Array or other value
8075      * @param {Mixed} o The variable to encode
8076      * @return {String} The JSON string
8077      */
8078     this.encode = function() {
8079         var ec;
8080         return function(o) {
8081             if (!ec) {
8082                 // setup encoding function on first access
8083                 ec = isNative() ? JSON.stringify : doEncode;
8084             }
8085             return ec(o);
8086         };
8087     }();
8088
8089
8090     /**
8091      * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
8092      * @param {String} json The JSON string
8093      * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
8094      * @return {Object} The resulting object
8095      */
8096     this.decode = function() {
8097         var dc;
8098         return function(json, safe) {
8099             if (!dc) {
8100                 // setup decoding function on first access
8101                 dc = isNative() ? JSON.parse : doDecode;
8102             }
8103             try {
8104                 return dc(json);
8105             } catch (e) {
8106                 if (safe === true) {
8107                     return null;
8108                 }
8109                 Ext.Error.raise({
8110                     sourceClass: "Ext.JSON",
8111                     sourceMethod: "decode",
8112                     msg: "You're trying to decode and invalid JSON String: " + json
8113                 });
8114             }
8115         };
8116     }();
8117
8118 })();
8119 /**
8120  * Shorthand for {@link Ext.JSON#encode}
8121  * @param {Mixed} o The variable to encode
8122  * @return {String} The JSON string
8123  * @member Ext
8124  * @method encode
8125  */
8126 Ext.encode = Ext.JSON.encode;
8127 /**
8128  * Shorthand for {@link Ext.JSON#decode}
8129  * @param {String} json The JSON string
8130  * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
8131  * @return {Object} The resulting object
8132  * @member Ext
8133  * @method decode
8134  */
8135 Ext.decode = Ext.JSON.decode;
8136
8137
8138 /**
8139  * @class Ext
8140
8141  The Ext namespace (global object) encapsulates all classes, singletons, and utility methods provided by Sencha's libraries.</p>
8142  Most user interface Components are at a lower level of nesting in the namespace, but many common utility functions are provided
8143  as direct properties of the Ext namespace.
8144
8145  Also many frequently used methods from other classes are provided as shortcuts within the Ext namespace.
8146  For example {@link Ext#getCmp Ext.getCmp} aliases {@link Ext.ComponentManager#get Ext.ComponentManager.get}.
8147
8148  Many applications are initiated with {@link Ext#onReady Ext.onReady} which is called once the DOM is ready.
8149  This ensures all scripts have been loaded, preventing dependency issues. For example
8150
8151      Ext.onReady(function(){
8152          new Ext.Component({
8153              renderTo: document.body,
8154              html: 'DOM ready!'
8155          });
8156      });
8157
8158 For more information about how to use the Ext classes, see
8159
8160 * <a href="http://www.sencha.com/learn/">The Learning Center</a>
8161 * <a href="http://www.sencha.com/learn/Ext_FAQ">The FAQ</a>
8162 * <a href="http://www.sencha.com/forum/">The forums</a>
8163
8164  * @singleton
8165  * @markdown
8166  */
8167 Ext.apply(Ext, {
8168     userAgent: navigator.userAgent.toLowerCase(),
8169     cache: {},
8170     idSeed: 1000,
8171     BLANK_IMAGE_URL : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
8172     isStrict: document.compatMode == "CSS1Compat",
8173     windowId: 'ext-window',
8174     documentId: 'ext-document',
8175
8176     /**
8177      * True when the document is fully initialized and ready for action
8178      * @type Boolean
8179      */
8180     isReady: false,
8181
8182     /**
8183      * True to automatically uncache orphaned Ext.core.Elements periodically (defaults to true)
8184      * @type Boolean
8185      */
8186     enableGarbageCollector: true,
8187
8188     /**
8189      * True to automatically purge event listeners during garbageCollection (defaults to true).
8190      * @type Boolean
8191      */
8192     enableListenerCollection: true,
8193
8194     /**
8195      * Generates unique ids. If the element already has an id, it is unchanged
8196      * @param {Mixed} el (optional) The element to generate an id for
8197      * @param {String} prefix (optional) Id prefix (defaults "ext-gen")
8198      * @return {String} The generated Id.
8199      */
8200     id: function(el, prefix) {
8201         el = Ext.getDom(el, true) || {};
8202         if (el === document) {
8203             el.id = this.documentId;
8204         }
8205         else if (el === window) {
8206             el.id = this.windowId;
8207         }
8208         if (!el.id) {
8209             el.id = (prefix || "ext-gen") + (++Ext.idSeed);
8210         }
8211         return el.id;
8212     },
8213
8214     /**
8215      * Returns the current document body as an {@link Ext.core.Element}.
8216      * @return Ext.core.Element The document body
8217      */
8218     getBody: function() {
8219         return Ext.get(document.body || false);
8220     },
8221
8222     /**
8223      * Returns the current document head as an {@link Ext.core.Element}.
8224      * @return Ext.core.Element The document head
8225      */
8226     getHead: function() {
8227         var head;
8228
8229         return function() {
8230             if (head == undefined) {
8231                 head = Ext.get(document.getElementsByTagName("head")[0]);
8232             }
8233
8234             return head;
8235         };
8236     }(),
8237
8238     /**
8239      * Returns the current HTML document object as an {@link Ext.core.Element}.
8240      * @return Ext.core.Element The document
8241      */
8242     getDoc: function() {
8243         return Ext.get(document);
8244     },
8245
8246     /**
8247      * This is shorthand reference to {@link Ext.ComponentManager#get}.
8248      * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id}
8249      * @param {String} id The component {@link Ext.Component#id id}
8250      * @return Ext.Component The Component, <tt>undefined</tt> if not found, or <tt>null</tt> if a
8251      * Class was found.
8252     */
8253     getCmp: function(id) {
8254         return Ext.ComponentManager.get(id);
8255     },
8256
8257     /**
8258      * Returns the current orientation of the mobile device
8259      * @return {String} Either 'portrait' or 'landscape'
8260      */
8261     getOrientation: function() {
8262         return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape';
8263     },
8264
8265     /**
8266      * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
8267      * DOM (if applicable) and calling their destroy functions (if available).  This method is primarily
8268      * intended for arguments of type {@link Ext.core.Element} and {@link Ext.Component}, but any subclass of
8269      * {@link Ext.util.Observable} can be passed in.  Any number of elements and/or components can be
8270      * passed into this function in a single call as separate arguments.
8271      * @param {Mixed} arg1 An {@link Ext.core.Element}, {@link Ext.Component}, or an Array of either of these to destroy
8272      * @param {Mixed} arg2 (optional)
8273      * @param {Mixed} etc... (optional)
8274      */
8275     destroy: function() {
8276         var ln = arguments.length,
8277         i, arg;
8278
8279         for (i = 0; i < ln; i++) {
8280             arg = arguments[i];
8281             if (arg) {
8282                 if (Ext.isArray(arg)) {
8283                     this.destroy.apply(this, arg);
8284                 }
8285                 else if (Ext.isFunction(arg.destroy)) {
8286                     arg.destroy();
8287                 }
8288                 else if (arg.dom) {
8289                     arg.remove();
8290                 }
8291             }
8292         }
8293     },
8294
8295     /**
8296      * Execute a callback function in a particular scope. If no function is passed the call is ignored.
8297      * @param {Function} callback The callback to execute
8298      * @param {Object} scope (optional) The scope to execute in
8299      * @param {Array} args (optional) The arguments to pass to the function
8300      * @param {Number} delay (optional) Pass a number to delay the call by a number of milliseconds.
8301      */
8302     callback: function(callback, scope, args, delay){
8303         if(Ext.isFunction(callback)){
8304             args = args || [];
8305             scope = scope || window;
8306             if (delay) {
8307                 Ext.defer(callback, delay, scope, args);
8308             } else {
8309                 callback.apply(scope, args);
8310             }
8311         }
8312     },
8313
8314     /**
8315      * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
8316      * @param {String} value The string to encode
8317      * @return {String} The encoded text
8318      */
8319     htmlEncode : function(value) {
8320         return Ext.String.htmlEncode(value);
8321     },
8322
8323     /**
8324      * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
8325      * @param {String} value The string to decode
8326      * @return {String} The decoded text
8327      */
8328     htmlDecode : function(value) {
8329          return Ext.String.htmlDecode(value);
8330     },
8331
8332     /**
8333      * Appends content to the query string of a URL, handling logic for whether to place
8334      * a question mark or ampersand.
8335      * @param {String} url The URL to append to.
8336      * @param {String} s The content to append to the URL.
8337      * @return (String) The resulting URL
8338      */
8339     urlAppend : function(url, s) {
8340         if (!Ext.isEmpty(s)) {
8341             return url + (url.indexOf('?') === -1 ? '?' : '&') + s;
8342         }
8343         return url;
8344     }
8345 });
8346
8347
8348 Ext.ns = Ext.namespace;
8349
8350 // for old browsers
8351 window.undefined = window.undefined;
8352 /**
8353  * @class Ext
8354  * Ext core utilities and functions.
8355  * @singleton
8356  */
8357 (function(){
8358     var check = function(regex){
8359             return regex.test(Ext.userAgent);
8360         },
8361         docMode = document.documentMode,
8362         isOpera = check(/opera/),
8363         isOpera10_5 = isOpera && check(/version\/10\.5/),
8364         isChrome = check(/\bchrome\b/),
8365         isWebKit = check(/webkit/),
8366         isSafari = !isChrome && check(/safari/),
8367         isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
8368         isSafari3 = isSafari && check(/version\/3/),
8369         isSafari4 = isSafari && check(/version\/4/),
8370         isIE = !isOpera && check(/msie/),
8371         isIE7 = isIE && (check(/msie 7/) || docMode == 7),
8372         isIE8 = isIE && (check(/msie 8/) && docMode != 7 && docMode != 9 || docMode == 8),
8373         isIE9 = isIE && (check(/msie 9/) && docMode != 7 && docMode != 8 || docMode == 9),
8374         isIE6 = isIE && check(/msie 6/),
8375         isGecko = !isWebKit && check(/gecko/),
8376         isGecko3 = isGecko && check(/rv:1\.9/),
8377         isGecko4 = isGecko && check(/rv:2\.0/),
8378         isFF3_0 = isGecko3 && check(/rv:1\.9\.0/),
8379         isFF3_5 = isGecko3 && check(/rv:1\.9\.1/),
8380         isFF3_6 = isGecko3 && check(/rv:1\.9\.2/),
8381         isWindows = check(/windows|win32/),
8382         isMac = check(/macintosh|mac os x/),
8383         isLinux = check(/linux/),
8384         scrollWidth = null;
8385
8386     // remove css image flicker
8387     try {
8388         document.execCommand("BackgroundImageCache", false, true);
8389     } catch(e) {}
8390
8391     Ext.setVersion('extjs', '4.0.0');
8392     Ext.apply(Ext, {
8393         /**
8394          * URL to a blank file used by Ext when in secure mode for iframe src and onReady src to prevent
8395          * the IE insecure content warning (<tt>'about:blank'</tt>, except for IE in secure mode, which is <tt>'javascript:""'</tt>).
8396          * @type String
8397          */
8398         SSL_SECURE_URL : Ext.isSecure && isIE ? 'javascript:""' : 'about:blank',
8399
8400         /**
8401          * True if the {@link Ext.fx.Anim} Class is available
8402          * @type Boolean
8403          * @property enableFx
8404          */
8405
8406         /**
8407          * True to scope the reset CSS to be just applied to Ext components. Note that this wraps root containers
8408          * with an additional element. Also remember that when you turn on this option, you have to use ext-all-scoped {
8409          * unless you use the bootstrap.js to load your javascript, in which case it will be handled for you.
8410          * @type Boolean
8411          */
8412         scopeResetCSS : Ext.buildSettings.scopeResetCSS,
8413
8414         /**
8415          * EXPERIMENTAL - True to cascade listener removal to child elements when an element is removed.
8416          * Currently not optimized for performance.
8417          * @type Boolean
8418          */
8419         enableNestedListenerRemoval : false,
8420
8421         /**
8422          * Indicates whether to use native browser parsing for JSON methods.
8423          * This option is ignored if the browser does not support native JSON methods.
8424          * <b>Note: Native JSON methods will not work with objects that have functions.
8425          * Also, property names must be quoted, otherwise the data will not parse.</b> (Defaults to false)
8426          * @type Boolean
8427          */
8428         USE_NATIVE_JSON : false,
8429
8430         /**
8431          * Return the dom node for the passed String (id), dom node, or Ext.core.Element.
8432          * Optional 'strict' flag is needed for IE since it can return 'name' and
8433          * 'id' elements by using getElementById.
8434          * Here are some examples:
8435          * <pre><code>
8436 // gets dom node based on id
8437 var elDom = Ext.getDom('elId');
8438 // gets dom node based on the dom node
8439 var elDom1 = Ext.getDom(elDom);
8440
8441 // If we don&#39;t know if we are working with an
8442 // Ext.core.Element or a dom node use Ext.getDom
8443 function(el){
8444     var dom = Ext.getDom(el);
8445     // do something with the dom node
8446 }
8447          * </code></pre>
8448          * <b>Note</b>: the dom node to be found actually needs to exist (be rendered, etc)
8449          * when this method is called to be successful.
8450          * @param {Mixed} el
8451          * @return HTMLElement
8452          */
8453         getDom : function(el, strict) {
8454             if (!el || !document) {
8455                 return null;
8456             }
8457             if (el.dom) {
8458                 return el.dom;
8459             } else {
8460                 if (typeof el == 'string') {
8461                     var e = document.getElementById(el);
8462                     // IE returns elements with the 'name' and 'id' attribute.
8463                     // we do a strict check to return the element with only the id attribute
8464                     if (e && isIE && strict) {
8465                         if (el == e.getAttribute('id')) {
8466                             return e;
8467                         } else {
8468                             return null;
8469                         }
8470                     }
8471                     return e;
8472                 } else {
8473                     return el;
8474                 }
8475             }
8476         },
8477
8478         /**
8479          * Removes a DOM node from the document.
8480          * <p>Removes this element from the document, removes all DOM event listeners, and deletes the cache reference.
8481          * All DOM event listeners are removed from this element. If {@link Ext#enableNestedListenerRemoval Ext.enableNestedListenerRemoval} is
8482          * <code>true</code>, then DOM event listeners are also removed from all child nodes. The body node
8483          * will be ignored if passed in.</p>
8484          * @param {HTMLElement} node The node to remove
8485          */
8486         removeNode : isIE6 || isIE7 ? function() {
8487             var d;
8488             return function(n){
8489                 if(n && n.tagName != 'BODY'){
8490                     (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
8491                     d = d || document.createElement('div');
8492                     d.appendChild(n);
8493                     d.innerHTML = '';
8494                     delete Ext.cache[n.id];
8495                 }
8496             };
8497         }() : function(n) {
8498             if (n && n.parentNode && n.tagName != 'BODY') {
8499                 (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
8500                 n.parentNode.removeChild(n);
8501                 delete Ext.cache[n.id];
8502             }
8503         },
8504
8505         /**
8506          * True if the detected browser is Opera.
8507          * @type Boolean
8508          */
8509         isOpera : isOpera,
8510
8511         /**
8512          * True if the detected browser is Opera 10.5x.
8513          * @type Boolean
8514          */
8515         isOpera10_5 : isOpera10_5,
8516
8517         /**
8518          * True if the detected browser uses WebKit.
8519          * @type Boolean
8520          */
8521         isWebKit : isWebKit,
8522
8523         /**
8524          * True if the detected browser is Chrome.
8525          * @type Boolean
8526          */
8527         isChrome : isChrome,
8528
8529         /**
8530          * True if the detected browser is Safari.
8531          * @type Boolean
8532          */
8533         isSafari : isSafari,
8534
8535         /**
8536          * True if the detected browser is Safari 3.x.
8537          * @type Boolean
8538          */
8539         isSafari3 : isSafari3,
8540
8541         /**
8542          * True if the detected browser is Safari 4.x.
8543          * @type Boolean
8544          */
8545         isSafari4 : isSafari4,
8546
8547         /**
8548          * True if the detected browser is Safari 2.x.
8549          * @type Boolean
8550          */
8551         isSafari2 : isSafari2,
8552
8553         /**
8554          * True if the detected browser is Internet Explorer.
8555          * @type Boolean
8556          */
8557         isIE : isIE,
8558
8559         /**
8560          * True if the detected browser is Internet Explorer 6.x.
8561          * @type Boolean
8562          */
8563         isIE6 : isIE6,
8564
8565         /**
8566          * True if the detected browser is Internet Explorer 7.x.
8567          * @type Boolean
8568          */
8569         isIE7 : isIE7,
8570
8571         /**
8572          * True if the detected browser is Internet Explorer 8.x.
8573          * @type Boolean
8574          */
8575         isIE8 : isIE8,
8576
8577         /**
8578          * True if the detected browser is Internet Explorer 9.x.
8579          * @type Boolean
8580          */
8581         isIE9 : isIE9,
8582
8583         /**
8584          * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
8585          * @type Boolean
8586          */
8587         isGecko : isGecko,
8588
8589         /**
8590          * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
8591          * @type Boolean
8592          */
8593         isGecko3 : isGecko3,
8594
8595         /**
8596          * True if the detected browser uses a Gecko 2.0+ layout engine (e.g. Firefox 4.x).
8597          * @type Boolean
8598          */
8599         isGecko4 : isGecko4,
8600
8601         /**
8602          * True if the detected browser uses FireFox 3.0
8603          * @type Boolean
8604          */
8605
8606         isFF3_0 : isFF3_0,
8607         /**
8608          * True if the detected browser uses FireFox 3.5
8609          * @type Boolean
8610          */
8611
8612         isFF3_5 : isFF3_5,
8613         /**
8614          * True if the detected browser uses FireFox 3.6
8615          * @type Boolean
8616          */
8617         isFF3_6 : isFF3_6,
8618
8619         /**
8620          * True if the detected platform is Linux.
8621          * @type Boolean
8622          */
8623         isLinux : isLinux,
8624
8625         /**
8626          * True if the detected platform is Windows.
8627          * @type Boolean
8628          */
8629         isWindows : isWindows,
8630
8631         /**
8632          * True if the detected platform is Mac OS.
8633          * @type Boolean
8634          */
8635         isMac : isMac,
8636
8637         /**
8638          * URL to a 1x1 transparent gif image used by Ext to create inline icons with CSS background images.
8639          * In older versions of IE, this defaults to "http://sencha.com/s.gif" and you should change this to a URL on your server.
8640          * For other browsers it uses an inline data URL.
8641          * @type String
8642          */
8643         BLANK_IMAGE_URL : (isIE6 || isIE7) ? 'http:/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
8644
8645         /**
8646          * <p>Utility method for returning a default value if the passed value is empty.</p>
8647          * <p>The value is deemed to be empty if it is<div class="mdetail-params"><ul>
8648          * <li>null</li>
8649          * <li>undefined</li>
8650          * <li>an empty array</li>
8651          * <li>a zero length string (Unless the <tt>allowBlank</tt> parameter is <tt>true</tt>)</li>
8652          * </ul></div>
8653          * @param {Mixed} value The value to test
8654          * @param {Mixed} defaultValue The value to return if the original value is empty
8655          * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
8656          * @return {Mixed} value, if non-empty, else defaultValue
8657          * @deprecated 4.0.0 Use {Ext#valueFrom} instead
8658          */
8659         value : function(v, defaultValue, allowBlank){
8660             return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
8661         },
8662
8663         /**
8664          * Escapes the passed string for use in a regular expression
8665          * @param {String} str
8666          * @return {String}
8667          * @deprecated 4.0.0 Use {@link Ext.String#escapeRegex} instead
8668          */
8669         escapeRe : function(s) {
8670             return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
8671         },
8672
8673         /**
8674          * Applies event listeners to elements by selectors when the document is ready.
8675          * The event name is specified with an <tt>&#64;</tt> suffix.
8676          * <pre><code>
8677 Ext.addBehaviors({
8678     // add a listener for click on all anchors in element with id foo
8679     '#foo a&#64;click' : function(e, t){
8680         // do something
8681     },
8682
8683     // add the same listener to multiple selectors (separated by comma BEFORE the &#64;)
8684     '#foo a, #bar span.some-class&#64;mouseover' : function(){
8685         // do something
8686     }
8687 });
8688          * </code></pre>
8689          * @param {Object} obj The list of behaviors to apply
8690          */
8691         addBehaviors : function(o){
8692             if(!Ext.isReady){
8693                 Ext.onReady(function(){
8694                     Ext.addBehaviors(o);
8695                 });
8696             } else {
8697                 var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
8698                     parts,
8699                     b,
8700                     s;
8701                 for (b in o) {
8702                     if ((parts = b.split('@'))[1]) { // for Object prototype breakers
8703                         s = parts[0];
8704                         if(!cache[s]){
8705                             cache[s] = Ext.select(s);
8706                         }
8707                         cache[s].on(parts[1], o[b]);
8708                     }
8709                 }
8710                 cache = null;
8711             }
8712         },
8713
8714         /**
8715          * Utility method for getting the width of the browser scrollbar. This can differ depending on
8716          * operating system settings, such as the theme or font size.
8717          * @param {Boolean} force (optional) true to force a recalculation of the value.
8718          * @return {Number} The width of the scrollbar.
8719          */
8720         getScrollBarWidth: function(force){
8721             if(!Ext.isReady){
8722                 return 0;
8723             }
8724
8725             if(force === true || scrollWidth === null){
8726                 // BrowserBug: IE9
8727                 // When IE9 positions an element offscreen via offsets, the offsetWidth is
8728                 // inaccurately reported. For IE9 only, we render on screen before removing.
8729                 var cssClass = Ext.isIE9 ? '' : Ext.baseCSSPrefix + 'hide-offsets';
8730                     // Append our div, do our calculation and then remove it
8731                 var div = Ext.getBody().createChild('<div class="' + cssClass + '" style="width:100px;height:50px;overflow:hidden;"><div style="height:200px;"></div></div>'),
8732                     child = div.child('div', true);
8733                 var w1 = child.offsetWidth;
8734                 div.setStyle('overflow', (Ext.isWebKit || Ext.isGecko) ? 'auto' : 'scroll');
8735                 var w2 = child.offsetWidth;
8736                 div.remove();
8737                 // Need to add 2 to ensure we leave enough space
8738                 scrollWidth = w1 - w2 + 2;
8739             }
8740             return scrollWidth;
8741         },
8742
8743         /**
8744          * Copies a set of named properties fom the source object to the destination object.
8745          * <p>example:<pre><code>
8746 ImageComponent = Ext.extend(Ext.Component, {
8747     initComponent: function() {
8748         this.autoEl = { tag: 'img' };
8749         MyComponent.superclass.initComponent.apply(this, arguments);
8750         this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
8751     }
8752 });
8753          * </code></pre>
8754          * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead.
8755          * @param {Object} dest The destination object.
8756          * @param {Object} source The source object.
8757          * @param {Array/String} names Either an Array of property names, or a comma-delimited list
8758          * of property names to copy.
8759          * @param {Boolean} usePrototypeKeys (Optional) Defaults to false. Pass true to copy keys off of the prototype as well as the instance.
8760          * @return {Object} The modified object.
8761         */
8762         copyTo : function(dest, source, names, usePrototypeKeys){
8763             if(typeof names == 'string'){
8764                 names = names.split(/[,;\s]/);
8765             }
8766             Ext.each(names, function(name){
8767                 if(usePrototypeKeys || source.hasOwnProperty(name)){
8768                     dest[name] = source[name];
8769                 }
8770             }, this);
8771             return dest;
8772         },
8773
8774         /**
8775          * Attempts to destroy and then remove a set of named properties of the passed object.
8776          * @param {Object} o The object (most likely a Component) who's properties you wish to destroy.
8777          * @param {Mixed} arg1 The name of the property to destroy and remove from the object.
8778          * @param {Mixed} etc... More property names to destroy and remove.
8779          */
8780         destroyMembers : function(o, arg1, arg2, etc){
8781             for (var i = 1, a = arguments, len = a.length; i < len; i++) {
8782                 Ext.destroy(o[a[i]]);
8783                 delete o[a[i]];
8784             }
8785         },
8786
8787         /**
8788          * Partitions the set into two sets: a true set and a false set.
8789          * Example:
8790          * Example2:
8791          * <pre><code>
8792 // Example 1:
8793 Ext.partition([true, false, true, true, false]); // [[true, true, true], [false, false]]
8794
8795 // Example 2:
8796 Ext.partition(
8797     Ext.query("p"),
8798     function(val){
8799         return val.className == "class1"
8800     }
8801 );
8802 // true are those paragraph elements with a className of "class1",
8803 // false set are those that do not have that className.
8804          * </code></pre>
8805          * @param {Array|NodeList} arr The array to partition
8806          * @param {Function} truth (optional) a function to determine truth.  If this is omitted the element
8807          *                   itself must be able to be evaluated for its truthfulness.
8808          * @return {Array} [true<Array>,false<Array>]
8809          * @deprecated 4.0.0 Will be removed in the next major version
8810          */
8811         partition : function(arr, truth){
8812             var ret = [[],[]];
8813             Ext.each(arr, function(v, i, a) {
8814                 ret[ (truth && truth(v, i, a)) || (!truth && v) ? 0 : 1].push(v);
8815             });
8816             return ret;
8817         },
8818
8819         /**
8820          * Invokes a method on each item in an Array.
8821          * <pre><code>
8822 // Example:
8823 Ext.invoke(Ext.query("p"), "getAttribute", "id");
8824 // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
8825          * </code></pre>
8826          * @param {Array|NodeList} arr The Array of items to invoke the method on.
8827          * @param {String} methodName The method name to invoke.
8828          * @param {...*} args Arguments to send into the method invocation.
8829          * @return {Array} The results of invoking the method on each item in the array.
8830          * @deprecated 4.0.0 Will be removed in the next major version
8831          */
8832         invoke : function(arr, methodName){
8833             var ret = [],
8834                 args = Array.prototype.slice.call(arguments, 2);
8835             Ext.each(arr, function(v,i) {
8836                 if (v && typeof v[methodName] == 'function') {
8837                     ret.push(v[methodName].apply(v, args));
8838                 } else {
8839                     ret.push(undefined);
8840                 }
8841             });
8842             return ret;
8843         },
8844
8845         /**
8846          * <p>Zips N sets together.</p>
8847          * <pre><code>
8848 // Example 1:
8849 Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]]
8850 // Example 2:
8851 Ext.zip(
8852     [ "+", "-", "+"],
8853     [  12,  10,  22],
8854     [  43,  15,  96],
8855     function(a, b, c){
8856         return "$" + a + "" + b + "." + c
8857     }
8858 ); // ["$+12.43", "$-10.15", "$+22.96"]
8859          * </code></pre>
8860          * @param {Arrays|NodeLists} arr This argument may be repeated. Array(s) to contribute values.
8861          * @param {Function} zipper (optional) The last item in the argument list. This will drive how the items are zipped together.
8862          * @return {Array} The zipped set.
8863          * @deprecated 4.0.0 Will be removed in the next major version
8864          */
8865         zip : function(){
8866             var parts = Ext.partition(arguments, function( val ){ return typeof val != 'function'; }),
8867                 arrs = parts[0],
8868                 fn = parts[1][0],
8869                 len = Ext.max(Ext.pluck(arrs, "length")),
8870                 ret = [];
8871
8872             for (var i = 0; i < len; i++) {
8873                 ret[i] = [];
8874                 if(fn){
8875                     ret[i] = fn.apply(fn, Ext.pluck(arrs, i));
8876                 }else{
8877                     for (var j = 0, aLen = arrs.length; j < aLen; j++){
8878                         ret[i].push( arrs[j][i] );
8879                     }
8880                 }
8881             }
8882             return ret;
8883         },
8884
8885         /**
8886          * Turns an array into a sentence, joined by a specified connector - e.g.:
8887          * Ext.toSentence(['Adama', 'Tigh', 'Roslin']); //'Adama, Tigh and Roslin'
8888          * Ext.toSentence(['Adama', 'Tigh', 'Roslin'], 'or'); //'Adama, Tigh or Roslin'
8889          * @param {Array} items The array to create a sentence from
8890          * @param {String} connector The string to use to connect the last two words. Usually 'and' or 'or' - defaults to 'and'.
8891          * @return {String} The sentence string
8892          * @deprecated 4.0.0 Will be removed in the next major version
8893          */
8894         toSentence: function(items, connector) {
8895             var length = items.length;
8896
8897             if (length <= 1) {
8898                 return items[0];
8899             } else {
8900                 var head = items.slice(0, length - 1),
8901                     tail = items[length - 1];
8902
8903                 return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail);
8904             }
8905         },
8906
8907         /**
8908          * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
8909          * you may want to set this to true.
8910          * @type Boolean
8911          */
8912         useShims: isIE6
8913     });
8914 })();
8915
8916 /**
8917  * TBD
8918  * @type Function
8919  * @param {Object} config
8920  */
8921 Ext.application = function(config) {
8922     Ext.require('Ext.app.Application');
8923
8924     Ext.onReady(function() {
8925         Ext.create('Ext.app.Application', config);
8926     });
8927 };
8928
8929 /**
8930  * @class Ext.util.Format
8931
8932 This class is a centralized place for formatting functions inside the library. It includes
8933 functions to format various different types of data, such as text, dates and numeric values.
8934
8935 __Localization__
8936 This class contains several options for localization. These can be set once the library has loaded,
8937 all calls to the functions from that point will use the locale settings that were specified.
8938 Options include:
8939 - thousandSeparator
8940 - decimalSeparator
8941 - currenyPrecision
8942 - currencySign
8943 - currencyAtEnd
8944 This class also uses the default date format defined here: {@link Ext.date#defaultFormat}.
8945
8946 __Using with renderers__
8947 There are two helper functions that return a new function that can be used in conjunction with 
8948 grid renderers:
8949
8950     columns: [{
8951         dataIndex: 'date',
8952         renderer: Ext.util.Format.dateRenderer('Y-m-d')
8953     }, {
8954         dataIndex: 'time',
8955         renderer: Ext.util.Format.numberRenderer('0.000')
8956     }]
8957     
8958 Functions that only take a single argument can also be passed directly:
8959     columns: [{
8960         dataIndex: 'cost',
8961         renderer: Ext.util.Format.usMoney
8962     }, {
8963         dataIndex: 'productCode',
8964         renderer: Ext.util.Format.uppercase
8965     }]
8966     
8967 __Using with XTemplates__
8968 XTemplates can also directly use Ext.util.Format functions:
8969
8970     new Ext.XTemplate([
8971         'Date: {startDate:date("Y-m-d")}',
8972         'Cost: {cost:usMoney}'
8973     ]);
8974
8975  * @markdown
8976  * @singleton
8977  */
8978 (function() {
8979     Ext.ns('Ext.util');
8980
8981     Ext.util.Format = {};
8982     var UtilFormat     = Ext.util.Format,
8983         stripTagsRE    = /<\/?[^>]+>/gi,
8984         stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
8985         nl2brRe        = /\r?\n/g,
8986
8987         // A RegExp to remove from a number format string, all characters except digits and '.'
8988         formatCleanRe  = /[^\d\.]/g,
8989
8990         // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
8991         // Created on first use. The local decimal separator character must be initialized for this to be created.
8992         I18NFormatCleanRe;
8993
8994     Ext.apply(UtilFormat, {
8995         /**
8996          * @type String
8997          * @property thousandSeparator
8998          * <p>The character that the {@link #number} function uses as a thousand separator.</p>
8999          * <p>This defaults to <code>,</code>, but may be overridden in a locale file.</p>
9000          */
9001         thousandSeparator: ',',
9002
9003         /**
9004          * @type String
9005          * @property decimalSeparator
9006          * <p>The character that the {@link #number} function uses as a decimal point.</p>
9007          * <p>This defaults to <code>.</code>, but may be overridden in a locale file.</p>
9008          */
9009         decimalSeparator: '.',
9010
9011         /**
9012          * @type Number
9013          * @property currencyPrecision
9014          * <p>The number of decimal places that the {@link #currency} function displays.</p>
9015          * <p>This defaults to <code>2</code>, but may be overridden in a locale file.</p>
9016          */
9017         currencyPrecision: 2,
9018
9019         /**
9020          * @type String
9021          * @property currencySign
9022          * <p>The currency sign that the {@link #currency} function displays.</p>
9023          * <p>This defaults to <code>$</code>, but may be overridden in a locale file.</p>
9024          */
9025         currencySign: '$',
9026
9027         /**
9028          * @type Boolean
9029          * @property currencyAtEnd
9030          * <p>This may be set to <code>true</code> to make the {@link #currency} function
9031          * append the currency sign to the formatted value.</p>
9032          * <p>This defaults to <code>false</code>, but may be overridden in a locale file.</p>
9033          */
9034         currencyAtEnd: false,
9035
9036         /**
9037          * Checks a reference and converts it to empty string if it is undefined
9038          * @param {Mixed} value Reference to check
9039          * @return {Mixed} Empty string if converted, otherwise the original value
9040          */
9041         undef : function(value) {
9042             return value !== undefined ? value : "";
9043         },
9044
9045         /**
9046          * Checks a reference and converts it to the default value if it's empty
9047          * @param {Mixed} value Reference to check
9048          * @param {String} defaultValue The value to insert of it's undefined (defaults to "")
9049          * @return {String}
9050          */
9051         defaultValue : function(value, defaultValue) {
9052             return value !== undefined && value !== '' ? value : defaultValue;
9053         },
9054
9055         /**
9056          * Returns a substring from within an original string
9057          * @param {String} value The original text
9058          * @param {Number} start The start index of the substring
9059          * @param {Number} length The length of the substring
9060          * @return {String} The substring
9061          */
9062         substr : function(value, start, length) {
9063             return String(value).substr(start, length);
9064         },
9065
9066         /**
9067          * Converts a string to all lower case letters
9068          * @param {String} value The text to convert
9069          * @return {String} The converted text
9070          */
9071         lowercase : function(value) {
9072             return String(value).toLowerCase();
9073         },
9074
9075         /**
9076          * Converts a string to all upper case letters
9077          * @param {String} value The text to convert
9078          * @return {String} The converted text
9079          */
9080         uppercase : function(value) {
9081             return String(value).toUpperCase();
9082         },
9083
9084         /**
9085          * Format a number as US currency
9086          * @param {Number/String} value The numeric value to format
9087          * @return {String} The formatted currency string
9088          */
9089         usMoney : function(v) {
9090             return UtilFormat.currency(v, '$', 2);
9091         },
9092
9093         /**
9094          * Format a number as a currency
9095          * @param {Number/String} value The numeric value to format
9096          * @param {String} sign The currency sign to use (defaults to {@link #currencySign})
9097          * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
9098          * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
9099          * @return {String} The formatted currency string
9100          */
9101         currency: function(v, currencySign, decimals, end) {
9102             var negativeSign = '',
9103                 format = ",0",
9104                 i = 0;
9105             v = v - 0;
9106             if (v < 0) {
9107                 v = -v;
9108                 negativeSign = '-';
9109             }
9110             decimals = decimals || UtilFormat.currencyPrecision;
9111             format += format + (decimals > 0 ? '.' : '');
9112             for (; i < decimals; i++) {
9113                 format += '0';
9114             }
9115             v = UtilFormat.number(v, format); 
9116             if ((end || UtilFormat.currencyAtEnd) === true) {
9117                 return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
9118             } else {
9119                 return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
9120             }
9121         },
9122
9123         /**
9124          * Formats the passed date using the specified format pattern.
9125          * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
9126          * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
9127          * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
9128          * @return {String} The formatted date string.
9129          */
9130         date: function(v, format) {
9131             if (!v) {
9132                 return "";
9133             }
9134             if (!Ext.isDate(v)) {
9135                 v = new Date(Date.parse(v));
9136             }
9137             return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
9138         },
9139
9140         /**
9141          * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
9142          * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
9143          * @return {Function} The date formatting function
9144          */
9145         dateRenderer : function(format) {
9146             return function(v) {
9147                 return UtilFormat.date(v, format);
9148             };
9149         },
9150
9151         /**
9152          * Strips all HTML tags
9153          * @param {Mixed} value The text from which to strip tags
9154          * @return {String} The stripped text
9155          */
9156         stripTags : function(v) {
9157             return !v ? v : String(v).replace(stripTagsRE, "");
9158         },
9159
9160         /**
9161          * Strips all script tags
9162          * @param {Mixed} value The text from which to strip script tags
9163          * @return {String} The stripped text
9164          */
9165         stripScripts : function(v) {
9166             return !v ? v : String(v).replace(stripScriptsRe, "");
9167         },
9168
9169         /**
9170          * Simple format for a file size (xxx bytes, xxx KB, xxx MB)
9171          * @param {Number/String} size The numeric value to format
9172          * @return {String} The formatted file size
9173          */
9174         fileSize : function(size) {
9175             if (size < 1024) {
9176                 return size + " bytes";
9177             } else if (size < 1048576) {
9178                 return (Math.round(((size*10) / 1024))/10) + " KB";
9179             } else {
9180                 return (Math.round(((size*10) / 1048576))/10) + " MB";
9181             }
9182         },
9183
9184         /**
9185          * It does simple math for use in a template, for example:<pre><code>
9186          * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
9187          * </code></pre>
9188          * @return {Function} A function that operates on the passed value.
9189          */
9190         math : function(){
9191             var fns = {};
9192
9193             return function(v, a){
9194                 if (!fns[a]) {
9195                     fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
9196                 }
9197                 return fns[a](v);
9198             };
9199         }(),
9200
9201         /**
9202          * Rounds the passed number to the required decimal precision.
9203          * @param {Number/String} value The numeric value to round.
9204          * @param {Number} precision The number of decimal places to which to round the first parameter's value.
9205          * @return {Number} The rounded value.
9206          */
9207         round : function(value, precision) {
9208             var result = Number(value);
9209             if (typeof precision == 'number') {
9210                 precision = Math.pow(10, precision);
9211                 result = Math.round(value * precision) / precision;
9212             }
9213             return result;
9214         },
9215
9216         /**
9217          * <p>Formats the passed number according to the passed format string.</p>
9218          * <p>The number of digits after the decimal separator character specifies the number of
9219          * decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
9220          * <p>The <i>presence</i> of a thousand separator character in the format string specifies that
9221          * the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
9222          * <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
9223          * <p><b>New to Ext4</b></p>
9224          * <p>Locale-specific characters are always used in the formatted output when inserting
9225          * thousand and decimal separators.</p>
9226          * <p>The format string must specify separator characters according to US/UK conventions ("," as the
9227          * thousand separator, and "." as the decimal separator)</p>
9228          * <p>To allow specification of format strings according to local conventions for separator characters, add
9229          * the string <code>/i</code> to the end of the format string.</p>
9230          * <div style="margin-left:40px">examples (123456.789):
9231          * <div style="margin-left:10px">
9232          * 0 - (123456) show only digits, no precision<br>
9233          * 0.00 - (123456.78) show only digits, 2 precision<br>
9234          * 0.0000 - (123456.7890) show only digits, 4 precision<br>
9235          * 0,000 - (123,456) show comma and digits, no precision<br>
9236          * 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
9237          * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
9238          * To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
9239          * For example: 0.000,00/i
9240          * </div></div>
9241          * @param {Number} v The number to format.
9242          * @param {String} format The way you would like to format this text.
9243          * @return {String} The formatted number.
9244          */
9245         number:
9246             function(v, formatString) {
9247             if (!formatString) {
9248                 return v;
9249             }
9250             v = Ext.Number.from(v, NaN);
9251             if (isNaN(v)) {
9252                 return '';
9253             }
9254             var comma = UtilFormat.thousandSeparator,
9255                 dec   = UtilFormat.decimalSeparator,
9256                 i18n  = false,
9257                 neg   = v < 0,
9258                 hasComma,
9259                 psplit;
9260
9261             v = Math.abs(v);
9262
9263             // The "/i" suffix allows caller to use a locale-specific formatting string.
9264             // Clean the format string by removing all but numerals and the decimal separator.
9265             // Then split the format string into pre and post decimal segments according to *what* the
9266             // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
9267             if (formatString.substr(formatString.length - 2) == '/i') {
9268                 if (!I18NFormatCleanRe) {
9269                     I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
9270                 }
9271                 formatString = formatString.substr(0, formatString.length - 2);
9272                 i18n   = true;
9273                 hasComma = formatString.indexOf(comma) != -1;
9274                 psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
9275             } else {
9276                 hasComma = formatString.indexOf(',') != -1;
9277                 psplit = formatString.replace(formatCleanRe, '').split('.');
9278             }
9279
9280             if (1 < psplit.length) {
9281                 v = v.toFixed(psplit[1].length);
9282             } else if(2 < psplit.length) {
9283                 Ext.Error.raise({
9284                     sourceClass: "Ext.util.Format",
9285                     sourceMethod: "number",
9286                     value: v,
9287                     formatString: formatString,
9288                     msg: "Invalid number format, should have no more than 1 decimal"
9289                 });
9290             } else {
9291                 v = v.toFixed(0);
9292             }
9293
9294             var fnum = v.toString();
9295
9296             psplit = fnum.split('.');
9297
9298             if (hasComma) {
9299                 var cnum = psplit[0],
9300                     parr = [],
9301                     j    = cnum.length,
9302                     m    = Math.floor(j / 3),
9303                     n    = cnum.length % 3 || 3,
9304                     i;
9305
9306                 for (i = 0; i < j; i += n) {
9307                     if (i !== 0) {
9308                         n = 3;
9309                     }
9310
9311                     parr[parr.length] = cnum.substr(i, n);
9312                     m -= 1;
9313                 }
9314                 fnum = parr.join(comma);
9315                 if (psplit[1]) {
9316                     fnum += dec + psplit[1];
9317                 }
9318             } else {
9319                 if (psplit[1]) {
9320                     fnum = psplit[0] + dec + psplit[1];
9321                 }
9322             }
9323
9324             return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
9325         },
9326
9327         /**
9328          * Returns a number rendering function that can be reused to apply a number format multiple times efficiently
9329          * @param {String} format Any valid number format string for {@link #number}
9330          * @return {Function} The number formatting function
9331          */
9332         numberRenderer : function(format) {
9333             return function(v) {
9334                 return UtilFormat.number(v, format);
9335             };
9336         },
9337
9338         /**
9339          * Selectively do a plural form of a word based on a numeric value. For example, in a template,
9340          * {commentCount:plural("Comment")}  would result in "1 Comment" if commentCount was 1 or would be "x Comments"
9341          * if the value is 0 or greater than 1.
9342          * @param {Number} value The value to compare against
9343          * @param {String} singular The singular form of the word
9344          * @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
9345          */
9346         plural : function(v, s, p) {
9347             return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
9348         },
9349
9350         /**
9351          * Converts newline characters to the HTML tag &lt;br/>
9352          * @param {String} The string value to format.
9353          * @return {String} The string with embedded &lt;br/> tags in place of newlines.
9354          */
9355         nl2br : function(v) {
9356             return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
9357         },
9358
9359         /**
9360          * Capitalize the given string. See {@link Ext.String#capitalize}.
9361          */
9362         capitalize: Ext.String.capitalize,
9363
9364         /**
9365          * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length.
9366          * See {@link Ext.String#ellipsis}.
9367          */
9368         ellipsis: Ext.String.ellipsis,
9369
9370         /**
9371          * Formats to a string. See {@link Ext.String#format}
9372          */
9373         format: Ext.String.format,
9374
9375         /**
9376          * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
9377          * See {@link Ext.string#htmlDecode}.
9378          */
9379         htmlDecode: Ext.String.htmlDecode,
9380
9381         /**
9382          * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
9383          * See {@link Ext.String#htmlEncode}.
9384          */
9385         htmlEncode: Ext.String.htmlEncode,
9386
9387         /**
9388          * Adds left padding to a string. See {@link Ext.String#leftPad}
9389          */
9390         leftPad: Ext.String.leftPad,
9391
9392         /**
9393          * Trims any whitespace from either side of a string. See {@link Ext.String#trim}.
9394          */
9395         trim : Ext.String.trim,
9396
9397         /**
9398          * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
9399          * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
9400          * @param {Number|String} v The encoded margins
9401          * @return {Object} An object with margin sizes for top, right, bottom and left
9402          */
9403         parseBox : function(box) {
9404             if (Ext.isNumber(box)) {
9405                 box = box.toString();
9406             }
9407             var parts  = box.split(' '),
9408                 ln = parts.length;
9409
9410             if (ln == 1) {
9411                 parts[1] = parts[2] = parts[3] = parts[0];
9412             }
9413             else if (ln == 2) {
9414                 parts[2] = parts[0];
9415                 parts[3] = parts[1];
9416             }
9417             else if (ln == 3) {
9418                 parts[3] = parts[1];
9419             }
9420
9421             return {
9422                 top   :parseInt(parts[0], 10) || 0,
9423                 right :parseInt(parts[1], 10) || 0,
9424                 bottom:parseInt(parts[2], 10) || 0,
9425                 left  :parseInt(parts[3], 10) || 0
9426             };
9427         },
9428
9429         /**
9430          * Escapes the passed string for use in a regular expression
9431          * @param {String} str
9432          * @return {String}
9433          */
9434         escapeRegex : function(s) {
9435             return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
9436         }
9437     });
9438 })();
9439
9440 /**
9441  * @class Ext.util.TaskRunner
9442  * Provides the ability to execute one or more arbitrary tasks in a multithreaded
9443  * manner.  Generally, you can use the singleton {@link Ext.TaskManager} instead, but
9444  * if needed, you can create separate instances of TaskRunner.  Any number of
9445  * separate tasks can be started at any time and will run independently of each
9446  * other. Example usage:
9447  * <pre><code>
9448 // Start a simple clock task that updates a div once per second
9449 var updateClock = function(){
9450     Ext.fly('clock').update(new Date().format('g:i:s A'));
9451
9452 var task = {
9453     run: updateClock,
9454     interval: 1000 //1 second
9455 }
9456 var runner = new Ext.util.TaskRunner();
9457 runner.start(task);
9458
9459 // equivalent using TaskManager
9460 Ext.TaskManager.start({
9461     run: updateClock,
9462     interval: 1000
9463 });
9464
9465  * </code></pre>
9466  * <p>See the {@link #start} method for details about how to configure a task object.</p>
9467  * Also see {@link Ext.util.DelayedTask}. 
9468  * 
9469  * @constructor
9470  * @param {Number} interval (optional) The minimum precision in milliseconds supported by this TaskRunner instance
9471  * (defaults to 10)
9472  */
9473 Ext.ns('Ext.util');
9474
9475 Ext.util.TaskRunner = function(interval) {
9476     interval = interval || 10;
9477     var tasks = [],
9478     removeQueue = [],
9479     id = 0,
9480     running = false,
9481
9482     // private
9483     stopThread = function() {
9484         running = false;
9485         clearInterval(id);
9486         id = 0;
9487     },
9488
9489     // private
9490     startThread = function() {
9491         if (!running) {
9492             running = true;
9493             id = setInterval(runTasks, interval);
9494         }
9495     },
9496
9497     // private
9498     removeTask = function(t) {
9499         removeQueue.push(t);
9500         if (t.onStop) {
9501             t.onStop.apply(t.scope || t);
9502         }
9503     },
9504
9505     // private
9506     runTasks = function() {
9507         var rqLen = removeQueue.length,
9508             now = new Date().getTime(),
9509             i;
9510
9511         if (rqLen > 0) {
9512             for (i = 0; i < rqLen; i++) {
9513                 Ext.Array.remove(tasks, removeQueue[i]);
9514             }
9515             removeQueue = [];
9516             if (tasks.length < 1) {
9517                 stopThread();
9518                 return;
9519             }
9520         }
9521         i = 0;
9522         var t,
9523             itime,
9524             rt,
9525             len = tasks.length;
9526         for (; i < len; ++i) {
9527             t = tasks[i];
9528             itime = now - t.taskRunTime;
9529             if (t.interval <= itime) {
9530                 rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
9531                 t.taskRunTime = now;
9532                 if (rt === false || t.taskRunCount === t.repeat) {
9533                     removeTask(t);
9534                     return;
9535                 }
9536             }
9537             if (t.duration && t.duration <= (now - t.taskStartTime)) {
9538                 removeTask(t);
9539             }
9540         }
9541     };
9542
9543     /**
9544      * Starts a new task.
9545      * @method start
9546      * @param {Object} task <p>A config object that supports the following properties:<ul>
9547      * <li><code>run</code> : Function<div class="sub-desc"><p>The function to execute each time the task is invoked. The
9548      * function will be called at each interval and passed the <code>args</code> argument if specified, and the
9549      * current invocation count if not.</p>
9550      * <p>If a particular scope (<code>this</code> reference) is required, be sure to specify it using the <code>scope</code> argument.</p>
9551      * <p>Return <code>false</code> from this function to terminate the task.</p></div></li>
9552      * <li><code>interval</code> : Number<div class="sub-desc">The frequency in milliseconds with which the task
9553      * should be invoked.</div></li>
9554      * <li><code>args</code> : Array<div class="sub-desc">(optional) An array of arguments to be passed to the function
9555      * specified by <code>run</code>. If not specified, the current invocation count is passed.</div></li>
9556      * <li><code>scope</code> : Object<div class="sub-desc">(optional) The scope (<tt>this</tt> reference) in which to execute the
9557      * <code>run</code> function. Defaults to the task config object.</div></li>
9558      * <li><code>duration</code> : Number<div class="sub-desc">(optional) The length of time in milliseconds to invoke
9559      * the task before stopping automatically (defaults to indefinite).</div></li>
9560      * <li><code>repeat</code> : Number<div class="sub-desc">(optional) The number of times to invoke the task before
9561      * stopping automatically (defaults to indefinite).</div></li>
9562      * </ul></p>
9563      * <p>Before each invocation, Ext injects the property <code>taskRunCount</code> into the task object so
9564      * that calculations based on the repeat count can be performed.</p>
9565      * @return {Object} The task
9566      */
9567     this.start = function(task) {
9568         tasks.push(task);
9569         task.taskStartTime = new Date().getTime();
9570         task.taskRunTime = 0;
9571         task.taskRunCount = 0;
9572         startThread();
9573         return task;
9574     };
9575
9576     /**
9577      * Stops an existing running task.
9578      * @method stop
9579      * @param {Object} task The task to stop
9580      * @return {Object} The task
9581      */
9582     this.stop = function(task) {
9583         removeTask(task);
9584         return task;
9585     };
9586
9587     /**
9588      * Stops all tasks that are currently running.
9589      * @method stopAll
9590      */
9591     this.stopAll = function() {
9592         stopThread();
9593         for (var i = 0, len = tasks.length; i < len; i++) {
9594             if (tasks[i].onStop) {
9595                 tasks[i].onStop();
9596             }
9597         }
9598         tasks = [];
9599         removeQueue = [];
9600     };
9601 };
9602
9603 /**
9604  * @class Ext.TaskManager
9605  * @extends Ext.util.TaskRunner
9606  * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop arbitrary tasks.  See
9607  * {@link Ext.util.TaskRunner} for supported methods and task config properties.
9608  * <pre><code>
9609 // Start a simple clock task that updates a div once per second
9610 var task = {
9611     run: function(){
9612         Ext.fly('clock').update(new Date().format('g:i:s A'));
9613     },
9614     interval: 1000 //1 second
9615 }
9616 Ext.TaskManager.start(task);
9617 </code></pre>
9618  * <p>See the {@link #start} method for details about how to configure a task object.</p>
9619  * @singleton
9620  */
9621 Ext.TaskManager = Ext.create('Ext.util.TaskRunner');
9622 /**
9623  * @class Ext.is
9624  * 
9625  * Determines information about the current platform the application is running on.
9626  * 
9627  * @singleton
9628  */
9629 Ext.is = {
9630     init : function(navigator) {
9631         var platforms = this.platforms,
9632             ln = platforms.length,
9633             i, platform;
9634
9635         navigator = navigator || window.navigator;
9636
9637         for (i = 0; i < ln; i++) {
9638             platform = platforms[i];
9639             this[platform.identity] = platform.regex.test(navigator[platform.property]);
9640         }
9641
9642         /**
9643          * @property Desktop True if the browser is running on a desktop machine
9644          * @type {Boolean}
9645          */
9646         this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android);
9647         /**
9648          * @property Tablet True if the browser is running on a tablet (iPad)
9649          */
9650         this.Tablet = this.iPad;
9651         /**
9652          * @property Phone True if the browser is running on a phone.
9653          * @type {Boolean}
9654          */
9655         this.Phone = !this.Desktop && !this.Tablet;
9656         /**
9657          * @property iOS True if the browser is running on iOS
9658          * @type {Boolean}
9659          */
9660         this.iOS = this.iPhone || this.iPad || this.iPod;
9661         
9662         /**
9663          * @property Standalone Detects when application has been saved to homescreen.
9664          * @type {Boolean}
9665          */
9666         this.Standalone = !!window.navigator.standalone;
9667     },
9668     
9669     /**
9670      * @property iPhone True when the browser is running on a iPhone
9671      * @type {Boolean}
9672      */
9673     platforms: [{
9674         property: 'platform',
9675         regex: /iPhone/i,
9676         identity: 'iPhone'
9677     },
9678     
9679     /**
9680      * @property iPod True when the browser is running on a iPod
9681      * @type {Boolean}
9682      */
9683     {
9684         property: 'platform',
9685         regex: /iPod/i,
9686         identity: 'iPod'
9687     },
9688     
9689     /**
9690      * @property iPad True when the browser is running on a iPad
9691      * @type {Boolean}
9692      */
9693     {
9694         property: 'userAgent',
9695         regex: /iPad/i,
9696         identity: 'iPad'
9697     },
9698     
9699     /**
9700      * @property Blackberry True when the browser is running on a Blackberry
9701      * @type {Boolean}
9702      */
9703     {
9704         property: 'userAgent',
9705         regex: /Blackberry/i,
9706         identity: 'Blackberry'
9707     },
9708     
9709     /**
9710      * @property Android True when the browser is running on an Android device
9711      * @type {Boolean}
9712      */
9713     {
9714         property: 'userAgent',
9715         regex: /Android/i,
9716         identity: 'Android'
9717     },
9718     
9719     /**
9720      * @property Mac True when the browser is running on a Mac
9721      * @type {Boolean}
9722      */
9723     {
9724         property: 'platform',
9725         regex: /Mac/i,
9726         identity: 'Mac'
9727     },
9728     
9729     /**
9730      * @property Windows True when the browser is running on Windows
9731      * @type {Boolean}
9732      */
9733     {
9734         property: 'platform',
9735         regex: /Win/i,
9736         identity: 'Windows'
9737     },
9738     
9739     /**
9740      * @property Linux True when the browser is running on Linux
9741      * @type {Boolean}
9742      */
9743     {
9744         property: 'platform',
9745         regex: /Linux/i,
9746         identity: 'Linux'
9747     }]
9748 };
9749
9750 Ext.is.init();
9751
9752 /**
9753  * @class Ext.supports
9754  *
9755  * Determines information about features are supported in the current environment
9756  * 
9757  * @singleton
9758  */
9759 Ext.supports = {
9760     init : function() {
9761         var doc = document,
9762             div = doc.createElement('div'),
9763             tests = this.tests,
9764             ln = tests.length,
9765             i, test;
9766
9767         div.innerHTML = [
9768             '<div style="height:30px;width:50px;">',
9769                 '<div style="height:20px;width:20px;"></div>',
9770             '</div>',
9771             '<div style="width: 200px; height: 200px; position: relative; padding: 5px;">',
9772                 '<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div>',
9773             '</div>',
9774             '<div style="float:left; background-color:transparent;"></div>'
9775         ].join('');
9776
9777         doc.body.appendChild(div);
9778
9779         for (i = 0; i < ln; i++) {
9780             test = tests[i];
9781             this[test.identity] = test.fn.call(this, doc, div);
9782         }
9783
9784         doc.body.removeChild(div);
9785     },
9786
9787     /**
9788      * @property CSS3BoxShadow True if document environment supports the CSS3 box-shadow style.
9789      * @type {Boolean}
9790      */
9791     CSS3BoxShadow: Ext.isDefined(document.documentElement.style.boxShadow),
9792
9793     /**
9794      * @property ClassList True if document environment supports the HTML5 classList API.
9795      * @type {Boolean}
9796      */
9797     ClassList: !!document.documentElement.classList,
9798
9799     /**
9800      * @property OrientationChange True if the device supports orientation change
9801      * @type {Boolean}
9802      */
9803     OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)),
9804     
9805     /**
9806      * @property DeviceMotion True if the device supports device motion (acceleration and rotation rate)
9807      * @type {Boolean}
9808      */
9809     DeviceMotion: ('ondevicemotion' in window),
9810     
9811     /**
9812      * @property Touch True if the device supports touch
9813      * @type {Boolean}
9814      */
9815     // is.Desktop is needed due to the bug in Chrome 5.0.375, Safari 3.1.2
9816     // and Safari 4.0 (they all have 'ontouchstart' in the window object).
9817     Touch: ('ontouchstart' in window) && (!Ext.is.Desktop),
9818
9819     tests: [
9820         /**
9821          * @property Transitions True if the device supports CSS3 Transitions
9822          * @type {Boolean}
9823          */
9824         {
9825             identity: 'Transitions',
9826             fn: function(doc, div) {
9827                 var prefix = [
9828                         'webkit',
9829                         'Moz',
9830                         'o',
9831                         'ms',
9832                         'khtml'
9833                     ],
9834                     TE = 'TransitionEnd',
9835                     transitionEndName = [
9836                         prefix[0] + TE,
9837                         'transitionend', //Moz bucks the prefixing convention
9838                         prefix[2] + TE,
9839                         prefix[3] + TE,
9840                         prefix[4] + TE
9841                     ],
9842                     ln = prefix.length,
9843                     i = 0,
9844                     out = false;
9845                 div = Ext.get(div);
9846                 for (; i < ln; i++) {
9847                     if (div.getStyle(prefix[i] + "TransitionProperty")) {
9848                         Ext.supports.CSS3Prefix = prefix[i];
9849                         Ext.supports.CSS3TransitionEnd = transitionEndName[i];
9850                         out = true;
9851                         break;
9852                     }
9853                 }
9854                 return out;
9855             }
9856         },
9857         
9858         /**
9859          * @property RightMargin True if the device supports right margin.
9860          * See https://bugs.webkit.org/show_bug.cgi?id=13343 for why this is needed.
9861          * @type {Boolean}
9862          */
9863         {
9864             identity: 'RightMargin',
9865             fn: function(doc, div, view) {
9866                 view = doc.defaultView;
9867                 return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px');
9868             }
9869         },
9870         
9871         /**
9872          * @property TransparentColor True if the device supports transparent color
9873          * @type {Boolean}
9874          */
9875         {
9876             identity: 'TransparentColor',
9877             fn: function(doc, div, view) {
9878                 view = doc.defaultView;
9879                 return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent');
9880             }
9881         },
9882
9883         /**
9884          * @property ComputedStyle True if the browser supports document.defaultView.getComputedStyle()
9885          * @type {Boolean}
9886          */
9887         {
9888             identity: 'ComputedStyle',
9889             fn: function(doc, div, view) {
9890                 view = doc.defaultView;
9891                 return view && view.getComputedStyle;
9892             }
9893         },
9894         
9895         /**
9896          * @property SVG True if the device supports SVG
9897          * @type {Boolean}
9898          */
9899         {
9900             identity: 'Svg',
9901             fn: function(doc) {
9902                 return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect;
9903             }
9904         },
9905     
9906         /**
9907          * @property Canvas True if the device supports Canvas
9908          * @type {Boolean}
9909          */
9910         {
9911             identity: 'Canvas',
9912             fn: function(doc) {
9913                 return !!doc.createElement('canvas').getContext;
9914             }
9915         },
9916         
9917         /**
9918          * @property VML True if the device supports VML
9919          * @type {Boolean}
9920          */
9921         {
9922             identity: 'Vml',
9923             fn: function(doc) {
9924                 var d = doc.createElement("div");
9925                 d.innerHTML = "<!--[if vml]><br><br><![endif]-->";
9926                 return (d.childNodes.length == 2);
9927             }
9928         },
9929         
9930         /**
9931          * @property Float True if the device supports CSS float
9932          * @type {Boolean}
9933          */
9934         {
9935             identity: 'Float',
9936             fn: function(doc, div) {
9937                 return !!div.lastChild.style.cssFloat;
9938             }
9939         },
9940         
9941         /**
9942          * @property AudioTag True if the device supports the HTML5 audio tag
9943          * @type {Boolean}
9944          */
9945         {
9946             identity: 'AudioTag',
9947             fn: function(doc) {
9948                 return !!doc.createElement('audio').canPlayType;
9949             }
9950         },
9951         
9952         /**
9953          * @property History True if the device supports HTML5 history
9954          * @type {Boolean}
9955          */
9956         {
9957             identity: 'History',
9958             fn: function() {
9959                 return !!(window.history && history.pushState);
9960             }
9961         },
9962         
9963         /**
9964          * @property CSS3DTransform True if the device supports CSS3DTransform
9965          * @type {Boolean}
9966          */
9967         {
9968             identity: 'CSS3DTransform',
9969             fn: function() {
9970                 return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41'));
9971             }
9972         },
9973
9974                 /**
9975          * @property CSS3LinearGradient True if the device supports CSS3 linear gradients
9976          * @type {Boolean}
9977          */
9978         {
9979             identity: 'CSS3LinearGradient',
9980             fn: function(doc, div) {
9981                 var property = 'background-image:',
9982                     webkit   = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))',
9983                     w3c      = 'linear-gradient(left top, black, white)',
9984                     moz      = '-moz-' + w3c,
9985                     options  = [property + webkit, property + w3c, property + moz];
9986                 
9987                 div.style.cssText = options.join(';');
9988                 
9989                 return ("" + div.style.backgroundImage).indexOf('gradient') !== -1;
9990             }
9991         },
9992         
9993         /**
9994          * @property CSS3BorderRadius True if the device supports CSS3 border radius
9995          * @type {Boolean}
9996          */
9997         {
9998             identity: 'CSS3BorderRadius',
9999             fn: function(doc, div) {
10000                 var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'],
10001                     pass = false,
10002                     i;
10003                 for (i = 0; i < domPrefixes.length; i++) {
10004                     if (document.body.style[domPrefixes[i]] !== undefined) {
10005                         return true;
10006                     }
10007                 }
10008                 return pass;
10009             }
10010         },
10011         
10012         /**
10013          * @property GeoLocation True if the device supports GeoLocation
10014          * @type {Boolean}
10015          */
10016         {
10017             identity: 'GeoLocation',
10018             fn: function() {
10019                 return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined');
10020             }
10021         },
10022         /**
10023          * @property MouseEnterLeave True if the browser supports mouseenter and mouseleave events
10024          * @type {Boolean}
10025          */
10026         {
10027             identity: 'MouseEnterLeave',
10028             fn: function(doc, div){
10029                 return ('onmouseenter' in div && 'onmouseleave' in div);
10030             }
10031         },
10032         /**
10033          * @property MouseWheel True if the browser supports the mousewheel event
10034          * @type {Boolean}
10035          */
10036         {
10037             identity: 'MouseWheel',
10038             fn: function(doc, div) {
10039                 return ('onmousewheel' in div);
10040             }
10041         },
10042         /**
10043          * @property Opacity True if the browser supports normal css opacity
10044          * @type {Boolean}
10045          */
10046         {
10047             identity: 'Opacity',
10048             fn: function(doc, div){
10049                 // Not a strict equal comparison in case opacity can be converted to a number.
10050                 if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
10051                     return false;
10052                 }
10053                 div.firstChild.style.cssText = 'opacity:0.73';
10054                 return div.firstChild.style.opacity == '0.73';
10055             }
10056         },
10057         /**
10058          * @property Placeholder True if the browser supports the HTML5 placeholder attribute on inputs
10059          * @type {Boolean}
10060          */
10061         {
10062             identity: 'Placeholder',
10063             fn: function(doc) {
10064                 return 'placeholder' in doc.createElement('input');
10065             }
10066         },
10067         
10068         /**
10069          * @property Direct2DBug True if when asking for an element's dimension via offsetWidth or offsetHeight, 
10070          * getBoundingClientRect, etc. the browser returns the subpixel width rounded to the nearest pixel.
10071          * @type {Boolean}
10072          */
10073         {
10074             identity: 'Direct2DBug',
10075             fn: function() {
10076                 return Ext.isString(document.body.style.msTransformOrigin);
10077             }
10078         },
10079         /**
10080          * @property BoundingClientRect True if the browser supports the getBoundingClientRect method on elements
10081          * @type {Boolean}
10082          */
10083         {
10084             identity: 'BoundingClientRect',
10085             fn: function(doc, div) {
10086                 return Ext.isFunction(div.getBoundingClientRect);
10087             }
10088         },
10089         {
10090             identity: 'IncludePaddingInWidthCalculation',
10091             fn: function(doc, div){
10092                 var el = Ext.get(div.childNodes[1].firstChild);
10093                 return el.getWidth() == 210;
10094             }
10095         },
10096         {
10097             identity: 'IncludePaddingInHeightCalculation',
10098             fn: function(doc, div){
10099                 var el = Ext.get(div.childNodes[1].firstChild);
10100                 return el.getHeight() == 210;
10101             }
10102         },
10103         
10104         /**
10105          * @property ArraySort True if the Array sort native method isn't bugged.
10106          * @type {Boolean}
10107          */
10108         {
10109             identity: 'ArraySort',
10110             fn: function() {
10111                 var a = [1,2,3,4,5].sort(function(){ return 0; });
10112                 return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
10113             }
10114         },
10115         /**
10116          * @property Range True if browser support document.createRange native method.
10117          * @type {Boolean}
10118          */
10119         {
10120             identity: 'Range',
10121             fn: function() {
10122                 return !!document.createRange;
10123             }
10124         },
10125         /**
10126          * @property CreateContextualFragment True if browser support CreateContextualFragment range native methods.
10127          * @type {Boolean}
10128          */
10129         {
10130             identity: 'CreateContextualFragment',
10131             fn: function() {
10132                 var range = Ext.supports.Range ? document.createRange() : false;
10133                 
10134                 return range && !!range.createContextualFragment;
10135             }
10136         }
10137         
10138     ]
10139 };
10140
10141
10142
10143 /*
10144 Ext JS - JavaScript Library
10145 Copyright (c) 2006-2011, Sencha Inc.
10146 All rights reserved.
10147 licensing@sencha.com
10148 */
10149 /**
10150  * @class Ext.core.DomHelper
10151  * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
10152  * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
10153  * from your DOM building code.</p>
10154  *
10155  * <p><b><u>DomHelper element specification object</u></b></p>
10156  * <p>A specification object is used when creating elements. Attributes of this object
10157  * are assumed to be element attributes, except for 4 special attributes:
10158  * <div class="mdetail-params"><ul>
10159  * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
10160  * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
10161  * same kind of element definition objects to be created and appended. These can be nested
10162  * as deep as you want.</div></li>
10163  * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
10164  * This will end up being either the "class" attribute on a HTML fragment or className
10165  * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
10166  * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
10167  * </ul></div></p>
10168  *
10169  * <p><b><u>Insertion methods</u></b></p>
10170  * <p>Commonly used insertion methods:
10171  * <div class="mdetail-params"><ul>
10172  * <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li>
10173  * <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li>
10174  * <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li>
10175  * <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li>
10176  * <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li>
10177  * <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li>
10178  * </ul></div></p>
10179  *
10180  * <p><b><u>Example</u></b></p>
10181  * <p>This is an example, where an unordered list with 3 children items is appended to an existing
10182  * element with id <tt>'my-div'</tt>:<br>
10183  <pre><code>
10184 var dh = Ext.core.DomHelper; // create shorthand alias
10185 // specification object
10186 var spec = {
10187     id: 'my-ul',
10188     tag: 'ul',
10189     cls: 'my-list',
10190     // append children after creating
10191     children: [     // may also specify 'cn' instead of 'children'
10192         {tag: 'li', id: 'item0', html: 'List Item 0'},
10193         {tag: 'li', id: 'item1', html: 'List Item 1'},
10194         {tag: 'li', id: 'item2', html: 'List Item 2'}
10195     ]
10196 };
10197 var list = dh.append(
10198     'my-div', // the context element 'my-div' can either be the id or the actual node
10199     spec      // the specification object
10200 );
10201  </code></pre></p>
10202  * <p>Element creation specification parameters in this class may also be passed as an Array of
10203  * specification objects. This can be used to insert multiple sibling nodes into an existing
10204  * container very efficiently. For example, to add more list items to the example above:<pre><code>
10205 dh.append('my-ul', [
10206     {tag: 'li', id: 'item3', html: 'List Item 3'},
10207     {tag: 'li', id: 'item4', html: 'List Item 4'}
10208 ]);
10209  * </code></pre></p>
10210  *
10211  * <p><b><u>Templating</u></b></p>
10212  * <p>The real power is in the built-in templating. Instead of creating or appending any elements,
10213  * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
10214  * insert new elements. Revisiting the example above, we could utilize templating this time:
10215  * <pre><code>
10216 // create the node
10217 var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
10218 // get template
10219 var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
10220
10221 for(var i = 0; i < 5, i++){
10222     tpl.append(list, [i]); // use template to append to the actual node
10223 }
10224  * </code></pre></p>
10225  * <p>An example using a template:<pre><code>
10226 var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
10227
10228 var tpl = new Ext.core.DomHelper.createTemplate(html);
10229 tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed&#39;s Site"]);
10230 tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin&#39;s Site"]);
10231  * </code></pre></p>
10232  *
10233  * <p>The same example using named parameters:<pre><code>
10234 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
10235
10236 var tpl = new Ext.core.DomHelper.createTemplate(html);
10237 tpl.append('blog-roll', {
10238     id: 'link1',
10239     url: 'http://www.edspencer.net/',
10240     text: "Ed&#39;s Site"
10241 });
10242 tpl.append('blog-roll', {
10243     id: 'link2',
10244     url: 'http://www.dustindiaz.com/',
10245     text: "Dustin&#39;s Site"
10246 });
10247  * </code></pre></p>
10248  *
10249  * <p><b><u>Compiling Templates</u></b></p>
10250  * <p>Templates are applied using regular expressions. The performance is great, but if
10251  * you are adding a bunch of DOM elements using the same template, you can increase
10252  * performance even further by {@link Ext.Template#compile "compiling"} the template.
10253  * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
10254  * broken up at the different variable points and a dynamic function is created and eval'ed.
10255  * The generated function performs string concatenation of these parts and the passed
10256  * variables instead of using regular expressions.
10257  * <pre><code>
10258 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
10259
10260 var tpl = new Ext.core.DomHelper.createTemplate(html);
10261 tpl.compile();
10262
10263 //... use template like normal
10264  * </code></pre></p>
10265  *
10266  * <p><b><u>Performance Boost</u></b></p>
10267  * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
10268  * of DOM can significantly boost performance.</p>
10269  * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
10270  * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
10271  * results in the creation of a text node. Usage:</p>
10272  * <pre><code>
10273 Ext.core.DomHelper.useDom = true; // force it to use DOM; reduces performance
10274  * </code></pre>
10275  * @singleton
10276  */
10277 Ext.ns('Ext.core');
10278 Ext.core.DomHelper = function(){
10279     var tempTableEl = null,
10280         emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
10281         tableRe = /^table|tbody|tr|td$/i,
10282         confRe = /tag|children|cn|html$/i,
10283         tableElRe = /td|tr|tbody/i,
10284         endRe = /end/i,
10285         pub,
10286         // kill repeat to save bytes
10287         afterbegin = 'afterbegin',
10288         afterend = 'afterend',
10289         beforebegin = 'beforebegin',
10290         beforeend = 'beforeend',
10291         ts = '<table>',
10292         te = '</table>',
10293         tbs = ts+'<tbody>',
10294         tbe = '</tbody>'+te,
10295         trs = tbs + '<tr>',
10296         tre = '</tr>'+tbe;
10297
10298     // private
10299     function doInsert(el, o, returnElement, pos, sibling, append){
10300         el = Ext.getDom(el);
10301         var newNode;
10302         if (pub.useDom) {
10303             newNode = createDom(o, null);
10304             if (append) {
10305                 el.appendChild(newNode);
10306             } else {
10307                 (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
10308             }
10309         } else {
10310             newNode = Ext.core.DomHelper.insertHtml(pos, el, Ext.core.DomHelper.createHtml(o));
10311         }
10312         return returnElement ? Ext.get(newNode, true) : newNode;
10313     }
10314     
10315     function createDom(o, parentNode){
10316         var el,
10317             doc = document,
10318             useSet,
10319             attr,
10320             val,
10321             cn;
10322
10323         if (Ext.isArray(o)) {                       // Allow Arrays of siblings to be inserted
10324             el = doc.createDocumentFragment(); // in one shot using a DocumentFragment
10325             for (var i = 0, l = o.length; i < l; i++) {
10326                 createDom(o[i], el);
10327             }
10328         } else if (typeof o == 'string') {         // Allow a string as a child spec.
10329             el = doc.createTextNode(o);
10330         } else {
10331             el = doc.createElement( o.tag || 'div' );
10332             useSet = !!el.setAttribute; // In IE some elements don't have setAttribute
10333             for (attr in o) {
10334                 if(!confRe.test(attr)){
10335                     val = o[attr];
10336                     if(attr == 'cls'){
10337                         el.className = val;
10338                     }else{
10339                         if(useSet){
10340                             el.setAttribute(attr, val);
10341                         }else{
10342                             el[attr] = val;
10343                         }
10344                     }
10345                 }
10346             }
10347             Ext.core.DomHelper.applyStyles(el, o.style);
10348
10349             if ((cn = o.children || o.cn)) {
10350                 createDom(cn, el);
10351             } else if (o.html) {
10352                 el.innerHTML = o.html;
10353             }
10354         }
10355         if(parentNode){
10356            parentNode.appendChild(el);
10357         }
10358         return el;
10359     }
10360
10361     // build as innerHTML where available
10362     function createHtml(o){
10363         var b = '',
10364             attr,
10365             val,
10366             key,
10367             cn,
10368             i;
10369
10370         if(typeof o == "string"){
10371             b = o;
10372         } else if (Ext.isArray(o)) {
10373             for (i=0; i < o.length; i++) {
10374                 if(o[i]) {
10375                     b += createHtml(o[i]);
10376                 }
10377             }
10378         } else {
10379             b += '<' + (o.tag = o.tag || 'div');
10380             for (attr in o) {
10381                 val = o[attr];
10382                 if(!confRe.test(attr)){
10383                     if (typeof val == "object") {
10384                         b += ' ' + attr + '="';
10385                         for (key in val) {
10386                             b += key + ':' + val[key] + ';';
10387                         }
10388                         b += '"';
10389                     }else{
10390                         b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
10391                     }
10392                 }
10393             }
10394             // Now either just close the tag or try to add children and close the tag.
10395             if (emptyTags.test(o.tag)) {
10396                 b += '/>';
10397             } else {
10398                 b += '>';
10399                 if ((cn = o.children || o.cn)) {
10400                     b += createHtml(cn);
10401                 } else if(o.html){
10402                     b += o.html;
10403                 }
10404                 b += '</' + o.tag + '>';
10405             }
10406         }
10407         return b;
10408     }
10409
10410     function ieTable(depth, s, h, e){
10411         tempTableEl.innerHTML = [s, h, e].join('');
10412         var i = -1,
10413             el = tempTableEl,
10414             ns;
10415         while(++i < depth){
10416             el = el.firstChild;
10417         }
10418 //      If the result is multiple siblings, then encapsulate them into one fragment.
10419         ns = el.nextSibling;
10420         if (ns){
10421             var df = document.createDocumentFragment();
10422             while(el){
10423                 ns = el.nextSibling;
10424                 df.appendChild(el);
10425                 el = ns;
10426             }
10427             el = df;
10428         }
10429         return el;
10430     }
10431
10432     /**
10433      * @ignore
10434      * Nasty code for IE's broken table implementation
10435      */
10436     function insertIntoTable(tag, where, el, html) {
10437         var node,
10438             before;
10439
10440         tempTableEl = tempTableEl || document.createElement('div');
10441
10442         if(tag == 'td' && (where == afterbegin || where == beforeend) ||
10443            !tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
10444             return null;
10445         }
10446         before = where == beforebegin ? el :
10447                  where == afterend ? el.nextSibling :
10448                  where == afterbegin ? el.firstChild : null;
10449
10450         if (where == beforebegin || where == afterend) {
10451             el = el.parentNode;
10452         }
10453
10454         if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
10455             node = ieTable(4, trs, html, tre);
10456         } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
10457                    (tag == 'tr' && (where == beforebegin || where == afterend))) {
10458             node = ieTable(3, tbs, html, tbe);
10459         } else {
10460             node = ieTable(2, ts, html, te);
10461         }
10462         el.insertBefore(node, before);
10463         return node;
10464     }
10465     
10466     /**
10467      * @ignore
10468      * Fix for IE9 createContextualFragment missing method
10469      */   
10470     function createContextualFragment(html){
10471         var div = document.createElement("div"),
10472             fragment = document.createDocumentFragment(),
10473             i = 0,
10474             length, childNodes;
10475         
10476         div.innerHTML = html;
10477         childNodes = div.childNodes;
10478         length = childNodes.length;
10479
10480         for (; i < length; i++) {
10481             fragment.appendChild(childNodes[i].cloneNode(true));
10482         }
10483
10484         return fragment;
10485     }
10486     
10487     pub = {
10488         /**
10489          * Returns the markup for the passed Element(s) config.
10490          * @param {Object} o The DOM object spec (and children)
10491          * @return {String}
10492          */
10493         markup : function(o){
10494             return createHtml(o);
10495         },
10496
10497         /**
10498          * Applies a style specification to an element.
10499          * @param {String/HTMLElement} el The element to apply styles to
10500          * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
10501          * a function which returns such a specification.
10502          */
10503         applyStyles : function(el, styles){
10504             if (styles) {
10505                 el = Ext.fly(el);
10506                 if (typeof styles == "function") {
10507                     styles = styles.call();
10508                 }
10509                 if (typeof styles == "string") {
10510                     styles = Ext.core.Element.parseStyles(styles);
10511                 }
10512                 if (typeof styles == "object") {
10513                     el.setStyle(styles);
10514                 }
10515             }
10516         },
10517
10518         /**
10519          * Inserts an HTML fragment into the DOM.
10520          * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
10521          * @param {HTMLElement/TextNode} el The context element
10522          * @param {String} html The HTML fragment
10523          * @return {HTMLElement} The new node
10524          */
10525         insertHtml : function(where, el, html){
10526             var hash = {},
10527                 hashVal,
10528                 range,
10529                 rangeEl,
10530                 setStart,
10531                 frag,
10532                 rs;
10533
10534             where = where.toLowerCase();
10535             // add these here because they are used in both branches of the condition.
10536             hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
10537             hash[afterend] = ['AfterEnd', 'nextSibling'];
10538             
10539             // if IE and context element is an HTMLElement
10540             if (el.insertAdjacentHTML) {
10541                 if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
10542                     return rs;
10543                 }
10544                 
10545                 // add these two to the hash.
10546                 hash[afterbegin] = ['AfterBegin', 'firstChild'];
10547                 hash[beforeend] = ['BeforeEnd', 'lastChild'];
10548                 if ((hashVal = hash[where])) {
10549                     el.insertAdjacentHTML(hashVal[0], html);
10550                     return el[hashVal[1]];
10551                 }
10552             // if (not IE and context element is an HTMLElement) or TextNode
10553             } else {
10554                 // we cannot insert anything inside a textnode so...
10555                 if (Ext.isTextNode(el)) {
10556                     where = where === 'afterbegin' ? 'beforebegin' : where; 
10557                     where = where === 'beforeend' ? 'afterend' : where;
10558                 }
10559                 range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined;
10560                 setStart = 'setStart' + (endRe.test(where) ? 'After' : 'Before');
10561                 if (hash[where]) {
10562                     if (range) {
10563                         range[setStart](el);
10564                         frag = range.createContextualFragment(html);
10565                     } else {
10566                         frag = createContextualFragment(html);
10567                     }
10568                     el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
10569                     return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
10570                 } else {
10571                     rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
10572                     if (el.firstChild) {
10573                         if (range) {
10574                             range[setStart](el[rangeEl]);
10575                             frag = range.createContextualFragment(html);
10576                         } else {
10577                             frag = createContextualFragment(html);
10578                         }
10579                         
10580                         if(where == afterbegin){
10581                             el.insertBefore(frag, el.firstChild);
10582                         }else{
10583                             el.appendChild(frag);
10584                         }
10585                     } else {
10586                         el.innerHTML = html;
10587                     }
10588                     return el[rangeEl];
10589                 }
10590             }
10591             Ext.Error.raise({
10592                 sourceClass: 'Ext.core.DomHelper',
10593                 sourceMethod: 'insertHtml',
10594                 htmlToInsert: html,
10595                 targetElement: el,
10596                 msg: 'Illegal insertion point reached: "' + where + '"'
10597             });
10598         },
10599
10600         /**
10601          * Creates new DOM element(s) and inserts them before el.
10602          * @param {Mixed} el The context element
10603          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
10604          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
10605          * @return {HTMLElement/Ext.core.Element} The new node
10606          */
10607         insertBefore : function(el, o, returnElement){
10608             return doInsert(el, o, returnElement, beforebegin);
10609         },
10610
10611         /**
10612          * Creates new DOM element(s) and inserts them after el.
10613          * @param {Mixed} el The context element
10614          * @param {Object} o The DOM object spec (and children)
10615          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
10616          * @return {HTMLElement/Ext.core.Element} The new node
10617          */
10618         insertAfter : function(el, o, returnElement){
10619             return doInsert(el, o, returnElement, afterend, 'nextSibling');
10620         },
10621
10622         /**
10623          * Creates new DOM element(s) and inserts them as the first child of el.
10624          * @param {Mixed} el The context element
10625          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
10626          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
10627          * @return {HTMLElement/Ext.core.Element} The new node
10628          */
10629         insertFirst : function(el, o, returnElement){
10630             return doInsert(el, o, returnElement, afterbegin, 'firstChild');
10631         },
10632
10633         /**
10634          * Creates new DOM element(s) and appends them to el.
10635          * @param {Mixed} el The context element
10636          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
10637          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
10638          * @return {HTMLElement/Ext.core.Element} The new node
10639          */
10640         append : function(el, o, returnElement){
10641             return doInsert(el, o, returnElement, beforeend, '', true);
10642         },
10643
10644         /**
10645          * Creates new DOM element(s) and overwrites the contents of el with them.
10646          * @param {Mixed} el The context element
10647          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
10648          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
10649          * @return {HTMLElement/Ext.core.Element} The new node
10650          */
10651         overwrite : function(el, o, returnElement){
10652             el = Ext.getDom(el);
10653             el.innerHTML = createHtml(o);
10654             return returnElement ? Ext.get(el.firstChild) : el.firstChild;
10655         },
10656
10657         createHtml : createHtml,
10658         
10659         /**
10660          * Creates new DOM element(s) without inserting them to the document.
10661          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
10662          * @return {HTMLElement} The new uninserted node
10663          */
10664         createDom: createDom,
10665         
10666         /** True to force the use of DOM instead of html fragments @type Boolean */
10667         useDom : false,
10668         
10669         /**
10670          * Creates a new Ext.Template from the DOM object spec.
10671          * @param {Object} o The DOM object spec (and children)
10672          * @return {Ext.Template} The new template
10673          */
10674         createTemplate : function(o){
10675             var html = Ext.core.DomHelper.createHtml(o);
10676             return Ext.create('Ext.Template', html);
10677         }
10678     };
10679     return pub;
10680 }();
10681
10682 /*
10683  * This is code is also distributed under MIT license for use
10684  * with jQuery and prototype JavaScript libraries.
10685  */
10686 /**
10687  * @class Ext.DomQuery
10688 Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in).
10689 <p>
10690 DomQuery supports most of the <a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#selectors">CSS3 selectors spec</a>, along with some custom selectors and basic XPath.</p>
10691
10692 <p>
10693 All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example "div.foo:nth-child(odd)[@foo=bar].bar:first" would be a perfectly valid selector. Node filters are processed in the order in which they appear, which allows you to optimize your queries for your document structure.
10694 </p>
10695 <h4>Element Selectors:</h4>
10696 <ul class="list">
10697     <li> <b>*</b> any element</li>
10698     <li> <b>E</b> an element with the tag E</li>
10699     <li> <b>E F</b> All descendent elements of E that have the tag F</li>
10700     <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
10701     <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
10702     <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
10703 </ul>
10704 <h4>Attribute Selectors:</h4>
10705 <p>The use of &#64; and quotes are optional. For example, div[&#64;foo='bar'] is also a valid attribute selector.</p>
10706 <ul class="list">
10707     <li> <b>E[foo]</b> has an attribute "foo"</li>
10708     <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
10709     <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
10710     <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
10711     <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
10712     <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
10713     <li> <b>E[foo!=bar]</b> attribute "foo" does not equal "bar"</li>
10714 </ul>
10715 <h4>Pseudo Classes:</h4>
10716 <ul class="list">
10717     <li> <b>E:first-child</b> E is the first child of its parent</li>
10718     <li> <b>E:last-child</b> E is the last child of its parent</li>
10719     <li> <b>E:nth-child(<i>n</i>)</b> E is the <i>n</i>th child of its parent (1 based as per the spec)</li>
10720     <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
10721     <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
10722     <li> <b>E:only-child</b> E is the only child of its parent</li>
10723     <li> <b>E:checked</b> E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) </li>
10724     <li> <b>E:first</b> the first E in the resultset</li>
10725     <li> <b>E:last</b> the last E in the resultset</li>
10726     <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
10727     <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
10728     <li> <b>E:even</b> shortcut for :nth-child(even)</li>
10729     <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
10730     <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
10731     <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
10732     <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
10733     <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
10734     <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
10735     <li> <b>E:any(S1|S2|S2)</b> an E element which matches any of the simple selectors S1, S2 or S3//\\</li>
10736 </ul>
10737 <h4>CSS Value Selectors:</h4>
10738 <ul class="list">
10739     <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
10740     <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
10741     <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
10742     <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
10743     <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
10744     <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
10745 </ul>
10746  * @singleton
10747  */
10748 Ext.ns('Ext.core');
10749
10750 Ext.core.DomQuery = Ext.DomQuery = function(){
10751     var cache = {},
10752         simpleCache = {},
10753         valueCache = {},
10754         nonSpace = /\S/,
10755         trimRe = /^\s+|\s+$/g,
10756         tplRe = /\{(\d+)\}/g,
10757         modeRe = /^(\s?[\/>+~]\s?|\s|$)/,
10758         tagTokenRe = /^(#)?([\w-\*]+)/,
10759         nthRe = /(\d*)n\+?(\d*)/,
10760         nthRe2 = /\D/,
10761         // This is for IE MSXML which does not support expandos.
10762     // IE runs the same speed using setAttribute, however FF slows way down
10763     // and Safari completely fails so they need to continue to use expandos.
10764     isIE = window.ActiveXObject ? true : false,
10765     key = 30803;
10766
10767     // this eval is stop the compressor from
10768     // renaming the variable to something shorter
10769     eval("var batch = 30803;");
10770
10771     // Retrieve the child node from a particular
10772     // parent at the specified index.
10773     function child(parent, index){
10774         var i = 0,
10775             n = parent.firstChild;
10776         while(n){
10777             if(n.nodeType == 1){
10778                if(++i == index){
10779                    return n;
10780                }
10781             }
10782             n = n.nextSibling;
10783         }
10784         return null;
10785     }
10786
10787     // retrieve the next element node
10788     function next(n){
10789         while((n = n.nextSibling) && n.nodeType != 1);
10790         return n;
10791     }
10792
10793     // retrieve the previous element node
10794     function prev(n){
10795         while((n = n.previousSibling) && n.nodeType != 1);
10796         return n;
10797     }
10798
10799     // Mark each child node with a nodeIndex skipping and
10800     // removing empty text nodes.
10801     function children(parent){
10802         var n = parent.firstChild,
10803         nodeIndex = -1,
10804         nextNode;
10805         while(n){
10806             nextNode = n.nextSibling;
10807             // clean worthless empty nodes.
10808             if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
10809             parent.removeChild(n);
10810             }else{
10811             // add an expando nodeIndex
10812             n.nodeIndex = ++nodeIndex;
10813             }
10814             n = nextNode;
10815         }
10816         return this;
10817     }
10818
10819
10820     // nodeSet - array of nodes
10821     // cls - CSS Class
10822     function byClassName(nodeSet, cls){
10823         if(!cls){
10824             return nodeSet;
10825         }
10826         var result = [], ri = -1;
10827         for(var i = 0, ci; ci = nodeSet[i]; i++){
10828             if((' '+ci.className+' ').indexOf(cls) != -1){
10829                 result[++ri] = ci;
10830             }
10831         }
10832         return result;
10833     };
10834
10835     function attrValue(n, attr){
10836         // if its an array, use the first node.
10837         if(!n.tagName && typeof n.length != "undefined"){
10838             n = n[0];
10839         }
10840         if(!n){
10841             return null;
10842         }
10843
10844         if(attr == "for"){
10845             return n.htmlFor;
10846         }
10847         if(attr == "class" || attr == "className"){
10848             return n.className;
10849         }
10850         return n.getAttribute(attr) || n[attr];
10851
10852     };
10853
10854
10855     // ns - nodes
10856     // mode - false, /, >, +, ~
10857     // tagName - defaults to "*"
10858     function getNodes(ns, mode, tagName){
10859         var result = [], ri = -1, cs;
10860         if(!ns){
10861             return result;
10862         }
10863         tagName = tagName || "*";
10864         // convert to array
10865         if(typeof ns.getElementsByTagName != "undefined"){
10866             ns = [ns];
10867         }
10868
10869         // no mode specified, grab all elements by tagName
10870         // at any depth
10871         if(!mode){
10872             for(var i = 0, ni; ni = ns[i]; i++){
10873                 cs = ni.getElementsByTagName(tagName);
10874                 for(var j = 0, ci; ci = cs[j]; j++){
10875                     result[++ri] = ci;
10876                 }
10877             }
10878         // Direct Child mode (/ or >)
10879         // E > F or E/F all direct children elements of E that have the tag
10880         } else if(mode == "/" || mode == ">"){
10881             var utag = tagName.toUpperCase();
10882             for(var i = 0, ni, cn; ni = ns[i]; i++){
10883                 cn = ni.childNodes;
10884                 for(var j = 0, cj; cj = cn[j]; j++){
10885                     if(cj.nodeName == utag || cj.nodeName == tagName  || tagName == '*'){
10886                         result[++ri] = cj;
10887                     }
10888                 }
10889             }
10890         // Immediately Preceding mode (+)
10891         // E + F all elements with the tag F that are immediately preceded by an element with the tag E
10892         }else if(mode == "+"){
10893             var utag = tagName.toUpperCase();
10894             for(var i = 0, n; n = ns[i]; i++){
10895                 while((n = n.nextSibling) && n.nodeType != 1);
10896                 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
10897                     result[++ri] = n;
10898                 }
10899             }
10900         // Sibling mode (~)
10901         // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
10902         }else if(mode == "~"){
10903             var utag = tagName.toUpperCase();
10904             for(var i = 0, n; n = ns[i]; i++){
10905                 while((n = n.nextSibling)){
10906                     if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){
10907                         result[++ri] = n;
10908                     }
10909                 }
10910             }
10911         }
10912         return result;
10913     }
10914
10915     function concat(a, b){
10916         if(b.slice){
10917             return a.concat(b);
10918         }
10919         for(var i = 0, l = b.length; i < l; i++){
10920             a[a.length] = b[i];
10921         }
10922         return a;
10923     }
10924
10925     function byTag(cs, tagName){
10926         if(cs.tagName || cs == document){
10927             cs = [cs];
10928         }
10929         if(!tagName){
10930             return cs;
10931         }
10932         var result = [], ri = -1;
10933         tagName = tagName.toLowerCase();
10934         for(var i = 0, ci; ci = cs[i]; i++){
10935             if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){
10936                 result[++ri] = ci;
10937             }
10938         }
10939         return result;
10940     }
10941
10942     function byId(cs, id){
10943         if(cs.tagName || cs == document){
10944             cs = [cs];
10945         }
10946         if(!id){
10947             return cs;
10948         }
10949         var result = [], ri = -1;
10950         for(var i = 0, ci; ci = cs[i]; i++){
10951             if(ci && ci.id == id){
10952                 result[++ri] = ci;
10953                 return result;
10954             }
10955         }
10956         return result;
10957     }
10958
10959     // operators are =, !=, ^=, $=, *=, %=, |= and ~=
10960     // custom can be "{"
10961     function byAttribute(cs, attr, value, op, custom){
10962         var result = [],
10963             ri = -1,
10964             useGetStyle = custom == "{",
10965             fn = Ext.DomQuery.operators[op],
10966             a,
10967             xml,
10968             hasXml;
10969
10970         for(var i = 0, ci; ci = cs[i]; i++){
10971             // skip non-element nodes.
10972             if(ci.nodeType != 1){
10973                 continue;
10974             }
10975             // only need to do this for the first node
10976             if(!hasXml){
10977                 xml = Ext.DomQuery.isXml(ci);
10978                 hasXml = true;
10979             }
10980
10981             // we only need to change the property names if we're dealing with html nodes, not XML
10982             if(!xml){
10983                 if(useGetStyle){
10984                     a = Ext.DomQuery.getStyle(ci, attr);
10985                 } else if (attr == "class" || attr == "className"){
10986                     a = ci.className;
10987                 } else if (attr == "for"){
10988                     a = ci.htmlFor;
10989                 } else if (attr == "href"){
10990                     // getAttribute href bug
10991                     // http://www.glennjones.net/Post/809/getAttributehrefbug.htm
10992                     a = ci.getAttribute("href", 2);
10993                 } else{
10994                     a = ci.getAttribute(attr);
10995                 }
10996             }else{
10997                 a = ci.getAttribute(attr);
10998             }
10999             if((fn && fn(a, value)) || (!fn && a)){
11000                 result[++ri] = ci;
11001             }
11002         }
11003         return result;
11004     }
11005
11006     function byPseudo(cs, name, value){
11007         return Ext.DomQuery.pseudos[name](cs, value);
11008     }
11009
11010     function nodupIEXml(cs){
11011         var d = ++key,
11012             r;
11013         cs[0].setAttribute("_nodup", d);
11014         r = [cs[0]];
11015         for(var i = 1, len = cs.length; i < len; i++){
11016             var c = cs[i];
11017             if(!c.getAttribute("_nodup") != d){
11018                 c.setAttribute("_nodup", d);
11019                 r[r.length] = c;
11020             }
11021         }
11022         for(var i = 0, len = cs.length; i < len; i++){
11023             cs[i].removeAttribute("_nodup");
11024         }
11025         return r;
11026     }
11027
11028     function nodup(cs){
11029         if(!cs){
11030             return [];
11031         }
11032         var len = cs.length, c, i, r = cs, cj, ri = -1;
11033         if(!len || typeof cs.nodeType != "undefined" || len == 1){
11034             return cs;
11035         }
11036         if(isIE && typeof cs[0].selectSingleNode != "undefined"){
11037             return nodupIEXml(cs);
11038         }
11039         var d = ++key;
11040         cs[0]._nodup = d;
11041         for(i = 1; c = cs[i]; i++){
11042             if(c._nodup != d){
11043                 c._nodup = d;
11044             }else{
11045                 r = [];
11046                 for(var j = 0; j < i; j++){
11047                     r[++ri] = cs[j];
11048                 }
11049                 for(j = i+1; cj = cs[j]; j++){
11050                     if(cj._nodup != d){
11051                         cj._nodup = d;
11052                         r[++ri] = cj;
11053                     }
11054                 }
11055                 return r;
11056             }
11057         }
11058         return r;
11059     }
11060
11061     function quickDiffIEXml(c1, c2){
11062         var d = ++key,
11063             r = [];
11064         for(var i = 0, len = c1.length; i < len; i++){
11065             c1[i].setAttribute("_qdiff", d);
11066         }
11067         for(var i = 0, len = c2.length; i < len; i++){
11068             if(c2[i].getAttribute("_qdiff") != d){
11069                 r[r.length] = c2[i];
11070             }
11071         }
11072         for(var i = 0, len = c1.length; i < len; i++){
11073            c1[i].removeAttribute("_qdiff");
11074         }
11075         return r;
11076     }
11077
11078     function quickDiff(c1, c2){
11079         var len1 = c1.length,
11080             d = ++key,
11081             r = [];
11082         if(!len1){
11083             return c2;
11084         }
11085         if(isIE && typeof c1[0].selectSingleNode != "undefined"){
11086             return quickDiffIEXml(c1, c2);
11087         }
11088         for(var i = 0; i < len1; i++){
11089             c1[i]._qdiff = d;
11090         }
11091         for(var i = 0, len = c2.length; i < len; i++){
11092             if(c2[i]._qdiff != d){
11093                 r[r.length] = c2[i];
11094             }
11095         }
11096         return r;
11097     }
11098
11099     function quickId(ns, mode, root, id){
11100         if(ns == root){
11101            var d = root.ownerDocument || root;
11102            return d.getElementById(id);
11103         }
11104         ns = getNodes(ns, mode, "*");
11105         return byId(ns, id);
11106     }
11107
11108     return {
11109         getStyle : function(el, name){
11110             return Ext.fly(el).getStyle(name);
11111         },
11112         /**
11113          * Compiles a selector/xpath query into a reusable function. The returned function
11114          * takes one parameter "root" (optional), which is the context node from where the query should start.
11115          * @param {String} selector The selector/xpath query
11116          * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
11117          * @return {Function}
11118          */
11119         compile : function(path, type){
11120             type = type || "select";
11121
11122             // setup fn preamble
11123             var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
11124                 mode,
11125                 lastPath,
11126                 matchers = Ext.DomQuery.matchers,
11127                 matchersLn = matchers.length,
11128                 modeMatch,
11129                 // accept leading mode switch
11130                 lmode = path.match(modeRe);
11131
11132             if(lmode && lmode[1]){
11133                 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
11134                 path = path.replace(lmode[1], "");
11135             }
11136
11137             // strip leading slashes
11138             while(path.substr(0, 1)=="/"){
11139                 path = path.substr(1);
11140             }
11141
11142             while(path && lastPath != path){
11143                 lastPath = path;
11144                 var tokenMatch = path.match(tagTokenRe);
11145                 if(type == "select"){
11146                     if(tokenMatch){
11147                         // ID Selector
11148                         if(tokenMatch[1] == "#"){
11149                             fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");';
11150                         }else{
11151                             fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");';
11152                         }
11153                         path = path.replace(tokenMatch[0], "");
11154                     }else if(path.substr(0, 1) != '@'){
11155                         fn[fn.length] = 'n = getNodes(n, mode, "*");';
11156                     }
11157                 // type of "simple"
11158                 }else{
11159                     if(tokenMatch){
11160                         if(tokenMatch[1] == "#"){
11161                             fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");';
11162                         }else{
11163                             fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");';
11164                         }
11165                         path = path.replace(tokenMatch[0], "");
11166                     }
11167                 }
11168                 while(!(modeMatch = path.match(modeRe))){
11169                     var matched = false;
11170                     for(var j = 0; j < matchersLn; j++){
11171                         var t = matchers[j];
11172                         var m = path.match(t.re);
11173                         if(m){
11174                             fn[fn.length] = t.select.replace(tplRe, function(x, i){
11175                                 return m[i];
11176                             });
11177                             path = path.replace(m[0], "");
11178                             matched = true;
11179                             break;
11180                         }
11181                     }
11182                     // prevent infinite loop on bad selector
11183                     if(!matched){
11184                         Ext.Error.raise({
11185                             sourceClass: 'Ext.DomQuery',
11186                             sourceMethod: 'compile',
11187                             msg: 'Error parsing selector. Parsing failed at "' + path + '"'
11188                         });
11189                     }
11190                 }
11191                 if(modeMatch[1]){
11192                     fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";';
11193                     path = path.replace(modeMatch[1], "");
11194                 }
11195             }
11196             // close fn out
11197             fn[fn.length] = "return nodup(n);\n}";
11198
11199             // eval fn and return it
11200             eval(fn.join(""));
11201             return f;
11202         },
11203
11204         /**
11205          * Selects a group of elements.
11206          * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
11207          * @param {Node/String} root (optional) The start of the query (defaults to document).
11208          * @return {Array} An Array of DOM elements which match the selector. If there are
11209          * no matches, and empty Array is returned.
11210          */
11211         jsSelect: function(path, root, type){
11212             // set root to doc if not specified.
11213             root = root || document;
11214
11215             if(typeof root == "string"){
11216                 root = document.getElementById(root);
11217             }
11218             var paths = path.split(","),
11219                 results = [];
11220
11221             // loop over each selector
11222             for(var i = 0, len = paths.length; i < len; i++){
11223                 var subPath = paths[i].replace(trimRe, "");
11224                 // compile and place in cache
11225                 if(!cache[subPath]){
11226                     cache[subPath] = Ext.DomQuery.compile(subPath);
11227                     if(!cache[subPath]){
11228                         Ext.Error.raise({
11229                             sourceClass: 'Ext.DomQuery',
11230                             sourceMethod: 'jsSelect',
11231                             msg: subPath + ' is not a valid selector'
11232                         });
11233                     }
11234                 }
11235                 var result = cache[subPath](root);
11236                 if(result && result != document){
11237                     results = results.concat(result);
11238                 }
11239             }
11240
11241             // if there were multiple selectors, make sure dups
11242             // are eliminated
11243             if(paths.length > 1){
11244                 return nodup(results);
11245             }
11246             return results;
11247         },
11248
11249         isXml: function(el) {
11250             var docEl = (el ? el.ownerDocument || el : 0).documentElement;
11251             return docEl ? docEl.nodeName !== "HTML" : false;
11252         },
11253         
11254         select : document.querySelectorAll ? function(path, root, type) {
11255             root = root || document;
11256             if (!Ext.DomQuery.isXml(root)) {
11257             try {
11258                 var cs = root.querySelectorAll(path);
11259                 return Ext.Array.toArray(cs);
11260             }
11261             catch (ex) {}
11262             }
11263             return Ext.DomQuery.jsSelect.call(this, path, root, type);
11264         } : function(path, root, type) {
11265             return Ext.DomQuery.jsSelect.call(this, path, root, type);
11266         },
11267
11268         /**
11269          * Selects a single element.
11270          * @param {String} selector The selector/xpath query
11271          * @param {Node} root (optional) The start of the query (defaults to document).
11272          * @return {Element} The DOM element which matched the selector.
11273          */
11274         selectNode : function(path, root){
11275             return Ext.DomQuery.select(path, root)[0];
11276         },
11277
11278         /**
11279          * Selects the value of a node, optionally replacing null with the defaultValue.
11280          * @param {String} selector The selector/xpath query
11281          * @param {Node} root (optional) The start of the query (defaults to document).
11282          * @param {String} defaultValue
11283          * @return {String}
11284          */
11285         selectValue : function(path, root, defaultValue){
11286             path = path.replace(trimRe, "");
11287             if(!valueCache[path]){
11288                 valueCache[path] = Ext.DomQuery.compile(path, "select");
11289             }
11290             var n = valueCache[path](root), v;
11291             n = n[0] ? n[0] : n;
11292
11293             // overcome a limitation of maximum textnode size
11294             // Rumored to potentially crash IE6 but has not been confirmed.
11295             // http://reference.sitepoint.com/javascript/Node/normalize
11296             // https://developer.mozilla.org/En/DOM/Node.normalize
11297             if (typeof n.normalize == 'function') n.normalize();
11298
11299             v = (n && n.firstChild ? n.firstChild.nodeValue : null);
11300             return ((v === null||v === undefined||v==='') ? defaultValue : v);
11301         },
11302
11303         /**
11304          * Selects the value of a node, parsing integers and floats. Returns the defaultValue, or 0 if none is specified.
11305          * @param {String} selector The selector/xpath query
11306          * @param {Node} root (optional) The start of the query (defaults to document).
11307          * @param {Number} defaultValue
11308          * @return {Number}
11309          */
11310         selectNumber : function(path, root, defaultValue){
11311             var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
11312             return parseFloat(v);
11313         },
11314
11315         /**
11316          * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
11317          * @param {String/HTMLElement/Array} el An element id, element or array of elements
11318          * @param {String} selector The simple selector to test
11319          * @return {Boolean}
11320          */
11321         is : function(el, ss){
11322             if(typeof el == "string"){
11323                 el = document.getElementById(el);
11324             }
11325             var isArray = Ext.isArray(el),
11326                 result = Ext.DomQuery.filter(isArray ? el : [el], ss);
11327             return isArray ? (result.length == el.length) : (result.length > 0);
11328         },
11329
11330         /**
11331          * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
11332          * @param {Array} el An array of elements to filter
11333          * @param {String} selector The simple selector to test
11334          * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
11335          * the selector instead of the ones that match
11336          * @return {Array} An Array of DOM elements which match the selector. If there are
11337          * no matches, and empty Array is returned.
11338          */
11339         filter : function(els, ss, nonMatches){
11340             ss = ss.replace(trimRe, "");
11341             if(!simpleCache[ss]){
11342                 simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
11343             }
11344             var result = simpleCache[ss](els);
11345             return nonMatches ? quickDiff(result, els) : result;
11346         },
11347
11348         /**
11349          * Collection of matching regular expressions and code snippets.
11350          * Each capture group within () will be replace the {} in the select
11351          * statement as specified by their index.
11352          */
11353         matchers : [{
11354                 re: /^\.([\w-]+)/,
11355                 select: 'n = byClassName(n, " {1} ");'
11356             }, {
11357                 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
11358                 select: 'n = byPseudo(n, "{1}", "{2}");'
11359             },{
11360                 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
11361                 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
11362             }, {
11363                 re: /^#([\w-]+)/,
11364                 select: 'n = byId(n, "{1}");'
11365             },{
11366                 re: /^@([\w-]+)/,
11367                 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
11368             }
11369         ],
11370
11371         /**
11372          * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
11373          * New operators can be added as long as the match the format <i>c</i>= where <i>c</i> is any character other than space, &gt; &lt;.
11374          */
11375         operators : {
11376             "=" : function(a, v){
11377                 return a == v;
11378             },
11379             "!=" : function(a, v){
11380                 return a != v;
11381             },
11382             "^=" : function(a, v){
11383                 return a && a.substr(0, v.length) == v;
11384             },
11385             "$=" : function(a, v){
11386                 return a && a.substr(a.length-v.length) == v;
11387             },
11388             "*=" : function(a, v){
11389                 return a && a.indexOf(v) !== -1;
11390             },
11391             "%=" : function(a, v){
11392                 return (a % v) == 0;
11393             },
11394             "|=" : function(a, v){
11395                 return a && (a == v || a.substr(0, v.length+1) == v+'-');
11396             },
11397             "~=" : function(a, v){
11398                 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
11399             }
11400         },
11401
11402         /**
11403 Object hash of "pseudo class" filter functions which are used when filtering selections. 
11404 Each function is passed two parameters:
11405
11406 - **c** : Array
11407     An Array of DOM elements to filter.
11408     
11409 - **v** : String
11410     The argument (if any) supplied in the selector.
11411
11412 A filter function returns an Array of DOM elements which conform to the pseudo class.
11413 In addition to the provided pseudo classes listed above such as `first-child` and `nth-child`,
11414 developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.
11415
11416 For example, to filter `a` elements to only return links to __external__ resources:
11417
11418     Ext.DomQuery.pseudos.external = function(c, v){
11419         var r = [], ri = -1;
11420         for(var i = 0, ci; ci = c[i]; i++){
11421             // Include in result set only if it's a link to an external resource
11422             if(ci.hostname != location.hostname){
11423                 r[++ri] = ci;
11424             }
11425         }
11426         return r;
11427     };
11428
11429 Then external links could be gathered with the following statement:
11430
11431     var externalLinks = Ext.select("a:external");
11432
11433         * @markdown
11434         */
11435         pseudos : {
11436             "first-child" : function(c){
11437                 var r = [], ri = -1, n;
11438                 for(var i = 0, ci; ci = n = c[i]; i++){
11439                     while((n = n.previousSibling) && n.nodeType != 1);
11440                     if(!n){
11441                         r[++ri] = ci;
11442                     }
11443                 }
11444                 return r;
11445             },
11446
11447             "last-child" : function(c){
11448                 var r = [], ri = -1, n;
11449                 for(var i = 0, ci; ci = n = c[i]; i++){
11450                     while((n = n.nextSibling) && n.nodeType != 1);
11451                     if(!n){
11452                         r[++ri] = ci;
11453                     }
11454                 }
11455                 return r;
11456             },
11457
11458             "nth-child" : function(c, a) {
11459                 var r = [], ri = -1,
11460                     m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
11461                     f = (m[1] || 1) - 0, l = m[2] - 0;
11462                 for(var i = 0, n; n = c[i]; i++){
11463                     var pn = n.parentNode;
11464                     if (batch != pn._batch) {
11465                         var j = 0;
11466                         for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
11467                             if(cn.nodeType == 1){
11468                                cn.nodeIndex = ++j;
11469                             }
11470                         }
11471                         pn._batch = batch;
11472                     }
11473                     if (f == 1) {
11474                         if (l == 0 || n.nodeIndex == l){
11475                             r[++ri] = n;
11476                         }
11477                     } else if ((n.nodeIndex + l) % f == 0){
11478                         r[++ri] = n;
11479                     }
11480                 }
11481
11482                 return r;
11483             },
11484
11485             "only-child" : function(c){
11486                 var r = [], ri = -1;;
11487                 for(var i = 0, ci; ci = c[i]; i++){
11488                     if(!prev(ci) && !next(ci)){
11489                         r[++ri] = ci;
11490                     }
11491                 }
11492                 return r;
11493             },
11494
11495             "empty" : function(c){
11496                 var r = [], ri = -1;
11497                 for(var i = 0, ci; ci = c[i]; i++){
11498                     var cns = ci.childNodes, j = 0, cn, empty = true;
11499                     while(cn = cns[j]){
11500                         ++j;
11501                         if(cn.nodeType == 1 || cn.nodeType == 3){
11502                             empty = false;
11503                             break;
11504                         }
11505                     }
11506                     if(empty){
11507                         r[++ri] = ci;
11508                     }
11509                 }
11510                 return r;
11511             },
11512
11513             "contains" : function(c, v){
11514                 var r = [], ri = -1;
11515                 for(var i = 0, ci; ci = c[i]; i++){
11516                     if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
11517                         r[++ri] = ci;
11518                     }
11519                 }
11520                 return r;
11521             },
11522
11523             "nodeValue" : function(c, v){
11524                 var r = [], ri = -1;
11525                 for(var i = 0, ci; ci = c[i]; i++){
11526                     if(ci.firstChild && ci.firstChild.nodeValue == v){
11527                         r[++ri] = ci;
11528                     }
11529                 }
11530                 return r;
11531             },
11532
11533             "checked" : function(c){
11534                 var r = [], ri = -1;
11535                 for(var i = 0, ci; ci = c[i]; i++){
11536                     if(ci.checked == true){
11537                         r[++ri] = ci;
11538                     }
11539                 }
11540                 return r;
11541             },
11542
11543             "not" : function(c, ss){
11544                 return Ext.DomQuery.filter(c, ss, true);
11545             },
11546
11547             "any" : function(c, selectors){
11548                 var ss = selectors.split('|'),
11549                     r = [], ri = -1, s;
11550                 for(var i = 0, ci; ci = c[i]; i++){
11551                     for(var j = 0; s = ss[j]; j++){
11552                         if(Ext.DomQuery.is(ci, s)){
11553                             r[++ri] = ci;
11554                             break;
11555                         }
11556                     }
11557                 }
11558                 return r;
11559             },
11560
11561             "odd" : function(c){
11562                 return this["nth-child"](c, "odd");
11563             },
11564
11565             "even" : function(c){
11566                 return this["nth-child"](c, "even");
11567             },
11568
11569             "nth" : function(c, a){
11570                 return c[a-1] || [];
11571             },
11572
11573             "first" : function(c){
11574                 return c[0] || [];
11575             },
11576
11577             "last" : function(c){
11578                 return c[c.length-1] || [];
11579             },
11580
11581             "has" : function(c, ss){
11582                 var s = Ext.DomQuery.select,
11583                     r = [], ri = -1;
11584                 for(var i = 0, ci; ci = c[i]; i++){
11585                     if(s(ss, ci).length > 0){
11586                         r[++ri] = ci;
11587                     }
11588                 }
11589                 return r;
11590             },
11591
11592             "next" : function(c, ss){
11593                 var is = Ext.DomQuery.is,
11594                     r = [], ri = -1;
11595                 for(var i = 0, ci; ci = c[i]; i++){
11596                     var n = next(ci);
11597                     if(n && is(n, ss)){
11598                         r[++ri] = ci;
11599                     }
11600                 }
11601                 return r;
11602             },
11603
11604             "prev" : function(c, ss){
11605                 var is = Ext.DomQuery.is,
11606                     r = [], ri = -1;
11607                 for(var i = 0, ci; ci = c[i]; i++){
11608                     var n = prev(ci);
11609                     if(n && is(n, ss)){
11610                         r[++ri] = ci;
11611                     }
11612                 }
11613                 return r;
11614             }
11615         }
11616     };
11617 }();
11618
11619 /**
11620  * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Ext.DomQuery#select}
11621  * @param {String} path The selector/xpath query
11622  * @param {Node} root (optional) The start of the query (defaults to document).
11623  * @return {Array}
11624  * @member Ext
11625  * @method query
11626  */
11627 Ext.query = Ext.DomQuery.select;
11628
11629 /**
11630  * @class Ext.core.Element
11631  * <p>Encapsulates a DOM element, adding simple DOM manipulation facilities, normalizing for browser differences.</p>
11632  * <p>All instances of this class inherit the methods of {@link Ext.fx.Anim} making visual effects easily available to all DOM elements.</p>
11633  * <p>Note that the events documented in this class are not Ext events, they encapsulate browser events. To
11634  * access the underlying browser event, see {@link Ext.EventObject#browserEvent}. Some older
11635  * browsers may not support the full range of events. Which events are supported is beyond the control of ExtJs.</p>
11636  * Usage:<br>
11637 <pre><code>
11638 // by id
11639 var el = Ext.get("my-div");
11640
11641 // by DOM element reference
11642 var el = Ext.get(myDivElement);
11643 </code></pre>
11644  * <b>Animations</b><br />
11645  * <p>When an element is manipulated, by default there is no animation.</p>
11646  * <pre><code>
11647 var el = Ext.get("my-div");
11648
11649 // no animation
11650 el.setWidth(100);
11651  * </code></pre>
11652  * <p>Many of the functions for manipulating an element have an optional "animate" parameter.  This
11653  * parameter can be specified as boolean (<tt>true</tt>) for default animation effects.</p>
11654  * <pre><code>
11655 // default animation
11656 el.setWidth(100, true);
11657  * </code></pre>
11658  *
11659  * <p>To configure the effects, an object literal with animation options to use as the Element animation
11660  * configuration object can also be specified. Note that the supported Element animation configuration
11661  * options are a subset of the {@link Ext.fx.Anim} animation options specific to Fx effects.  The supported
11662  * Element animation configuration options are:</p>
11663 <pre>
11664 Option    Default   Description
11665 --------- --------  ---------------------------------------------
11666 {@link Ext.fx.Anim#duration duration}  .35       The duration of the animation in seconds
11667 {@link Ext.fx.Anim#easing easing}    easeOut   The easing method
11668 {@link Ext.fx.Anim#callback callback}  none      A function to execute when the anim completes
11669 {@link Ext.fx.Anim#scope scope}     this      The scope (this) of the callback function
11670 </pre>
11671  *
11672  * <pre><code>
11673 // Element animation options object
11674 var opt = {
11675     {@link Ext.fx.Anim#duration duration}: 1,
11676     {@link Ext.fx.Anim#easing easing}: 'elasticIn',
11677     {@link Ext.fx.Anim#callback callback}: this.foo,
11678     {@link Ext.fx.Anim#scope scope}: this
11679 };
11680 // animation with some options set
11681 el.setWidth(100, opt);
11682  * </code></pre>
11683  * <p>The Element animation object being used for the animation will be set on the options
11684  * object as "anim", which allows you to stop or manipulate the animation. Here is an example:</p>
11685  * <pre><code>
11686 // using the "anim" property to get the Anim object
11687 if(opt.anim.isAnimated()){
11688     opt.anim.stop();
11689 }
11690  * </code></pre>
11691  * <p>Also see the <tt>{@link #animate}</tt> method for another animation technique.</p>
11692  * <p><b> Composite (Collections of) Elements</b></p>
11693  * <p>For working with collections of Elements, see {@link Ext.CompositeElement}</p>
11694  * @constructor Create a new Element directly.
11695  * @param {String/HTMLElement} element
11696  * @param {Boolean} forceNew (optional) By default the constructor checks to see if there is already an instance of this element in the cache and if there is it returns the same instance. This will skip that check (useful for extending this class).
11697  */
11698  (function() {
11699     var DOC = document,
11700         EC = Ext.cache;
11701
11702     Ext.Element = Ext.core.Element = function(element, forceNew) {
11703         var dom = typeof element == "string" ? DOC.getElementById(element) : element,
11704         id;
11705
11706         if (!dom) {
11707             return null;
11708         }
11709
11710         id = dom.id;
11711
11712         if (!forceNew && id && EC[id]) {
11713             // element object already exists
11714             return EC[id].el;
11715         }
11716
11717         /**
11718      * The DOM element
11719      * @type HTMLElement
11720      */
11721         this.dom = dom;
11722
11723         /**
11724      * The DOM element ID
11725      * @type String
11726      */
11727         this.id = id || Ext.id(dom);
11728     };
11729
11730     var DH = Ext.core.DomHelper,
11731     El = Ext.core.Element;
11732
11733
11734     El.prototype = {
11735         /**
11736      * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
11737      * @param {Object} o The object with the attributes
11738      * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
11739      * @return {Ext.core.Element} this
11740      */
11741         set: function(o, useSet) {
11742             var el = this.dom,
11743                 attr,
11744                 val;
11745             useSet = (useSet !== false) && !!el.setAttribute;
11746
11747             for (attr in o) {
11748                 if (o.hasOwnProperty(attr)) {
11749                     val = o[attr];
11750                     if (attr == 'style') {
11751                         DH.applyStyles(el, val);
11752                     } else if (attr == 'cls') {
11753                         el.className = val;
11754                     } else if (useSet) {
11755                         el.setAttribute(attr, val);
11756                     } else {
11757                         el[attr] = val;
11758                     }
11759                 }
11760             }
11761             return this;
11762         },
11763
11764         //  Mouse events
11765         /**
11766      * @event click
11767      * Fires when a mouse click is detected within the element.
11768      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11769      * @param {HtmlElement} t The target of the event.
11770      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11771      */
11772         /**
11773      * @event contextmenu
11774      * Fires when a right click is detected within the element.
11775      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11776      * @param {HtmlElement} t The target of the event.
11777      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11778      */
11779         /**
11780      * @event dblclick
11781      * Fires when a mouse double click is detected within the element.
11782      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11783      * @param {HtmlElement} t The target of the event.
11784      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11785      */
11786         /**
11787      * @event mousedown
11788      * Fires when a mousedown is detected within the element.
11789      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11790      * @param {HtmlElement} t The target of the event.
11791      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11792      */
11793         /**
11794      * @event mouseup
11795      * Fires when a mouseup is detected within the element.
11796      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11797      * @param {HtmlElement} t The target of the event.
11798      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11799      */
11800         /**
11801      * @event mouseover
11802      * Fires when a mouseover is detected within the element.
11803      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11804      * @param {HtmlElement} t The target of the event.
11805      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11806      */
11807         /**
11808      * @event mousemove
11809      * Fires when a mousemove is detected with the element.
11810      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11811      * @param {HtmlElement} t The target of the event.
11812      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11813      */
11814         /**
11815      * @event mouseout
11816      * Fires when a mouseout is detected with the element.
11817      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11818      * @param {HtmlElement} t The target of the event.
11819      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11820      */
11821         /**
11822      * @event mouseenter
11823      * Fires when the mouse enters the element.
11824      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11825      * @param {HtmlElement} t The target of the event.
11826      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11827      */
11828         /**
11829      * @event mouseleave
11830      * Fires when the mouse leaves the element.
11831      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11832      * @param {HtmlElement} t The target of the event.
11833      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11834      */
11835
11836         //  Keyboard events
11837         /**
11838      * @event keypress
11839      * Fires when a keypress is detected within the element.
11840      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11841      * @param {HtmlElement} t The target of the event.
11842      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11843      */
11844         /**
11845      * @event keydown
11846      * Fires when a keydown is detected within the element.
11847      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11848      * @param {HtmlElement} t The target of the event.
11849      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11850      */
11851         /**
11852      * @event keyup
11853      * Fires when a keyup is detected within the element.
11854      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11855      * @param {HtmlElement} t The target of the event.
11856      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11857      */
11858
11859
11860         //  HTML frame/object events
11861         /**
11862      * @event load
11863      * Fires when the user agent finishes loading all content within the element. Only supported by window, frames, objects and images.
11864      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11865      * @param {HtmlElement} t The target of the event.
11866      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11867      */
11868         /**
11869      * @event unload
11870      * Fires when the user agent removes all content from a window or frame. For elements, it fires when the target element or any of its content has been removed.
11871      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11872      * @param {HtmlElement} t The target of the event.
11873      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11874      */
11875         /**
11876      * @event abort
11877      * Fires when an object/image is stopped from loading before completely loaded.
11878      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11879      * @param {HtmlElement} t The target of the event.
11880      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11881      */
11882         /**
11883      * @event error
11884      * Fires when an object/image/frame cannot be loaded properly.
11885      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11886      * @param {HtmlElement} t The target of the event.
11887      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11888      */
11889         /**
11890      * @event resize
11891      * Fires when a document view is resized.
11892      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11893      * @param {HtmlElement} t The target of the event.
11894      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11895      */
11896         /**
11897      * @event scroll
11898      * Fires when a document view is scrolled.
11899      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11900      * @param {HtmlElement} t The target of the event.
11901      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11902      */
11903
11904         //  Form events
11905         /**
11906      * @event select
11907      * Fires when a user selects some text in a text field, including input and textarea.
11908      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11909      * @param {HtmlElement} t The target of the event.
11910      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11911      */
11912         /**
11913      * @event change
11914      * Fires when a control loses the input focus and its value has been modified since gaining focus.
11915      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11916      * @param {HtmlElement} t The target of the event.
11917      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11918      */
11919         /**
11920      * @event submit
11921      * Fires when a form is submitted.
11922      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11923      * @param {HtmlElement} t The target of the event.
11924      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11925      */
11926         /**
11927      * @event reset
11928      * Fires when a form is reset.
11929      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11930      * @param {HtmlElement} t The target of the event.
11931      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11932      */
11933         /**
11934      * @event focus
11935      * Fires when an element receives focus either via the pointing device or by tab navigation.
11936      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11937      * @param {HtmlElement} t The target of the event.
11938      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11939      */
11940         /**
11941      * @event blur
11942      * Fires when an element loses focus either via the pointing device or by tabbing navigation.
11943      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11944      * @param {HtmlElement} t The target of the event.
11945      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11946      */
11947
11948         //  User Interface events
11949         /**
11950      * @event DOMFocusIn
11951      * Where supported. Similar to HTML focus event, but can be applied to any focusable element.
11952      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11953      * @param {HtmlElement} t The target of the event.
11954      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11955      */
11956         /**
11957      * @event DOMFocusOut
11958      * Where supported. Similar to HTML blur event, but can be applied to any focusable element.
11959      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11960      * @param {HtmlElement} t The target of the event.
11961      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11962      */
11963         /**
11964      * @event DOMActivate
11965      * Where supported. Fires when an element is activated, for instance, through a mouse click or a keypress.
11966      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11967      * @param {HtmlElement} t The target of the event.
11968      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11969      */
11970
11971         //  DOM Mutation events
11972         /**
11973      * @event DOMSubtreeModified
11974      * Where supported. Fires when the subtree is modified.
11975      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11976      * @param {HtmlElement} t The target of the event.
11977      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11978      */
11979         /**
11980      * @event DOMNodeInserted
11981      * Where supported. Fires when a node has been added as a child of another node.
11982      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11983      * @param {HtmlElement} t The target of the event.
11984      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11985      */
11986         /**
11987      * @event DOMNodeRemoved
11988      * Where supported. Fires when a descendant node of the element is removed.
11989      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11990      * @param {HtmlElement} t The target of the event.
11991      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11992      */
11993         /**
11994      * @event DOMNodeRemovedFromDocument
11995      * Where supported. Fires when a node is being removed from a document.
11996      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
11997      * @param {HtmlElement} t The target of the event.
11998      * @param {Object} o The options configuration passed to the {@link #addListener} call.
11999      */
12000         /**
12001      * @event DOMNodeInsertedIntoDocument
12002      * Where supported. Fires when a node is being inserted into a document.
12003      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
12004      * @param {HtmlElement} t The target of the event.
12005      * @param {Object} o The options configuration passed to the {@link #addListener} call.
12006      */
12007         /**
12008      * @event DOMAttrModified
12009      * Where supported. Fires when an attribute has been modified.
12010      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
12011      * @param {HtmlElement} t The target of the event.
12012      * @param {Object} o The options configuration passed to the {@link #addListener} call.
12013      */
12014         /**
12015      * @event DOMCharacterDataModified
12016      * Where supported. Fires when the character data has been modified.
12017      * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
12018      * @param {HtmlElement} t The target of the event.
12019      * @param {Object} o The options configuration passed to the {@link #addListener} call.
12020      */
12021
12022         /**
12023      * The default unit to append to CSS values where a unit isn't provided (defaults to px).
12024      * @type String
12025      */
12026         defaultUnit: "px",
12027
12028         /**
12029      * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
12030      * @param {String} selector The simple selector to test
12031      * @return {Boolean} True if this element matches the selector, else false
12032      */
12033         is: function(simpleSelector) {
12034             return Ext.DomQuery.is(this.dom, simpleSelector);
12035         },
12036
12037         /**
12038      * Tries to focus the element. Any exceptions are caught and ignored.
12039      * @param {Number} defer (optional) Milliseconds to defer the focus
12040      * @return {Ext.core.Element} this
12041      */
12042         focus: function(defer,
12043                         /* private */
12044                         dom) {
12045             var me = this;
12046             dom = dom || me.dom;
12047             try {
12048                 if (Number(defer)) {
12049                     Ext.defer(me.focus, defer, null, [null, dom]);
12050                 } else {
12051                     dom.focus();
12052                 }
12053             } catch(e) {}
12054             return me;
12055         },
12056
12057         /**
12058      * Tries to blur the element. Any exceptions are caught and ignored.
12059      * @return {Ext.core.Element} this
12060      */
12061         blur: function() {
12062             try {
12063                 this.dom.blur();
12064             } catch(e) {}
12065             return this;
12066         },
12067
12068         /**
12069      * Returns the value of the "value" attribute
12070      * @param {Boolean} asNumber true to parse the value as a number
12071      * @return {String/Number}
12072      */
12073         getValue: function(asNumber) {
12074             var val = this.dom.value;
12075             return asNumber ? parseInt(val, 10) : val;
12076         },
12077
12078         /**
12079      * Appends an event handler to this element.  The shorthand version {@link #on} is equivalent.
12080      * @param {String} eventName The name of event to handle.
12081      * @param {Function} fn The handler function the event invokes. This function is passed
12082      * the following parameters:<ul>
12083      * <li><b>evt</b> : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
12084      * <li><b>el</b> : HtmlElement<div class="sub-desc">The DOM element which was the target of the event.
12085      * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
12086      * <li><b>o</b> : Object<div class="sub-desc">The options object from the addListener call.</div></li>
12087      * </ul>
12088      * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed.
12089      * <b>If omitted, defaults to this Element.</b>.
12090      * @param {Object} options (optional) An object containing handler configuration properties.
12091      * This may contain any of the following properties:<ul>
12092      * <li><b>scope</b> Object : <div class="sub-desc">The scope (<code><b>this</b></code> reference) in which the handler function is executed.
12093      * <b>If omitted, defaults to this Element.</b></div></li>
12094      * <li><b>delegate</b> String: <div class="sub-desc">A simple selector to filter the target or look for a descendant of the target. See below for additional details.</div></li>
12095      * <li><b>stopEvent</b> Boolean: <div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
12096      * <li><b>preventDefault</b> Boolean: <div class="sub-desc">True to prevent the default action</div></li>
12097      * <li><b>stopPropagation</b> Boolean: <div class="sub-desc">True to prevent event propagation</div></li>
12098      * <li><b>normalized</b> Boolean: <div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
12099      * <li><b>target</b> Ext.core.Element: <div class="sub-desc">Only call the handler if the event was fired on the target Element, <i>not</i> if the event was bubbled up from a child node.</div></li>
12100      * <li><b>delay</b> Number: <div class="sub-desc">The number of milliseconds to delay the invocation of the handler after the event fires.</div></li>
12101      * <li><b>single</b> Boolean: <div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li>
12102      * <li><b>buffer</b> Number: <div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
12103      * by the specified number of milliseconds. If the event fires again within that time, the original
12104      * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
12105      * </ul><br>
12106      * <p>
12107      * <b>Combining Options</b><br>
12108      * In the following examples, the shorthand form {@link #on} is used rather than the more verbose
12109      * addListener.  The two are equivalent.  Using the options argument, it is possible to combine different
12110      * types of listeners:<br>
12111      * <br>
12112      * A delayed, one-time listener that auto stops the event and adds a custom argument (forumId) to the
12113      * options object. The options object is available as the third parameter in the handler function.<div style="margin: 5px 20px 20px;">
12114      * Code:<pre><code>
12115 el.on('click', this.onClick, this, {
12116     single: true,
12117     delay: 100,
12118     stopEvent : true,
12119     forumId: 4
12120 });</code></pre></p>
12121      * <p>
12122      * <b>Attaching multiple handlers in 1 call</b><br>
12123      * The method also allows for a single argument to be passed which is a config object containing properties
12124      * which specify multiple handlers.</p>
12125      * <p>
12126      * Code:<pre><code>
12127 el.on({
12128     'click' : {
12129         fn: this.onClick,
12130         scope: this,
12131         delay: 100
12132     },
12133     'mouseover' : {
12134         fn: this.onMouseOver,
12135         scope: this
12136     },
12137     'mouseout' : {
12138         fn: this.onMouseOut,
12139         scope: this
12140     }
12141 });</code></pre>
12142      * <p>
12143      * Or a shorthand syntax:<br>
12144      * Code:<pre><code></p>
12145 el.on({
12146     'click' : this.onClick,
12147     'mouseover' : this.onMouseOver,
12148     'mouseout' : this.onMouseOut,
12149     scope: this
12150 });
12151      * </code></pre></p>
12152      * <p><b>delegate</b></p>
12153      * <p>This is a configuration option that you can pass along when registering a handler for
12154      * an event to assist with event delegation. Event delegation is a technique that is used to
12155      * reduce memory consumption and prevent exposure to memory-leaks. By registering an event
12156      * for a container element as opposed to each element within a container. By setting this
12157      * configuration option to a simple selector, the target element will be filtered to look for
12158      * a descendant of the target.
12159      * For example:<pre><code>
12160 // using this markup:
12161 &lt;div id='elId'>
12162     &lt;p id='p1'>paragraph one&lt;/p>
12163     &lt;p id='p2' class='clickable'>paragraph two&lt;/p>
12164     &lt;p id='p3'>paragraph three&lt;/p>
12165 &lt;/div>
12166 // utilize event delegation to registering just one handler on the container element:
12167 el = Ext.get('elId');
12168 el.on(
12169     'click',
12170     function(e,t) {
12171         // handle click
12172         console.info(t.id); // 'p2'
12173     },
12174     this,
12175     {
12176         // filter the target element to be a descendant with the class 'clickable'
12177         delegate: '.clickable'
12178     }
12179 );
12180      * </code></pre></p>
12181      * @return {Ext.core.Element} this
12182      */
12183         addListener: function(eventName, fn, scope, options) {
12184             Ext.EventManager.on(this.dom, eventName, fn, scope || this, options);
12185             return this;
12186         },
12187
12188         /**
12189      * Removes an event handler from this element.  The shorthand version {@link #un} is equivalent.
12190      * <b>Note</b>: if a <i>scope</i> was explicitly specified when {@link #addListener adding} the
12191      * listener, the same scope must be specified here.
12192      * Example:
12193      * <pre><code>
12194 el.removeListener('click', this.handlerFn);
12195 // or
12196 el.un('click', this.handlerFn);
12197 </code></pre>
12198      * @param {String} eventName The name of the event from which to remove the handler.
12199      * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
12200      * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
12201      * then this must refer to the same object.
12202      * @return {Ext.core.Element} this
12203      */
12204         removeListener: function(eventName, fn, scope) {
12205             Ext.EventManager.un(this.dom, eventName, fn, scope || this);
12206             return this;
12207         },
12208
12209         /**
12210      * Removes all previous added listeners from this element
12211      * @return {Ext.core.Element} this
12212      */
12213         removeAllListeners: function() {
12214             Ext.EventManager.removeAll(this.dom);
12215             return this;
12216         },
12217
12218         /**
12219          * Recursively removes all previous added listeners from this element and its children
12220          * @return {Ext.core.Element} this
12221          */
12222         purgeAllListeners: function() {
12223             Ext.EventManager.purgeElement(this);
12224             return this;
12225         },
12226
12227         /**
12228          * @private Test if size has a unit, otherwise appends the passed unit string, or the default for this Element.
12229          * @param size {Mixed} The size to set
12230          * @param units {String} The units to append to a numeric size value
12231          */
12232         addUnits: function(size, units) {
12233
12234             // Most common case first: Size is set to a number
12235             if (Ext.isNumber(size)) {
12236                 return size + (units || this.defaultUnit || 'px');
12237             }
12238
12239             // Size set to a value which means "auto"
12240             if (size === "" || size == "auto" || size === undefined || size === null) {
12241                 return size || '';
12242             }
12243
12244             // Otherwise, warn if it's not a valid CSS measurement
12245             if (!unitPattern.test(size)) {
12246                 if (Ext.isDefined(Ext.global.console)) {
12247                     Ext.global.console.warn("Warning, size detected as NaN on Element.addUnits.");
12248                 }
12249                 return size || '';
12250             }
12251             return size;
12252         },
12253
12254         /**
12255          * Tests various css rules/browsers to determine if this element uses a border box
12256          * @return {Boolean}
12257          */
12258         isBorderBox: function() {
12259             return Ext.isBorderBox || noBoxAdjust[(this.dom.tagName || "").toLowerCase()];
12260         },
12261
12262         /**
12263          * <p>Removes this element's dom reference.  Note that event and cache removal is handled at {@link Ext#removeNode Ext.removeNode}</p>
12264          */
12265         remove: function() {
12266             var me = this,
12267             dom = me.dom;
12268
12269             if (dom) {
12270                 delete me.dom;
12271                 Ext.removeNode(dom);
12272             }
12273         },
12274
12275         /**
12276          * Sets up event handlers to call the passed functions when the mouse is moved into and out of the Element.
12277          * @param {Function} overFn The function to call when the mouse enters the Element.
12278          * @param {Function} outFn The function to call when the mouse leaves the Element.
12279          * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the functions are executed. Defaults to the Element's DOM element.
12280          * @param {Object} options (optional) Options for the listener. See {@link Ext.util.Observable#addListener the <tt>options</tt> parameter}.
12281          * @return {Ext.core.Element} this
12282          */
12283         hover: function(overFn, outFn, scope, options) {
12284             var me = this;
12285             me.on('mouseenter', overFn, scope || me.dom, options);
12286             me.on('mouseleave', outFn, scope || me.dom, options);
12287             return me;
12288         },
12289
12290         /**
12291          * Returns true if this element is an ancestor of the passed element
12292          * @param {HTMLElement/String} el The element to check
12293          * @return {Boolean} True if this element is an ancestor of el, else false
12294          */
12295         contains: function(el) {
12296             return ! el ? false: Ext.core.Element.isAncestor(this.dom, el.dom ? el.dom: el);
12297         },
12298
12299         /**
12300          * Returns the value of a namespaced attribute from the element's underlying DOM node.
12301          * @param {String} namespace The namespace in which to look for the attribute
12302          * @param {String} name The attribute name
12303          * @return {String} The attribute value
12304          * @deprecated
12305          */
12306         getAttributeNS: function(ns, name) {
12307             return this.getAttribute(name, ns);
12308         },
12309
12310         /**
12311          * Returns the value of an attribute from the element's underlying DOM node.
12312          * @param {String} name The attribute name
12313          * @param {String} namespace (optional) The namespace in which to look for the attribute
12314          * @return {String} The attribute value
12315          */
12316         getAttribute: (Ext.isIE && !(Ext.isIE9 && document.documentMode === 9)) ?
12317         function(name, ns) {
12318             var d = this.dom,
12319             type;
12320             if(ns) {
12321                 type = typeof d[ns + ":" + name];
12322                 if (type != 'undefined' && type != 'unknown') {
12323                     return d[ns + ":" + name] || null;
12324                 }
12325                 return null;
12326             }
12327             if (name === "for") {
12328                 name = "htmlFor";
12329             }
12330             return d[name] || null;
12331         }: function(name, ns) {
12332             var d = this.dom;
12333             if (ns) {
12334                return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name);
12335             }
12336             return  d.getAttribute(name) || d[name] || null;
12337         },
12338
12339         /**
12340          * Update the innerHTML of this element
12341          * @param {String} html The new HTML
12342          * @return {Ext.core.Element} this
12343          */
12344         update: function(html) {
12345             if (this.dom) {
12346                 this.dom.innerHTML = html;
12347             }
12348             return this;
12349         }
12350     };
12351
12352     var ep = El.prototype;
12353
12354     El.addMethods = function(o) {
12355         Ext.apply(ep, o);
12356     };
12357
12358     /**
12359      * Appends an event handler (shorthand for {@link #addListener}).
12360      * @param {String} eventName The name of event to handle.
12361      * @param {Function} fn The handler function the event invokes.
12362      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function is executed.
12363      * @param {Object} options (optional) An object containing standard {@link #addListener} options
12364      * @member Ext.core.Element
12365      * @method on
12366      */
12367     ep.on = ep.addListener;
12368
12369     /**
12370      * Removes an event handler from this element (see {@link #removeListener} for additional notes).
12371      * @param {String} eventName The name of the event from which to remove the handler.
12372      * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
12373      * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
12374      * then this must refer to the same object.
12375      * @return {Ext.core.Element} this
12376      * @member Ext.core.Element
12377      * @method un
12378      */
12379     ep.un = ep.removeListener;
12380
12381     /**
12382      * Removes all previous added listeners from this element
12383      * @return {Ext.core.Element} this
12384      * @member Ext.core.Element
12385      * @method clearListeners
12386      */
12387     ep.clearListeners = ep.removeAllListeners;
12388
12389     /**
12390      * Removes this element's dom reference.  Note that event and cache removal is handled at {@link Ext#removeNode Ext.removeNode}.
12391      * Alias to {@link #remove}.
12392      * @member Ext.core.Element
12393      * @method destroy
12394      */
12395     ep.destroy = ep.remove;
12396
12397     /**
12398      * true to automatically adjust width and height settings for box-model issues (default to true)
12399      */
12400     ep.autoBoxAdjust = true;
12401
12402     // private
12403     var unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i,
12404     docEl;
12405
12406     /**
12407      * Retrieves Ext.core.Element objects.
12408      * <p><b>This method does not retrieve {@link Ext.Component Component}s.</b> This method
12409      * retrieves Ext.core.Element objects which encapsulate DOM elements. To retrieve a Component by
12410      * its ID, use {@link Ext.ComponentManager#get}.</p>
12411      * <p>Uses simple caching to consistently return the same object. Automatically fixes if an
12412      * object was recreated with the same id via AJAX or DOM.</p>
12413      * @param {Mixed} el The id of the node, a DOM Node or an existing Element.
12414      * @return {Element} The Element object (or null if no matching element was found)
12415      * @static
12416      * @member Ext.core.Element
12417      * @method get
12418      */
12419     El.get = function(el) {
12420         var ex,
12421         elm,
12422         id;
12423         if (!el) {
12424             return null;
12425         }
12426         if (typeof el == "string") {
12427             // element id
12428             if (! (elm = DOC.getElementById(el))) {
12429                 return null;
12430             }
12431             if (EC[el] && EC[el].el) {
12432                 ex = EC[el].el;
12433                 ex.dom = elm;
12434             } else {
12435                 ex = El.addToCache(new El(elm));
12436             }
12437             return ex;
12438         } else if (el.tagName) {
12439             // dom element
12440             if (! (id = el.id)) {
12441                 id = Ext.id(el);
12442             }
12443             if (EC[id] && EC[id].el) {
12444                 ex = EC[id].el;
12445                 ex.dom = el;
12446             } else {
12447                 ex = El.addToCache(new El(el));
12448             }
12449             return ex;
12450         } else if (el instanceof El) {
12451             if (el != docEl) {
12452                 // refresh dom element in case no longer valid,
12453                 // catch case where it hasn't been appended
12454                 // If an el instance is passed, don't pass to getElementById without some kind of id
12455                 if (Ext.isIE && (el.id == undefined || el.id == '')) {
12456                     el.dom = el.dom;
12457                 } else {
12458                     el.dom = DOC.getElementById(el.id) || el.dom;
12459                 }
12460             }
12461             return el;
12462         } else if (el.isComposite) {
12463             return el;
12464         } else if (Ext.isArray(el)) {
12465             return El.select(el);
12466         } else if (el == DOC) {
12467             // create a bogus element object representing the document object
12468             if (!docEl) {
12469                 var f = function() {};
12470                 f.prototype = El.prototype;
12471                 docEl = new f();
12472                 docEl.dom = DOC;
12473             }
12474             return docEl;
12475         }
12476         return null;
12477     };
12478
12479     El.addToCache = function(el, id) {
12480         if (el) {
12481             id = id || el.id;
12482             EC[id] = {
12483                 el: el,
12484                 data: {},
12485                 events: {}
12486             };
12487         }
12488         return el;
12489     };
12490
12491     // private method for getting and setting element data
12492     El.data = function(el, key, value) {
12493         el = El.get(el);
12494         if (!el) {
12495             return null;
12496         }
12497         var c = EC[el.id].data;
12498         if (arguments.length == 2) {
12499             return c[key];
12500         } else {
12501             return (c[key] = value);
12502         }
12503     };
12504
12505     // private
12506     // Garbage collection - uncache elements/purge listeners on orphaned elements
12507     // so we don't hold a reference and cause the browser to retain them
12508     function garbageCollect() {
12509         if (!Ext.enableGarbageCollector) {
12510             clearInterval(El.collectorThreadId);
12511         } else {
12512             var eid,
12513             el,
12514             d,
12515             o;
12516
12517             for (eid in EC) {
12518                 if (!EC.hasOwnProperty(eid)) {
12519                     continue;
12520                 }
12521                 o = EC[eid];
12522                 if (o.skipGarbageCollection) {
12523                     continue;
12524                 }
12525                 el = o.el;
12526                 d = el.dom;
12527                 // -------------------------------------------------------
12528                 // Determining what is garbage:
12529                 // -------------------------------------------------------
12530                 // !d
12531                 // dom node is null, definitely garbage
12532                 // -------------------------------------------------------
12533                 // !d.parentNode
12534                 // no parentNode == direct orphan, definitely garbage
12535                 // -------------------------------------------------------
12536                 // !d.offsetParent && !document.getElementById(eid)
12537                 // display none elements have no offsetParent so we will
12538                 // also try to look it up by it's id. However, check
12539                 // offsetParent first so we don't do unneeded lookups.
12540                 // This enables collection of elements that are not orphans
12541                 // directly, but somewhere up the line they have an orphan
12542                 // parent.
12543                 // -------------------------------------------------------
12544                 if (!d || !d.parentNode || (!d.offsetParent && !DOC.getElementById(eid))) {
12545                     if (d && Ext.enableListenerCollection) {
12546                         Ext.EventManager.removeAll(d);
12547                     }
12548                     delete EC[eid];
12549                 }
12550             }
12551             // Cleanup IE Object leaks
12552             if (Ext.isIE) {
12553                 var t = {};
12554                 for (eid in EC) {
12555                     if (!EC.hasOwnProperty(eid)) {
12556                         continue;
12557                     }
12558                     t[eid] = EC[eid];
12559                 }
12560                 EC = Ext.cache = t;
12561             }
12562         }
12563     }
12564     El.collectorThreadId = setInterval(garbageCollect, 30000);
12565
12566     var flyFn = function() {};
12567     flyFn.prototype = El.prototype;
12568
12569     // dom is optional
12570     El.Flyweight = function(dom) {
12571         this.dom = dom;
12572     };
12573
12574     El.Flyweight.prototype = new flyFn();
12575     El.Flyweight.prototype.isFlyweight = true;
12576     El._flyweights = {};
12577
12578     /**
12579      * <p>Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
12580      * the dom node can be overwritten by other code. Shorthand of {@link Ext.core.Element#fly}</p>
12581      * <p>Use this to make one-time references to DOM elements which are not going to be accessed again either by
12582      * application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link Ext#get Ext.get}
12583      * will be more appropriate to take advantage of the caching provided by the Ext.core.Element class.</p>
12584      * @param {String/HTMLElement} el The dom node or id
12585      * @param {String} named (optional) Allows for creation of named reusable flyweights to prevent conflicts
12586      * (e.g. internally Ext uses "_global")
12587      * @return {Element} The shared Element object (or null if no matching element was found)
12588      * @member Ext.core.Element
12589      * @method fly
12590      */
12591     El.fly = function(el, named) {
12592         var ret = null;
12593         named = named || '_global';
12594         el = Ext.getDom(el);
12595         if (el) {
12596             (El._flyweights[named] = El._flyweights[named] || new El.Flyweight()).dom = el;
12597             ret = El._flyweights[named];
12598         }
12599         return ret;
12600     };
12601
12602     /**
12603      * Retrieves Ext.core.Element objects.
12604      * <p><b>This method does not retrieve {@link Ext.Component Component}s.</b> This method
12605      * retrieves Ext.core.Element objects which encapsulate DOM elements. To retrieve a Component by
12606      * its ID, use {@link Ext.ComponentManager#get}.</p>
12607      * <p>Uses simple caching to consistently return the same object. Automatically fixes if an
12608      * object was recreated with the same id via AJAX or DOM.</p>
12609      * Shorthand of {@link Ext.core.Element#get}
12610      * @param {Mixed} el The id of the node, a DOM Node or an existing Element.
12611      * @return {Element} The Element object (or null if no matching element was found)
12612      * @member Ext
12613      * @method get
12614      */
12615     Ext.get = El.get;
12616
12617     /**
12618      * <p>Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
12619      * the dom node can be overwritten by other code. Shorthand of {@link Ext.core.Element#fly}</p>
12620      * <p>Use this to make one-time references to DOM elements which are not going to be accessed again either by
12621      * application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link Ext#get Ext.get}
12622      * will be more appropriate to take advantage of the caching provided by the Ext.core.Element class.</p>
12623      * @param {String/HTMLElement} el The dom node or id
12624      * @param {String} named (optional) Allows for creation of named reusable flyweights to prevent conflicts
12625      * (e.g. internally Ext uses "_global")
12626      * @return {Element} The shared Element object (or null if no matching element was found)
12627      * @member Ext
12628      * @method fly
12629      */
12630     Ext.fly = El.fly;
12631
12632     // speedy lookup for elements never to box adjust
12633     var noBoxAdjust = Ext.isStrict ? {
12634         select: 1
12635     }: {
12636         input: 1,
12637         select: 1,
12638         textarea: 1
12639     };
12640     if (Ext.isIE || Ext.isGecko) {
12641         noBoxAdjust['button'] = 1;
12642     }
12643 })();
12644
12645 /**
12646  * @class Ext.core.Element
12647  */
12648 Ext.core.Element.addMethods({
12649     /**
12650      * Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
12651      * @param {String} selector The simple selector to test
12652      * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 50 || document.body)
12653      * @param {Boolean} returnEl (optional) True to return a Ext.core.Element object instead of DOM node
12654      * @return {HTMLElement} The matching DOM node (or null if no match was found)
12655      */
12656     findParent : function(simpleSelector, maxDepth, returnEl) {
12657         var p = this.dom,
12658             b = document.body,
12659             depth = 0,
12660             stopEl;
12661
12662         maxDepth = maxDepth || 50;
12663         if (isNaN(maxDepth)) {
12664             stopEl = Ext.getDom(maxDepth);
12665             maxDepth = Number.MAX_VALUE;
12666         }
12667         while (p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl) {
12668             if (Ext.DomQuery.is(p, simpleSelector)) {
12669                 return returnEl ? Ext.get(p) : p;
12670             }
12671             depth++;
12672             p = p.parentNode;
12673         }
12674         return null;
12675     },
12676     
12677     /**
12678      * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
12679      * @param {String} selector The simple selector to test
12680      * @param {Number/Mixed} maxDepth (optional) The max depth to
12681             search as a number or element (defaults to 10 || document.body)
12682      * @param {Boolean} returnEl (optional) True to return a Ext.core.Element object instead of DOM node
12683      * @return {HTMLElement} The matching DOM node (or null if no match was found)
12684      */
12685     findParentNode : function(simpleSelector, maxDepth, returnEl) {
12686         var p = Ext.fly(this.dom.parentNode, '_internal');
12687         return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
12688     },
12689
12690     /**
12691      * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
12692      * This is a shortcut for findParentNode() that always returns an Ext.core.Element.
12693      * @param {String} selector The simple selector to test
12694      * @param {Number/Mixed} maxDepth (optional) The max depth to
12695             search as a number or element (defaults to 10 || document.body)
12696      * @return {Ext.core.Element} The matching DOM node (or null if no match was found)
12697      */
12698     up : function(simpleSelector, maxDepth) {
12699         return this.findParentNode(simpleSelector, maxDepth, true);
12700     },
12701
12702     /**
12703      * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
12704      * @param {String} selector The CSS selector
12705      * @return {CompositeElement/CompositeElement} The composite element
12706      */
12707     select : function(selector) {
12708         return Ext.core.Element.select(selector, false,  this.dom);
12709     },
12710
12711     /**
12712      * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
12713      * @param {String} selector The CSS selector
12714      * @return {Array} An array of the matched nodes
12715      */
12716     query : function(selector) {
12717         return Ext.DomQuery.select(selector, this.dom);
12718     },
12719
12720     /**
12721      * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
12722      * @param {String} selector The CSS selector
12723      * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.core.Element (defaults to false)
12724      * @return {HTMLElement/Ext.core.Element} The child Ext.core.Element (or DOM node if returnDom = true)
12725      */
12726     down : function(selector, returnDom) {
12727         var n = Ext.DomQuery.selectNode(selector, this.dom);
12728         return returnDom ? n : Ext.get(n);
12729     },
12730
12731     /**
12732      * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
12733      * @param {String} selector The CSS selector
12734      * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.core.Element (defaults to false)
12735      * @return {HTMLElement/Ext.core.Element} The child Ext.core.Element (or DOM node if returnDom = true)
12736      */
12737     child : function(selector, returnDom) {
12738         var node,
12739             me = this,
12740             id;
12741         id = Ext.get(me).id;
12742         // Escape . or :
12743         id = id.replace(/[\.:]/g, "\\$0");
12744         node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom);
12745         return returnDom ? node : Ext.get(node);
12746     },
12747
12748      /**
12749      * Gets the parent node for this element, optionally chaining up trying to match a selector
12750      * @param {String} selector (optional) Find a parent node that matches the passed simple selector
12751      * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.core.Element
12752      * @return {Ext.core.Element/HTMLElement} The parent node or null
12753      */
12754     parent : function(selector, returnDom) {
12755         return this.matchNode('parentNode', 'parentNode', selector, returnDom);
12756     },
12757
12758      /**
12759      * Gets the next sibling, skipping text nodes
12760      * @param {String} selector (optional) Find the next sibling that matches the passed simple selector
12761      * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.core.Element
12762      * @return {Ext.core.Element/HTMLElement} The next sibling or null
12763      */
12764     next : function(selector, returnDom) {
12765         return this.matchNode('nextSibling', 'nextSibling', selector, returnDom);
12766     },
12767
12768     /**
12769      * Gets the previous sibling, skipping text nodes
12770      * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector
12771      * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.core.Element
12772      * @return {Ext.core.Element/HTMLElement} The previous sibling or null
12773      */
12774     prev : function(selector, returnDom) {
12775         return this.matchNode('previousSibling', 'previousSibling', selector, returnDom);
12776     },
12777
12778
12779     /**
12780      * Gets the first child, skipping text nodes
12781      * @param {String} selector (optional) Find the next sibling that matches the passed simple selector
12782      * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.core.Element
12783      * @return {Ext.core.Element/HTMLElement} The first child or null
12784      */
12785     first : function(selector, returnDom) {
12786         return this.matchNode('nextSibling', 'firstChild', selector, returnDom);
12787     },
12788
12789     /**
12790      * Gets the last child, skipping text nodes
12791      * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector
12792      * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.core.Element
12793      * @return {Ext.core.Element/HTMLElement} The last child or null
12794      */
12795     last : function(selector, returnDom) {
12796         return this.matchNode('previousSibling', 'lastChild', selector, returnDom);
12797     },
12798
12799     matchNode : function(dir, start, selector, returnDom) {
12800         if (!this.dom) {
12801             return null;
12802         }
12803         
12804         var n = this.dom[start];
12805         while (n) {
12806             if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) {
12807                 return !returnDom ? Ext.get(n) : n;
12808             }
12809             n = n[dir];
12810         }
12811         return null;
12812     }
12813 });
12814
12815 /**
12816  * @class Ext.core.Element
12817  */
12818 Ext.core.Element.addMethods({
12819     /**
12820      * Appends the passed element(s) to this element
12821      * @param {String/HTMLElement/Array/Element/CompositeElement} el
12822      * @return {Ext.core.Element} this
12823      */
12824     appendChild : function(el) {
12825         return Ext.get(el).appendTo(this);
12826     },
12827
12828     /**
12829      * Appends this element to the passed element
12830      * @param {Mixed} el The new parent element
12831      * @return {Ext.core.Element} this
12832      */
12833     appendTo : function(el) {
12834         Ext.getDom(el).appendChild(this.dom);
12835         return this;
12836     },
12837
12838     /**
12839      * Inserts this element before the passed element in the DOM
12840      * @param {Mixed} el The element before which this element will be inserted
12841      * @return {Ext.core.Element} this
12842      */
12843     insertBefore : function(el) {
12844         el = Ext.getDom(el);
12845         el.parentNode.insertBefore(this.dom, el);
12846         return this;
12847     },
12848
12849     /**
12850      * Inserts this element after the passed element in the DOM
12851      * @param {Mixed} el The element to insert after
12852      * @return {Ext.core.Element} this
12853      */
12854     insertAfter : function(el) {
12855         el = Ext.getDom(el);
12856         el.parentNode.insertBefore(this.dom, el.nextSibling);
12857         return this;
12858     },
12859
12860     /**
12861      * Inserts (or creates) an element (or DomHelper config) as the first child of this element
12862      * @param {Mixed/Object} el The id or element to insert or a DomHelper config to create and insert
12863      * @return {Ext.core.Element} The new child
12864      */
12865     insertFirst : function(el, returnDom) {
12866         el = el || {};
12867         if (el.nodeType || el.dom || typeof el == 'string') { // element
12868             el = Ext.getDom(el);
12869             this.dom.insertBefore(el, this.dom.firstChild);
12870             return !returnDom ? Ext.get(el) : el;
12871         }
12872         else { // dh config
12873             return this.createChild(el, this.dom.firstChild, returnDom);
12874         }
12875     },
12876
12877     /**
12878      * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
12879      * @param {Mixed/Object/Array} el The id, element to insert or a DomHelper config to create and insert *or* an array of any of those.
12880      * @param {String} where (optional) 'before' or 'after' defaults to before
12881      * @param {Boolean} returnDom (optional) True to return the .;ll;l,raw DOM element instead of Ext.core.Element
12882      * @return {Ext.core.Element} The inserted Element. If an array is passed, the last inserted element is returned.
12883      */
12884     insertSibling: function(el, where, returnDom){
12885         var me = this, rt,
12886         isAfter = (where || 'before').toLowerCase() == 'after',
12887         insertEl;
12888
12889         if(Ext.isArray(el)){
12890             insertEl = me;
12891             Ext.each(el, function(e) {
12892                 rt = Ext.fly(insertEl, '_internal').insertSibling(e, where, returnDom);
12893                 if(isAfter){
12894                     insertEl = rt;
12895                 }
12896             });
12897             return rt;
12898         }
12899
12900         el = el || {};
12901
12902         if(el.nodeType || el.dom){
12903             rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom);
12904             if (!returnDom) {
12905                 rt = Ext.get(rt);
12906             }
12907         }else{
12908             if (isAfter && !me.dom.nextSibling) {
12909                 rt = Ext.core.DomHelper.append(me.dom.parentNode, el, !returnDom);
12910             } else {
12911                 rt = Ext.core.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom);
12912             }
12913         }
12914         return rt;
12915     },
12916
12917     /**
12918      * Replaces the passed element with this element
12919      * @param {Mixed} el The element to replace
12920      * @return {Ext.core.Element} this
12921      */
12922     replace : function(el) {
12923         el = Ext.get(el);
12924         this.insertBefore(el);
12925         el.remove();
12926         return this;
12927     },
12928     
12929     /**
12930      * Replaces this element with the passed element
12931      * @param {Mixed/Object} el The new element or a DomHelper config of an element to create
12932      * @return {Ext.core.Element} this
12933      */
12934     replaceWith: function(el){
12935         var me = this;
12936             
12937         if(el.nodeType || el.dom || typeof el == 'string'){
12938             el = Ext.get(el);
12939             me.dom.parentNode.insertBefore(el, me.dom);
12940         }else{
12941             el = Ext.core.DomHelper.insertBefore(me.dom, el);
12942         }
12943         
12944         delete Ext.cache[me.id];
12945         Ext.removeNode(me.dom);      
12946         me.id = Ext.id(me.dom = el);
12947         Ext.core.Element.addToCache(me.isFlyweight ? new Ext.core.Element(me.dom) : me);     
12948         return me;
12949     },
12950     
12951     /**
12952      * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
12953      * @param {Object} config DomHelper element config object.  If no tag is specified (e.g., {tag:'input'}) then a div will be
12954      * automatically generated with the specified attributes.
12955      * @param {HTMLElement} insertBefore (optional) a child element of this element
12956      * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
12957      * @return {Ext.core.Element} The new child element
12958      */
12959     createChild : function(config, insertBefore, returnDom) {
12960         config = config || {tag:'div'};
12961         if (insertBefore) {
12962             return Ext.core.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
12963         }
12964         else {
12965             return Ext.core.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config,  returnDom !== true);
12966         }
12967     },
12968
12969     /**
12970      * Creates and wraps this element with another element
12971      * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
12972      * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Ext.core.Element
12973      * @return {HTMLElement/Element} The newly created wrapper element
12974      */
12975     wrap : function(config, returnDom) {
12976         var newEl = Ext.core.DomHelper.insertBefore(this.dom, config || {tag: "div"}, !returnDom),
12977             d = newEl.dom || newEl;
12978
12979         d.appendChild(this.dom);
12980         return newEl;
12981     },
12982
12983     /**
12984      * Inserts an html fragment into this element
12985      * @param {String} where Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
12986      * @param {String} html The HTML fragment
12987      * @param {Boolean} returnEl (optional) True to return an Ext.core.Element (defaults to false)
12988      * @return {HTMLElement/Ext.core.Element} The inserted node (or nearest related if more than 1 inserted)
12989      */
12990     insertHtml : function(where, html, returnEl) {
12991         var el = Ext.core.DomHelper.insertHtml(where, this.dom, html);
12992         return returnEl ? Ext.get(el) : el;
12993     }
12994 });
12995
12996 /**
12997  * @class Ext.core.Element
12998  */
12999 (function(){
13000     Ext.core.Element.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>';
13001     // local style camelizing for speed
13002     var supports = Ext.supports,
13003         view = document.defaultView,
13004         opacityRe = /alpha\(opacity=(.*)\)/i,
13005         trimRe = /^\s+|\s+$/g,
13006         spacesRe = /\s+/,
13007         wordsRe = /\w/g,
13008         adjustDirect2DTableRe = /table-row|table-.*-group/,
13009         INTERNAL = '_internal',
13010         PADDING = 'padding',
13011         MARGIN = 'margin',
13012         BORDER = 'border',
13013         LEFT = '-left',
13014         RIGHT = '-right',
13015         TOP = '-top',
13016         BOTTOM = '-bottom',
13017         WIDTH = '-width',
13018         MATH = Math,
13019         HIDDEN = 'hidden',
13020         ISCLIPPED = 'isClipped',
13021         OVERFLOW = 'overflow',
13022         OVERFLOWX = 'overflow-x',
13023         OVERFLOWY = 'overflow-y',
13024         ORIGINALCLIP = 'originalClip',
13025         // special markup used throughout Ext when box wrapping elements
13026         borders = {l: BORDER + LEFT + WIDTH, r: BORDER + RIGHT + WIDTH, t: BORDER + TOP + WIDTH, b: BORDER + BOTTOM + WIDTH},
13027         paddings = {l: PADDING + LEFT, r: PADDING + RIGHT, t: PADDING + TOP, b: PADDING + BOTTOM},
13028         margins = {l: MARGIN + LEFT, r: MARGIN + RIGHT, t: MARGIN + TOP, b: MARGIN + BOTTOM},
13029         data = Ext.core.Element.data;
13030
13031     Ext.override(Ext.core.Element, {
13032         
13033         /**
13034          * TODO: Look at this
13035          */
13036         // private  ==> used by Fx
13037         adjustWidth : function(width) {
13038             var me = this,
13039                 isNum = (typeof width == 'number');
13040                 
13041             if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
13042                width -= (me.getBorderWidth("lr") + me.getPadding("lr"));
13043             }
13044             return (isNum && width < 0) ? 0 : width;
13045         },
13046
13047         // private   ==> used by Fx
13048         adjustHeight : function(height) {
13049             var me = this,
13050                 isNum = (typeof height == "number");
13051                 
13052             if(isNum && me.autoBoxAdjust && !me.isBorderBox()){
13053                height -= (me.getBorderWidth("tb") + me.getPadding("tb"));
13054             }
13055             return (isNum && height < 0) ? 0 : height;
13056         },
13057
13058
13059         /**
13060          * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
13061          * @param {String/Array} className The CSS classes to add separated by space, or an array of classes
13062          * @return {Ext.core.Element} this
13063          */
13064         addCls : function(className){
13065             var me = this,
13066                 cls = [],
13067                 space = ((me.dom.className.replace(trimRe, '') == '') ? "" : " "),
13068                 i, len, v;
13069             if (!Ext.isDefined(className)) {
13070                 return me;
13071             }
13072             // Separate case is for speed
13073             if (!Ext.isArray(className)) {
13074                 if (typeof className === 'string') {
13075                     className = className.replace(trimRe, '').split(spacesRe);
13076                     if (className.length === 1) {
13077                         className = className[0];
13078                         if (!me.hasCls(className)) {
13079                             me.dom.className += space + className;
13080                         }
13081                     } else {
13082                         this.addCls(className);
13083                     }
13084                 }
13085             } else {
13086                 for (i = 0, len = className.length; i < len; i++) {
13087                     v = className[i];
13088                     if (typeof v == 'string' && (' ' + me.dom.className + ' ').indexOf(' ' + v + ' ') == -1) {
13089                         cls.push(v);
13090                     }
13091                 }
13092                 if (cls.length) {
13093                     me.dom.className += space + cls.join(" ");
13094                 }
13095             }
13096             return me;
13097         },
13098
13099         /**
13100          * Removes one or more CSS classes from the element.
13101          * @param {String/Array} className The CSS classes to remove separated by space, or an array of classes
13102          * @return {Ext.core.Element} this
13103          */
13104         removeCls : function(className){
13105             var me = this,
13106                 i, idx, len, cls, elClasses;
13107             if (!Ext.isDefined(className)) {
13108                 return me;
13109             }
13110             if (!Ext.isArray(className)){
13111                 className = className.replace(trimRe, '').split(spacesRe);
13112             }
13113             if (me.dom && me.dom.className) {
13114                 elClasses = me.dom.className.replace(trimRe, '').split(spacesRe);
13115                 for (i = 0, len = className.length; i < len; i++) {
13116                     cls = className[i];
13117                     if (typeof cls == 'string') {
13118                         cls = cls.replace(trimRe, '');
13119                         idx = Ext.Array.indexOf(elClasses, cls);
13120                         if (idx != -1) {
13121                             elClasses.splice(idx, 1);
13122                         }
13123                     }
13124                 }
13125                 me.dom.className = elClasses.join(" ");
13126             }
13127             return me;
13128         },
13129
13130         /**
13131          * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
13132          * @param {String/Array} className The CSS class to add, or an array of classes
13133          * @return {Ext.core.Element} this
13134          */
13135         radioCls : function(className){
13136             var cn = this.dom.parentNode.childNodes,
13137                 v, i, len;
13138             className = Ext.isArray(className) ? className : [className];
13139             for (i = 0, len = cn.length; i < len; i++) {
13140                 v = cn[i];
13141                 if (v && v.nodeType == 1) {
13142                     Ext.fly(v, '_internal').removeCls(className);
13143                 }
13144             }
13145             return this.addCls(className);
13146         },
13147
13148         /**
13149          * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
13150          * @param {String} className The CSS class to toggle
13151          * @return {Ext.core.Element} this
13152          */
13153         toggleCls : Ext.supports.ClassList ?
13154             function(className) {
13155                 this.dom.classList.toggle(Ext.String.trim(className));
13156                 return this;
13157             } :
13158             function(className) {
13159                 return this.hasCls(className) ? this.removeCls(className) : this.addCls(className);
13160             },
13161
13162         /**
13163          * Checks if the specified CSS class exists on this element's DOM node.
13164          * @param {String} className The CSS class to check for
13165          * @return {Boolean} True if the class exists, else false
13166          */
13167         hasCls : Ext.supports.ClassList ?
13168             function(className) {
13169                 if (!className) {
13170                     return false;
13171                 }
13172                 className = className.split(spacesRe);
13173                 var ln = className.length,
13174                     i = 0;
13175                 for (; i < ln; i++) {
13176                     if (className[i] && this.dom.classList.contains(className[i])) {
13177                         return true;
13178                     }
13179                 }
13180                 return false;
13181             } :
13182             function(className){
13183                 return className && (' ' + this.dom.className + ' ').indexOf(' ' + className + ' ') != -1;
13184             },
13185
13186         /**
13187          * Replaces a CSS class on the element with another.  If the old name does not exist, the new name will simply be added.
13188          * @param {String} oldClassName The CSS class to replace
13189          * @param {String} newClassName The replacement CSS class
13190          * @return {Ext.core.Element} this
13191          */
13192         replaceCls : function(oldClassName, newClassName){
13193             return this.removeCls(oldClassName).addCls(newClassName);
13194         },
13195
13196         isStyle : function(style, val) {
13197             return this.getStyle(style) == val;
13198         },
13199
13200         /**
13201          * Normalizes currentStyle and computedStyle.
13202          * @param {String} property The style property whose value is returned.
13203          * @return {String} The current value of the style property for this element.
13204          */
13205         getStyle : function(){
13206             return view && view.getComputedStyle ?
13207                 function(prop){
13208                     var el = this.dom,
13209                         v, cs, out, display;
13210
13211                     if(el == document){
13212                         return null;
13213                     }
13214                     prop = Ext.core.Element.normalize(prop);
13215                     out = (v = el.style[prop]) ? v :
13216                            (cs = view.getComputedStyle(el, "")) ? cs[prop] : null;
13217                            
13218                     // Ignore cases when the margin is correctly reported as 0, the bug only shows
13219                     // numbers larger.
13220                     if(prop == 'marginRight' && out != '0px' && !supports.RightMargin){
13221                         display = this.getStyle('display');
13222                         el.style.display = 'inline-block';
13223                         out = view.getComputedStyle(el, '').marginRight;
13224                         el.style.display = display;
13225                     }
13226                     
13227                     if(prop == 'backgroundColor' && out == 'rgba(0, 0, 0, 0)' && !supports.TransparentColor){
13228                         out = 'transparent';
13229                     }
13230                     return out;
13231                 } :
13232                 function(prop){
13233                     var el = this.dom,
13234                         m, cs;
13235
13236                     if (el == document) {
13237                         return null;
13238                     }
13239                     
13240                     if (prop == 'opacity') {
13241                         if (el.style.filter.match) {
13242                             m = el.style.filter.match(opacityRe);
13243                             if(m){
13244                                 var fv = parseFloat(m[1]);
13245                                 if(!isNaN(fv)){
13246                                     return fv ? fv / 100 : 0;
13247                                 }
13248                             }
13249                         }
13250                         return 1;
13251                     }
13252                     prop = Ext.core.Element.normalize(prop);
13253                     return el.style[prop] || ((cs = el.currentStyle) ? cs[prop] : null);
13254                 };
13255         }(),
13256
13257         /**
13258          * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
13259          * are convert to standard 6 digit hex color.
13260          * @param {String} attr The css attribute
13261          * @param {String} defaultValue The default value to use when a valid color isn't found
13262          * @param {String} prefix (optional) defaults to #. Use an empty string when working with
13263          * color anims.
13264          */
13265         getColor : function(attr, defaultValue, prefix){
13266             var v = this.getStyle(attr),
13267                 color = prefix || prefix === '' ? prefix : '#',
13268                 h;
13269
13270             if(!v || (/transparent|inherit/.test(v))) {
13271                 return defaultValue;
13272             }
13273             if(/^r/.test(v)){
13274                 Ext.each(v.slice(4, v.length -1).split(','), function(s){
13275                     h = parseInt(s, 10);
13276                     color += (h < 16 ? '0' : '') + h.toString(16);
13277                 });
13278             }else{
13279                 v = v.replace('#', '');
13280                 color += v.length == 3 ? v.replace(/^(\w)(\w)(\w)$/, '$1$1$2$2$3$3') : v;
13281             }
13282             return(color.length > 5 ? color.toLowerCase() : defaultValue);
13283         },
13284
13285         /**
13286          * Wrapper for setting style properties, also takes single object parameter of multiple styles.
13287          * @param {String/Object} property The style property to be set, or an object of multiple styles.
13288          * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
13289          * @return {Ext.core.Element} this
13290          */
13291         setStyle : function(prop, value){
13292             var me = this,
13293                 tmp, style;
13294
13295             if (!me.dom) {
13296                 return me;
13297             }
13298
13299             if (!Ext.isObject(prop)) {
13300                 tmp = {};
13301                 tmp[prop] = value;
13302                 prop = tmp;
13303             }
13304             for (style in prop) {
13305                 if (prop.hasOwnProperty(style)) {
13306                     value = Ext.value(prop[style], '');
13307                     if (style == 'opacity') {
13308                         me.setOpacity(value);
13309                     }
13310                     else {
13311                         me.dom.style[Ext.core.Element.normalize(style)] = value;
13312                     }
13313                 }
13314             }
13315             return me;
13316         },
13317
13318         /**
13319          * Set the opacity of the element
13320          * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
13321          * @param {Boolean/Object} animate (optional) a standard Element animation config object or <tt>true</tt> for
13322          * the default animation (<tt>{duration: .35, easing: 'easeIn'}</tt>)
13323          * @return {Ext.core.Element} this
13324          */
13325         setOpacity: function(opacity, animate) {
13326             var me = this,
13327                 dom = me.dom,
13328                 val,
13329                 style;
13330
13331             if (!me.dom) {
13332                 return me;
13333             }
13334
13335             style = me.dom.style;
13336
13337             if (!animate || !me.anim) {
13338                 if (!Ext.supports.Opacity) {
13339                     opacity = opacity < 1 ? 'alpha(opacity=' + opacity * 100 + ')': '';
13340                     val = style.filter.replace(opacityRe, '').replace(trimRe, '');
13341
13342                     style.zoom = 1;
13343                     style.filter = val + (val.length > 0 ? ' ': '') + opacity;
13344                 }
13345                 else {
13346                     style.opacity = opacity;
13347                 }
13348             }
13349             else {
13350                 if (!Ext.isObject(animate)) {
13351                     animate = {
13352                         duration: 350,
13353                         easing: 'ease-in'
13354                     };
13355                 }
13356                 me.animate(Ext.applyIf({
13357                     to: {
13358                         opacity: opacity
13359                     }
13360                 },
13361                 animate));
13362             }
13363             return me;
13364         },
13365
13366
13367         /**
13368          * Clears any opacity settings from this element. Required in some cases for IE.
13369          * @return {Ext.core.Element} this
13370          */
13371         clearOpacity : function(){
13372             var style = this.dom.style;
13373             if(!Ext.supports.Opacity){
13374                 if(!Ext.isEmpty(style.filter)){
13375                     style.filter = style.filter.replace(opacityRe, '').replace(trimRe, '');
13376                 }
13377             }else{
13378                 style.opacity = style['-moz-opacity'] = style['-khtml-opacity'] = '';
13379             }
13380             return this;
13381         },
13382         
13383         /**
13384          * @private
13385          * Returns 1 if the browser returns the subpixel dimension rounded to the lowest pixel.
13386          * @return {Number} 0 or 1 
13387          */
13388         adjustDirect2DDimension: function(dimension) {
13389             var me = this,
13390                 dom = me.dom,
13391                 display = me.getStyle('display'),
13392                 inlineDisplay = dom.style['display'],
13393                 inlinePosition = dom.style['position'],
13394                 originIndex = dimension === 'width' ? 0 : 1,
13395                 floating;
13396                 
13397             if (display === 'inline') {
13398                 dom.style['display'] = 'inline-block';
13399             }
13400
13401             dom.style['position'] = display.match(adjustDirect2DTableRe) ? 'absolute' : 'static';
13402
13403             // floating will contain digits that appears after the decimal point
13404             // if height or width are set to auto we fallback to msTransformOrigin calculation
13405             floating = (parseFloat(me.getStyle(dimension)) || parseFloat(dom.currentStyle.msTransformOrigin.split(' ')[originIndex]) * 2) % 1;
13406             
13407             dom.style['position'] = inlinePosition;
13408             
13409             if (display === 'inline') {
13410                 dom.style['display'] = inlineDisplay;
13411             }
13412
13413             return floating;
13414         },
13415         
13416         /**
13417          * Returns the offset height of the element
13418          * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
13419          * @return {Number} The element's height
13420          */
13421         getHeight: function(contentHeight, preciseHeight) {
13422             var me = this,
13423                 dom = me.dom,
13424                 hidden = Ext.isIE && me.isStyle('display', 'none'),
13425                 height, overflow, style, floating;
13426
13427             // IE Quirks mode acts more like a max-size measurement unless overflow is hidden during measurement.
13428             // We will put the overflow back to it's original value when we are done measuring.
13429             if (Ext.isIEQuirks) {
13430                 style = dom.style;
13431                 overflow = style.overflow;
13432                 me.setStyle({ overflow: 'hidden'});
13433             }
13434
13435             height = dom.offsetHeight;
13436
13437             height = MATH.max(height, hidden ? 0 : dom.clientHeight) || 0;
13438
13439             // IE9 Direct2D dimension rounding bug
13440             if (!hidden && Ext.supports.Direct2DBug) {
13441                 floating = me.adjustDirect2DDimension('height');
13442                 if (preciseHeight) {
13443                     height += floating;
13444                 }
13445                 else if (floating > 0 && floating < 0.5) {
13446                     height++;
13447                 }
13448             }
13449
13450             if (contentHeight) {
13451                 height -= (me.getBorderWidth("tb") + me.getPadding("tb"));
13452             }
13453
13454             if (Ext.isIEQuirks) {
13455                 me.setStyle({ overflow: overflow});
13456             }
13457
13458             if (height < 0) {
13459                 height = 0;
13460             }
13461             return height;
13462         },
13463                 
13464         /**
13465          * Returns the offset width of the element
13466          * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
13467          * @return {Number} The element's width
13468          */
13469         getWidth: function(contentWidth, preciseWidth) {
13470             var me = this,
13471                 dom = me.dom,
13472                 hidden = Ext.isIE && me.isStyle('display', 'none'),
13473                 rect, width, overflow, style, floating, parentPosition;
13474
13475             // IE Quirks mode acts more like a max-size measurement unless overflow is hidden during measurement.
13476             // We will put the overflow back to it's original value when we are done measuring.
13477             if (Ext.isIEQuirks) {
13478                 style = dom.style;
13479                 overflow = style.overflow;
13480                 me.setStyle({overflow: 'hidden'});
13481             }
13482             
13483             // Fix Opera 10.5x width calculation issues 
13484             if (Ext.isOpera10_5) {
13485                 if (dom.parentNode.currentStyle.position === 'relative') {
13486                     parentPosition = dom.parentNode.style.position;
13487                     dom.parentNode.style.position = 'static';
13488                     width = dom.offsetWidth;
13489                     dom.parentNode.style.position = parentPosition;
13490                 }
13491                 width = Math.max(width || 0, dom.offsetWidth);
13492             
13493             // Gecko will in some cases report an offsetWidth that is actually less than the width of the
13494             // text contents, because it measures fonts with sub-pixel precision but rounds the calculated
13495             // value down. Using getBoundingClientRect instead of offsetWidth allows us to get the precise
13496             // subpixel measurements so we can force them to always be rounded up. See
13497             // https://bugzilla.mozilla.org/show_bug.cgi?id=458617
13498             } else if (Ext.supports.BoundingClientRect) {
13499                 rect = dom.getBoundingClientRect();
13500                 width = rect.right - rect.left;
13501                 width = preciseWidth ? width : Math.ceil(width);
13502             } else {
13503                 width = dom.offsetWidth;
13504             }
13505
13506             width = MATH.max(width, hidden ? 0 : dom.clientWidth) || 0;
13507
13508             // IE9 Direct2D dimension rounding bug
13509             if (!hidden && Ext.supports.Direct2DBug) {
13510                 floating = me.adjustDirect2DDimension('width');
13511                 if (preciseWidth) {
13512                     width += floating;
13513                 }
13514                 else if (floating > 0 && floating < 0.5) {
13515                     width++;
13516                 }
13517             }
13518             
13519             if (contentWidth) {
13520                 width -= (me.getBorderWidth("lr") + me.getPadding("lr"));
13521             }
13522             
13523             if (Ext.isIEQuirks) {
13524                 me.setStyle({ overflow: overflow});
13525             }
13526
13527             if (width < 0) {
13528                 width = 0;
13529             }
13530             return width;
13531         },
13532
13533         /**
13534          * Set the width of this Element.
13535          * @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul>
13536          * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li>
13537          * <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
13538          * </ul></div>
13539          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
13540          * @return {Ext.core.Element} this
13541          */
13542         setWidth : function(width, animate){
13543             var me = this;
13544             width = me.adjustWidth(width);
13545             if (!animate || !me.anim) {
13546                 me.dom.style.width = me.addUnits(width);
13547             }
13548             else {
13549                 if (!Ext.isObject(animate)) {
13550                     animate = {};
13551                 }
13552                 me.animate(Ext.applyIf({
13553                     to: {
13554                         width: width
13555                     }
13556                 }, animate));
13557             }
13558             return me;
13559         },
13560
13561         /**
13562          * Set the height of this Element.
13563          * <pre><code>
13564 // change the height to 200px and animate with default configuration
13565 Ext.fly('elementId').setHeight(200, true);
13566
13567 // change the height to 150px and animate with a custom configuration
13568 Ext.fly('elId').setHeight(150, {
13569     duration : .5, // animation will have a duration of .5 seconds
13570     // will change the content to "finished"
13571     callback: function(){ this.{@link #update}("finished"); }
13572 });
13573          * </code></pre>
13574          * @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul>
13575          * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)</li>
13576          * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
13577          * </ul></div>
13578          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
13579          * @return {Ext.core.Element} this
13580          */
13581          setHeight : function(height, animate){
13582             var me = this;
13583             height = me.adjustHeight(height);
13584             if (!animate || !me.anim) {
13585                 me.dom.style.height = me.addUnits(height);
13586             }
13587             else {
13588                 if (!Ext.isObject(animate)) {
13589                     animate = {};
13590                 }
13591                 me.animate(Ext.applyIf({
13592                     to: {
13593                         height: height
13594                     }
13595                 }, animate));
13596             }
13597             return me;
13598         },
13599
13600         /**
13601          * Gets the width of the border(s) for the specified side(s)
13602          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
13603          * passing <tt>'lr'</tt> would get the border <b><u>l</u></b>eft width + the border <b><u>r</u></b>ight width.
13604          * @return {Number} The width of the sides passed added together
13605          */
13606         getBorderWidth : function(side){
13607             return this.addStyles(side, borders);
13608         },
13609
13610         /**
13611          * Gets the width of the padding(s) for the specified side(s)
13612          * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
13613          * passing <tt>'lr'</tt> would get the padding <b><u>l</u></b>eft + the padding <b><u>r</u></b>ight.
13614          * @return {Number} The padding of the sides passed added together
13615          */
13616         getPadding : function(side){
13617             return this.addStyles(side, paddings);
13618         },
13619
13620         /**
13621          *  Store the current overflow setting and clip overflow on the element - use <tt>{@link #unclip}</tt> to remove
13622          * @return {Ext.core.Element} this
13623          */
13624         clip : function(){
13625             var me = this,
13626                 dom = me.dom;
13627
13628             if(!data(dom, ISCLIPPED)){
13629                 data(dom, ISCLIPPED, true);
13630                 data(dom, ORIGINALCLIP, {
13631                     o: me.getStyle(OVERFLOW),
13632                     x: me.getStyle(OVERFLOWX),
13633                     y: me.getStyle(OVERFLOWY)
13634                 });
13635                 me.setStyle(OVERFLOW, HIDDEN);
13636                 me.setStyle(OVERFLOWX, HIDDEN);
13637                 me.setStyle(OVERFLOWY, HIDDEN);
13638             }
13639             return me;
13640         },
13641
13642         /**
13643          *  Return clipping (overflow) to original clipping before <tt>{@link #clip}</tt> was called
13644          * @return {Ext.core.Element} this
13645          */
13646         unclip : function(){
13647             var me = this,
13648                 dom = me.dom,
13649                 clip;
13650
13651             if(data(dom, ISCLIPPED)){
13652                 data(dom, ISCLIPPED, false);
13653                 clip = data(dom, ORIGINALCLIP);
13654                 if(o.o){
13655                     me.setStyle(OVERFLOW, o.o);
13656                 }
13657                 if(o.x){
13658                     me.setStyle(OVERFLOWX, o.x);
13659                 }
13660                 if(o.y){
13661                     me.setStyle(OVERFLOWY, o.y);
13662                 }
13663             }
13664             return me;
13665         },
13666
13667         // private
13668         addStyles : function(sides, styles){
13669             var totalSize = 0,
13670                 sidesArr = sides.match(wordsRe),
13671                 i = 0,
13672                 len = sidesArr.length,
13673                 side, size;
13674             for (; i < len; i++) {
13675                 side = sidesArr[i];
13676                 size = side && parseInt(this.getStyle(styles[side]), 10);
13677                 if (size) {
13678                     totalSize += MATH.abs(size);
13679                 }
13680             }
13681             return totalSize;
13682         },
13683
13684         margins : margins,
13685         
13686         /**
13687          * More flexible version of {@link #setStyle} for setting style properties.
13688          * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
13689          * a function which returns such a specification.
13690          * @return {Ext.core.Element} this
13691          */
13692         applyStyles : function(style){
13693             Ext.core.DomHelper.applyStyles(this.dom, style);
13694             return this;
13695         },
13696
13697         /**
13698          * Returns an object with properties matching the styles requested.
13699          * For example, el.getStyles('color', 'font-size', 'width') might return
13700          * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
13701          * @param {String} style1 A style name
13702          * @param {String} style2 A style name
13703          * @param {String} etc.
13704          * @return {Object} The style object
13705          */
13706         getStyles : function(){
13707             var styles = {},
13708                 len = arguments.length,
13709                 i = 0, style;
13710                 
13711             for(; i < len; ++i) {
13712                 style = arguments[i];
13713                 styles[style] = this.getStyle(style);
13714             }
13715             return styles;
13716         },
13717
13718        /**
13719         * <p>Wraps the specified element with a special 9 element markup/CSS block that renders by default as
13720         * a gray container with a gradient background, rounded corners and a 4-way shadow.</p>
13721         * <p>This special markup is used throughout Ext when box wrapping elements ({@link Ext.button.Button},
13722         * {@link Ext.panel.Panel} when <tt>{@link Ext.panel.Panel#frame frame=true}</tt>, {@link Ext.window.Window}).  The markup
13723         * is of this form:</p>
13724         * <pre><code>
13725     Ext.core.Element.boxMarkup =
13726     &#39;&lt;div class="{0}-tl">&lt;div class="{0}-tr">&lt;div class="{0}-tc">&lt;/div>&lt;/div>&lt;/div>
13727      &lt;div class="{0}-ml">&lt;div class="{0}-mr">&lt;div class="{0}-mc">&lt;/div>&lt;/div>&lt;/div>
13728      &lt;div class="{0}-bl">&lt;div class="{0}-br">&lt;div class="{0}-bc">&lt;/div>&lt;/div>&lt;/div>&#39;;
13729         * </code></pre>
13730         * <p>Example usage:</p>
13731         * <pre><code>
13732     // Basic box wrap
13733     Ext.get("foo").boxWrap();
13734
13735     // You can also add a custom class and use CSS inheritance rules to customize the box look.
13736     // 'x-box-blue' is a built-in alternative -- look at the related CSS definitions as an example
13737     // for how to create a custom box wrap style.
13738     Ext.get("foo").boxWrap().addCls("x-box-blue");
13739         * </code></pre>
13740         * @param {String} class (optional) A base CSS class to apply to the containing wrapper element
13741         * (defaults to <tt>'x-box'</tt>). Note that there are a number of CSS rules that are dependent on
13742         * this name to make the overall effect work, so if you supply an alternate base class, make sure you
13743         * also supply all of the necessary rules.
13744         * @return {Ext.core.Element} The outermost wrapping element of the created box structure.
13745         */
13746         boxWrap : function(cls){
13747             cls = cls || Ext.baseCSSPrefix + 'box';
13748             var el = Ext.get(this.insertHtml("beforeBegin", "<div class='" + cls + "'>" + Ext.String.format(Ext.core.Element.boxMarkup, cls) + "</div>"));
13749             Ext.DomQuery.selectNode('.' + cls + '-mc', el.dom).appendChild(this.dom);
13750             return el;
13751         },
13752
13753         /**
13754          * Set the size of this Element. If animation is true, both width and height will be animated concurrently.
13755          * @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul>
13756          * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li>
13757          * <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
13758          * <li>A size object in the format <code>{width: widthValue, height: heightValue}</code>.</li>
13759          * </ul></div>
13760          * @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul>
13761          * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels).</li>
13762          * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
13763          * </ul></div>
13764          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
13765          * @return {Ext.core.Element} this
13766          */
13767         setSize : function(width, height, animate){
13768             var me = this;
13769             if (Ext.isObject(width)){ // in case of object from getSize()
13770                 height = width.height;
13771                 width = width.width;
13772             }
13773             width = me.adjustWidth(width);
13774             height = me.adjustHeight(height);
13775             if(!animate || !me.anim){
13776                 me.dom.style.width = me.addUnits(width);
13777                 me.dom.style.height = me.addUnits(height);
13778             }
13779             else {
13780                 if (!Ext.isObject(animate)) {
13781                     animate = {};
13782                 }
13783                 me.animate(Ext.applyIf({
13784                     to: {
13785                         width: width,
13786                         height: height
13787                     }
13788                 }, animate));
13789             }
13790             return me;
13791         },
13792
13793         /**
13794          * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
13795          * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
13796          * if a height has not been set using CSS.
13797          * @return {Number}
13798          */
13799         getComputedHeight : function(){
13800             var me = this,
13801                 h = Math.max(me.dom.offsetHeight, me.dom.clientHeight);
13802             if(!h){
13803                 h = parseFloat(me.getStyle('height')) || 0;
13804                 if(!me.isBorderBox()){
13805                     h += me.getFrameWidth('tb');
13806                 }
13807             }
13808             return h;
13809         },
13810
13811         /**
13812          * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
13813          * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
13814          * if a width has not been set using CSS.
13815          * @return {Number}
13816          */
13817         getComputedWidth : function(){
13818             var me = this,
13819                 w = Math.max(me.dom.offsetWidth, me.dom.clientWidth);
13820                 
13821             if(!w){
13822                 w = parseFloat(me.getStyle('width')) || 0;
13823                 if(!me.isBorderBox()){
13824                     w += me.getFrameWidth('lr');
13825                 }
13826             }
13827             return w;
13828         },
13829
13830         /**
13831          * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
13832          for more information about the sides.
13833          * @param {String} sides
13834          * @return {Number}
13835          */
13836         getFrameWidth : function(sides, onlyContentBox){
13837             return onlyContentBox && this.isBorderBox() ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
13838         },
13839
13840         /**
13841          * Sets up event handlers to add and remove a css class when the mouse is over this element
13842          * @param {String} className
13843          * @return {Ext.core.Element} this
13844          */
13845         addClsOnOver : function(className){
13846             var dom = this.dom;
13847             this.hover(
13848                 function(){
13849                     Ext.fly(dom, INTERNAL).addCls(className);
13850                 },
13851                 function(){
13852                     Ext.fly(dom, INTERNAL).removeCls(className);
13853                 }
13854             );
13855             return this;
13856         },
13857
13858         /**
13859          * Sets up event handlers to add and remove a css class when this element has the focus
13860          * @param {String} className
13861          * @return {Ext.core.Element} this
13862          */
13863         addClsOnFocus : function(className){
13864             var me = this,
13865                 dom = me.dom;
13866             me.on("focus", function(){
13867                 Ext.fly(dom, INTERNAL).addCls(className);
13868             });
13869             me.on("blur", function(){
13870                 Ext.fly(dom, INTERNAL).removeCls(className);
13871             });
13872             return me;
13873         },
13874
13875         /**
13876          * Sets up event handlers to add and remove a css class when the mouse is down and then up on this element (a click effect)
13877          * @param {String} className
13878          * @return {Ext.core.Element} this
13879          */
13880         addClsOnClick : function(className){
13881             var dom = this.dom;
13882             this.on("mousedown", function(){
13883                 Ext.fly(dom, INTERNAL).addCls(className);
13884                 var d = Ext.getDoc(),
13885                     fn = function(){
13886                         Ext.fly(dom, INTERNAL).removeCls(className);
13887                         d.removeListener("mouseup", fn);
13888                     };
13889                 d.on("mouseup", fn);
13890             });
13891             return this;
13892         },
13893
13894         /**
13895          * <p>Returns the dimensions of the element available to lay content out in.<p>
13896          * <p>If the element (or any ancestor element) has CSS style <code>display : none</code>, the dimensions will be zero.</p>
13897          * example:<pre><code>
13898         var vpSize = Ext.getBody().getViewSize();
13899
13900         // all Windows created afterwards will have a default value of 90% height and 95% width
13901         Ext.Window.override({
13902             width: vpSize.width * 0.9,
13903             height: vpSize.height * 0.95
13904         });
13905         // To handle window resizing you would have to hook onto onWindowResize.
13906         * </code></pre>
13907         *
13908         * getViewSize utilizes clientHeight/clientWidth which excludes sizing of scrollbars.
13909         * To obtain the size including scrollbars, use getStyleSize
13910         *
13911         * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
13912         */
13913
13914         getViewSize : function(){
13915             var me = this,
13916                 dom = me.dom,
13917                 isDoc = (dom == Ext.getDoc().dom || dom == Ext.getBody().dom),
13918                 style, overflow, ret;
13919
13920             // If the body, use static methods
13921             if (isDoc) {
13922                 ret = {
13923                     width : Ext.core.Element.getViewWidth(),
13924                     height : Ext.core.Element.getViewHeight()
13925                 };
13926
13927             // Else use clientHeight/clientWidth
13928             }
13929             else {
13930                 // IE 6 & IE Quirks mode acts more like a max-size measurement unless overflow is hidden during measurement.
13931                 // We will put the overflow back to it's original value when we are done measuring.
13932                 if (Ext.isIE6 || Ext.isIEQuirks) {
13933                     style = dom.style;
13934                     overflow = style.overflow;
13935                     me.setStyle({ overflow: 'hidden'});
13936                 }
13937                 ret = {
13938                     width : dom.clientWidth,
13939                     height : dom.clientHeight
13940                 };
13941                 if (Ext.isIE6 || Ext.isIEQuirks) {
13942                     me.setStyle({ overflow: overflow });
13943                 }
13944             }
13945             return ret;
13946         },
13947
13948         /**
13949         * <p>Returns the dimensions of the element available to lay content out in.<p>
13950         *
13951         * getStyleSize utilizes prefers style sizing if present, otherwise it chooses the larger of offsetHeight/clientHeight and offsetWidth/clientWidth.
13952         * To obtain the size excluding scrollbars, use getViewSize
13953         *
13954         * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
13955         */
13956
13957         getStyleSize : function(){
13958             var me = this,
13959                 doc = document,
13960                 d = this.dom,
13961                 isDoc = (d == doc || d == doc.body),
13962                 s = d.style,
13963                 w, h;
13964
13965             // If the body, use static methods
13966             if (isDoc) {
13967                 return {
13968                     width : Ext.core.Element.getViewWidth(),
13969                     height : Ext.core.Element.getViewHeight()
13970                 };
13971             }
13972             // Use Styles if they are set
13973             if(s.width && s.width != 'auto'){
13974                 w = parseFloat(s.width);
13975                 if(me.isBorderBox()){
13976                    w -= me.getFrameWidth('lr');
13977                 }
13978             }
13979             // Use Styles if they are set
13980             if(s.height && s.height != 'auto'){
13981                 h = parseFloat(s.height);
13982                 if(me.isBorderBox()){
13983                    h -= me.getFrameWidth('tb');
13984                 }
13985             }
13986             // Use getWidth/getHeight if style not set.
13987             return {width: w || me.getWidth(true), height: h || me.getHeight(true)};
13988         },
13989
13990         /**
13991          * Returns the size of the element.
13992          * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
13993          * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
13994          */
13995         getSize : function(contentSize){
13996             return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
13997         },
13998
13999         /**
14000          * Forces the browser to repaint this element
14001          * @return {Ext.core.Element} this
14002          */
14003         repaint : function(){
14004             var dom = this.dom;
14005             this.addCls(Ext.baseCSSPrefix + 'repaint');
14006             setTimeout(function(){
14007                 Ext.fly(dom).removeCls(Ext.baseCSSPrefix + 'repaint');
14008             }, 1);
14009             return this;
14010         },
14011
14012         /**
14013          * Disables text selection for this element (normalized across browsers)
14014          * @return {Ext.core.Element} this
14015          */
14016         unselectable : function(){
14017             var me = this;
14018             me.dom.unselectable = "on";
14019
14020             me.swallowEvent("selectstart", true);
14021             me.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
14022             me.addCls(Ext.baseCSSPrefix + 'unselectable');
14023             
14024             return me;
14025         },
14026
14027         /**
14028          * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
14029          * then it returns the calculated width of the sides (see getPadding)
14030          * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
14031          * @return {Object/Number}
14032          */
14033         getMargin : function(side){
14034             var me = this,
14035                 hash = {t:"top", l:"left", r:"right", b: "bottom"},
14036                 o = {},
14037                 key;
14038
14039             if (!side) {
14040                 for (key in me.margins){
14041                     o[hash[key]] = parseFloat(me.getStyle(me.margins[key])) || 0;
14042                 }
14043                 return o;
14044             } else {
14045                 return me.addStyles.call(me, side, me.margins);
14046             }
14047         }
14048     });
14049 })();
14050 /**
14051  * @class Ext.core.Element
14052  */
14053 /**
14054  * Visibility mode constant for use with {@link #setVisibilityMode}. Use visibility to hide element
14055  * @static
14056  * @type Number
14057  */
14058 Ext.core.Element.VISIBILITY = 1;
14059 /**
14060  * Visibility mode constant for use with {@link #setVisibilityMode}. Use display to hide element
14061  * @static
14062  * @type Number
14063  */
14064 Ext.core.Element.DISPLAY = 2;
14065
14066 /**
14067  * Visibility mode constant for use with {@link #setVisibilityMode}. Use offsets (x and y positioning offscreen)
14068  * to hide element.
14069  * @static
14070  * @type Number
14071  */
14072 Ext.core.Element.OFFSETS = 3;
14073
14074
14075 Ext.core.Element.ASCLASS = 4;
14076
14077 /**
14078  * Defaults to 'x-hide-nosize'
14079  * @static
14080  * @type String
14081  */
14082 Ext.core.Element.visibilityCls = Ext.baseCSSPrefix + 'hide-nosize';
14083
14084 Ext.core.Element.addMethods(function(){
14085     var El = Ext.core.Element,
14086         OPACITY = "opacity",
14087         VISIBILITY = "visibility",
14088         DISPLAY = "display",
14089         HIDDEN = "hidden",
14090         OFFSETS = "offsets",
14091         ASCLASS = "asclass",
14092         NONE = "none",
14093         NOSIZE = 'nosize',
14094         ORIGINALDISPLAY = 'originalDisplay',
14095         VISMODE = 'visibilityMode',
14096         ISVISIBLE = 'isVisible',
14097         data = El.data,
14098         getDisplay = function(dom){
14099             var d = data(dom, ORIGINALDISPLAY);
14100             if(d === undefined){
14101                 data(dom, ORIGINALDISPLAY, d = '');
14102             }
14103             return d;
14104         },
14105         getVisMode = function(dom){
14106             var m = data(dom, VISMODE);
14107             if(m === undefined){
14108                 data(dom, VISMODE, m = 1);
14109             }
14110             return m;
14111         };
14112
14113     return {
14114         /**
14115          * The element's default display mode  (defaults to "")
14116          * @type String
14117          */
14118         originalDisplay : "",
14119         visibilityMode : 1,
14120
14121         /**
14122          * Sets the element's visibility mode. When setVisible() is called it
14123          * will use this to determine whether to set the visibility or the display property.
14124          * @param {Number} visMode Ext.core.Element.VISIBILITY or Ext.core.Element.DISPLAY
14125          * @return {Ext.core.Element} this
14126          */
14127         setVisibilityMode : function(visMode){
14128             data(this.dom, VISMODE, visMode);
14129             return this;
14130         },
14131
14132         /**
14133          * Checks whether the element is currently visible using both visibility and display properties.
14134          * @return {Boolean} True if the element is currently visible, else false
14135          */
14136         isVisible : function() {
14137             var me = this,
14138                 dom = me.dom,
14139                 visible = data(dom, ISVISIBLE);
14140
14141             if(typeof visible == 'boolean'){ //return the cached value if registered
14142                 return visible;
14143             }
14144             //Determine the current state based on display states
14145             visible = !me.isStyle(VISIBILITY, HIDDEN) &&
14146                       !me.isStyle(DISPLAY, NONE) &&
14147                       !((getVisMode(dom) == El.ASCLASS) && me.hasCls(me.visibilityCls || El.visibilityCls));
14148
14149             data(dom, ISVISIBLE, visible);
14150             return visible;
14151         },
14152
14153         /**
14154          * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
14155          * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
14156          * @param {Boolean} visible Whether the element is visible
14157          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
14158          * @return {Ext.core.Element} this
14159          */
14160         setVisible : function(visible, animate){
14161             var me = this, isDisplay, isVisibility, isOffsets, isNosize,
14162                 dom = me.dom,
14163                 visMode = getVisMode(dom);
14164
14165
14166             // hideMode string override
14167             if (typeof animate == 'string'){
14168                 switch (animate) {
14169                     case DISPLAY:
14170                         visMode = El.DISPLAY;
14171                         break;
14172                     case VISIBILITY:
14173                         visMode = El.VISIBILITY;
14174                         break;
14175                     case OFFSETS:
14176                         visMode = El.OFFSETS;
14177                         break;
14178                     case NOSIZE:
14179                     case ASCLASS:
14180                         visMode = El.ASCLASS;
14181                         break;
14182                 }
14183                 me.setVisibilityMode(visMode);
14184                 animate = false;
14185             }
14186
14187             if (!animate || !me.anim) {
14188                 if(visMode == El.ASCLASS ){
14189
14190                     me[visible?'removeCls':'addCls'](me.visibilityCls || El.visibilityCls);
14191
14192                 } else if (visMode == El.DISPLAY){
14193
14194                     return me.setDisplayed(visible);
14195
14196                 } else if (visMode == El.OFFSETS){
14197
14198                     if (!visible){
14199                         // Remember position for restoring, if we are not already hidden by offsets.
14200                         if (!me.hideModeStyles) {
14201                             me.hideModeStyles = {
14202                                 position: me.getStyle('position'),
14203                                 top: me.getStyle('top'),
14204                                 left: me.getStyle('left')
14205                             };
14206                         }
14207                         me.applyStyles({position: 'absolute', top: '-10000px', left: '-10000px'});
14208                     }
14209
14210                     // Only "restore" as position if we have actually been hidden using offsets.
14211                     // Calling setVisible(true) on a positioned element should not reposition it.
14212                     else if (me.hideModeStyles) {
14213                         me.applyStyles(me.hideModeStyles || {position: '', top: '', left: ''});
14214                         delete me.hideModeStyles;
14215                     }
14216
14217                 }else{
14218                     me.fixDisplay();
14219                     // Show by clearing visibility style. Explicitly setting to "visible" overrides parent visibility setting.
14220                     dom.style.visibility = visible ? '' : HIDDEN;
14221                 }
14222             }else{
14223                 // closure for composites
14224                 if(visible){
14225                     me.setOpacity(0.01);
14226                     me.setVisible(true);
14227                 }
14228                 if (!Ext.isObject(animate)) {
14229                     animate = {
14230                         duration: 350,
14231                         easing: 'ease-in'
14232                     };
14233                 }
14234                 me.animate(Ext.applyIf({
14235                     callback: function() {
14236                         visible || me.setVisible(false).setOpacity(1);
14237                     },
14238                     to: {
14239                         opacity: (visible) ? 1 : 0
14240                     }
14241                 }, animate));
14242             }
14243             data(dom, ISVISIBLE, visible);  //set logical visibility state
14244             return me;
14245         },
14246
14247
14248         /**
14249          * @private
14250          * Determine if the Element has a relevant height and width available based
14251          * upon current logical visibility state
14252          */
14253         hasMetrics  : function(){
14254             var dom = this.dom;
14255             return this.isVisible() || (getVisMode(dom) == El.OFFSETS) || (getVisMode(dom) == El.VISIBILITY);
14256         },
14257
14258         /**
14259          * Toggles the element's visibility or display, depending on visibility mode.
14260          * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
14261          * @return {Ext.core.Element} this
14262          */
14263         toggle : function(animate){
14264             var me = this;
14265             me.setVisible(!me.isVisible(), me.anim(animate));
14266             return me;
14267         },
14268
14269         /**
14270          * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
14271          * @param {Mixed} value Boolean value to display the element using its default display, or a string to set the display directly.
14272          * @return {Ext.core.Element} this
14273          */
14274         setDisplayed : function(value) {
14275             if(typeof value == "boolean"){
14276                value = value ? getDisplay(this.dom) : NONE;
14277             }
14278             this.setStyle(DISPLAY, value);
14279             return this;
14280         },
14281
14282         // private
14283         fixDisplay : function(){
14284             var me = this;
14285             if (me.isStyle(DISPLAY, NONE)) {
14286                 me.setStyle(VISIBILITY, HIDDEN);
14287                 me.setStyle(DISPLAY, getDisplay(this.dom)); // first try reverting to default
14288                 if (me.isStyle(DISPLAY, NONE)) { // if that fails, default to block
14289                     me.setStyle(DISPLAY, "block");
14290                 }
14291             }
14292         },
14293
14294         /**
14295          * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
14296          * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
14297          * @return {Ext.core.Element} this
14298          */
14299         hide : function(animate){
14300             // hideMode override
14301             if (typeof animate == 'string'){
14302                 this.setVisible(false, animate);
14303                 return this;
14304             }
14305             this.setVisible(false, this.anim(animate));
14306             return this;
14307         },
14308
14309         /**
14310         * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
14311         * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
14312          * @return {Ext.core.Element} this
14313          */
14314         show : function(animate){
14315             // hideMode override
14316             if (typeof animate == 'string'){
14317                 this.setVisible(true, animate);
14318                 return this;
14319             }
14320             this.setVisible(true, this.anim(animate));
14321             return this;
14322         }
14323     };
14324 }());
14325 /**
14326  * @class Ext.core.Element
14327  */
14328 Ext.applyIf(Ext.core.Element.prototype, {
14329     // @private override base Ext.util.Animate mixin for animate for backwards compatibility
14330     animate: function(config) {
14331         var me = this;
14332         if (!me.id) {
14333             me = Ext.get(me.dom);
14334         }
14335         if (Ext.fx.Manager.hasFxBlock(me.id)) {
14336             return me;
14337         }
14338         Ext.fx.Manager.queueFx(Ext.create('Ext.fx.Anim', me.anim(config)));
14339         return this;
14340     },
14341
14342     // @private override base Ext.util.Animate mixin for animate for backwards compatibility
14343     anim: function(config) {
14344         if (!Ext.isObject(config)) {
14345             return (config) ? {} : false;
14346         }
14347
14348         var me = this,
14349             duration = config.duration || Ext.fx.Anim.prototype.duration,
14350             easing = config.easing || 'ease',
14351             animConfig;
14352
14353         if (config.stopAnimation) {
14354             me.stopAnimation();
14355         }
14356
14357         Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id));
14358
14359         // Clear any 'paused' defaults.
14360         Ext.fx.Manager.setFxDefaults(me.id, {
14361             delay: 0
14362         });
14363
14364         animConfig = {
14365             target: me,
14366             remove: config.remove,
14367             alternate: config.alternate || false,
14368             duration: duration,
14369             easing: easing,
14370             callback: config.callback,
14371             listeners: config.listeners,
14372             iterations: config.iterations || 1,
14373             scope: config.scope,
14374             block: config.block,
14375             concurrent: config.concurrent,
14376             delay: config.delay || 0,
14377             paused: true,
14378             keyframes: config.keyframes,
14379             from: config.from || {},
14380             to: Ext.apply({}, config)
14381         };
14382         Ext.apply(animConfig.to, config.to);
14383
14384         // Anim API properties - backward compat
14385         delete animConfig.to.to;
14386         delete animConfig.to.from;
14387         delete animConfig.to.remove;
14388         delete animConfig.to.alternate;
14389         delete animConfig.to.keyframes;
14390         delete animConfig.to.iterations;
14391         delete animConfig.to.listeners;
14392         delete animConfig.to.target;
14393         delete animConfig.to.paused;
14394         delete animConfig.to.callback;
14395         delete animConfig.to.scope;
14396         delete animConfig.to.duration;
14397         delete animConfig.to.easing;
14398         delete animConfig.to.concurrent;
14399         delete animConfig.to.block;
14400         delete animConfig.to.stopAnimation;
14401         delete animConfig.to.delay;
14402         return animConfig;
14403     },
14404
14405     /**
14406      * Slides the element into view.  An anchor point can be optionally passed to set the point of
14407      * origin for the slide effect.  This function automatically handles wrapping the element with
14408      * a fixed-size container if needed.  See the Fx class overview for valid anchor point options.
14409      * Usage:
14410      *<pre><code>
14411 // default: slide the element in from the top
14412 el.slideIn();
14413
14414 // custom: slide the element in from the right with a 2-second duration
14415 el.slideIn('r', { duration: 2 });
14416
14417 // common config options shown with default values
14418 el.slideIn('t', {
14419     easing: 'easeOut',
14420     duration: 500
14421 });
14422 </code></pre>
14423      * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
14424      * @param {Object} options (optional) Object literal with any of the Fx config options
14425      * @return {Ext.core.Element} The Element
14426      */
14427     slideIn: function(anchor, obj, slideOut) { 
14428         var me = this,
14429             elStyle = me.dom.style,
14430             beforeAnim, wrapAnim;
14431
14432         anchor = anchor || "t";
14433         obj = obj || {};
14434
14435         beforeAnim = function() {
14436             var animScope = this,
14437                 listeners = obj.listeners,
14438                 box, position, restoreSize, wrap, anim;
14439
14440             if (!slideOut) {
14441                 me.fixDisplay();
14442             }
14443
14444             box = me.getBox();
14445             if ((anchor == 't' || anchor == 'b') && box.height == 0) {
14446                 box.height = me.dom.scrollHeight;
14447             }
14448             else if ((anchor == 'l' || anchor == 'r') && box.width == 0) {
14449                 box.width = me.dom.scrollWidth;
14450             }
14451             
14452             position = me.getPositioning();
14453             me.setSize(box.width, box.height);
14454
14455             wrap = me.wrap({
14456                 style: {
14457                     visibility: slideOut ? 'visible' : 'hidden'
14458                 }
14459             });
14460             wrap.setPositioning(position);
14461             if (wrap.isStyle('position', 'static')) {
14462                 wrap.position('relative');
14463             }
14464             me.clearPositioning('auto');
14465             wrap.clip();
14466
14467             // This element is temporarily positioned absolute within its wrapper.
14468             // Restore to its default, CSS-inherited visibility setting.
14469             // We cannot explicitly poke visibility:visible into its style because that overrides the visibility of the wrap.
14470             me.setStyle({
14471                 visibility: '',
14472                 position: 'absolute'
14473             });
14474             if (slideOut) {
14475                 wrap.setSize(box.width, box.height);
14476             }
14477
14478             switch (anchor) {
14479                 case 't':
14480                     anim = {
14481                         from: {
14482                             width: box.width + 'px',
14483                             height: '0px'
14484                         },
14485                         to: {
14486                             width: box.width + 'px',
14487                             height: box.height + 'px'
14488                         }
14489                     };
14490                     elStyle.bottom = '0px';
14491                     break;
14492                 case 'l':
14493                     anim = {
14494                         from: {
14495                             width: '0px',
14496                             height: box.height + 'px'
14497                         },
14498                         to: {
14499                             width: box.width + 'px',
14500                             height: box.height + 'px'
14501                         }
14502                     };
14503                     elStyle.right = '0px';
14504                     break;
14505                 case 'r':
14506                     anim = {
14507                         from: {
14508                             x: box.x + box.width,
14509                             width: '0px',
14510                             height: box.height + 'px'
14511                         },
14512                         to: {
14513                             x: box.x,
14514                             width: box.width + 'px',
14515                             height: box.height + 'px'
14516                         }
14517                     };
14518                     break;
14519                 case 'b':
14520                     anim = {
14521                         from: {
14522                             y: box.y + box.height,
14523                             width: box.width + 'px',
14524                             height: '0px'
14525                         },
14526                         to: {
14527                             y: box.y,
14528                             width: box.width + 'px',
14529                             height: box.height + 'px'
14530                         }
14531                     };
14532                     break;
14533                 case 'tl':
14534                     anim = {
14535                         from: {
14536                             x: box.x,
14537                             y: box.y,
14538                             width: '0px',
14539                             height: '0px'
14540                         },
14541                         to: {
14542                             width: box.width + 'px',
14543                             height: box.height + 'px'
14544                         }
14545                     };
14546                     elStyle.bottom = '0px';
14547                     elStyle.right = '0px';
14548                     break;
14549                 case 'bl':
14550                     anim = {
14551                         from: {
14552                             x: box.x + box.width,
14553                             width: '0px',
14554                             height: '0px'
14555                         },
14556                         to: {
14557                             x: box.x,
14558                             width: box.width + 'px',
14559                             height: box.height + 'px'
14560                         }
14561                     };
14562                     elStyle.right = '0px';
14563                     break;
14564                 case 'br':
14565                     anim = {
14566                         from: {
14567                             x: box.x + box.width,
14568                             y: box.y + box.height,
14569                             width: '0px',
14570                             height: '0px'
14571                         },
14572                         to: {
14573                             x: box.x,
14574                             y: box.y,
14575                             width: box.width + 'px',
14576                             height: box.height + 'px'
14577                         }
14578                     };
14579                     break;
14580                 case 'tr':
14581                     anim = {
14582                         from: {
14583                             y: box.y + box.height,
14584                             width: '0px',
14585                             height: '0px'
14586                         },
14587                         to: {
14588                             y: box.y,
14589                             width: box.width + 'px',
14590                             height: box.height + 'px'
14591                         }
14592                     };
14593                     elStyle.bottom = '0px';
14594                     break;
14595             }
14596
14597             wrap.show();
14598             wrapAnim = Ext.apply({}, obj);
14599             delete wrapAnim.listeners;
14600             wrapAnim = Ext.create('Ext.fx.Anim', Ext.applyIf(wrapAnim, {
14601                 target: wrap,
14602                 duration: 500,
14603                 easing: 'ease-out',
14604                 from: slideOut ? anim.to : anim.from,
14605                 to: slideOut ? anim.from : anim.to
14606             }));
14607
14608             // In the absence of a callback, this listener MUST be added first
14609             wrapAnim.on('afteranimate', function() {
14610                 if (slideOut) {
14611                     me.setPositioning(position);
14612                     if (obj.useDisplay) {
14613                         me.setDisplayed(false);
14614                     } else {
14615                         me.hide();   
14616                     }
14617                 }
14618                 else {
14619                     me.clearPositioning();
14620                     me.setPositioning(position);
14621                 }
14622                 if (wrap.dom) {
14623                     wrap.dom.parentNode.insertBefore(me.dom, wrap.dom); 
14624                     wrap.remove();
14625                 }
14626                 me.setSize(box.width, box.height);
14627                 animScope.end();
14628             });
14629             // Add configured listeners after
14630             if (listeners) {
14631                 wrapAnim.on(listeners);
14632             }
14633         };
14634
14635         me.animate({
14636             duration: obj.duration ? obj.duration * 2 : 1000,
14637             listeners: {
14638                 beforeanimate: {
14639                     fn: beforeAnim
14640                 },
14641                 afteranimate: {
14642                     fn: function() {
14643                         if (wrapAnim && wrapAnim.running) {
14644                             wrapAnim.end();
14645                         }
14646                     }
14647                 }
14648             }
14649         });
14650         return me;
14651     },
14652
14653     
14654     /**
14655      * Slides the element out of view.  An anchor point can be optionally passed to set the end point
14656      * for the slide effect.  When the effect is completed, the element will be hidden (visibility = 
14657      * 'hidden') but block elements will still take up space in the document.  The element must be removed
14658      * from the DOM using the 'remove' config option if desired.  This function automatically handles 
14659      * wrapping the element with a fixed-size container if needed.  See the Fx class overview for valid anchor point options.
14660      * Usage:
14661      *<pre><code>
14662 // default: slide the element out to the top
14663 el.slideOut();
14664
14665 // custom: slide the element out to the right with a 2-second duration
14666 el.slideOut('r', { duration: 2 });
14667
14668 // common config options shown with default values
14669 el.slideOut('t', {
14670     easing: 'easeOut',
14671     duration: 500,
14672     remove: false,
14673     useDisplay: false
14674 });
14675 </code></pre>
14676      * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
14677      * @param {Object} options (optional) Object literal with any of the Fx config options
14678      * @return {Ext.core.Element} The Element
14679      */
14680     slideOut: function(anchor, o) {
14681         return this.slideIn(anchor, o, true);
14682     },
14683
14684     /**
14685      * Fades the element out while slowly expanding it in all directions.  When the effect is completed, the 
14686      * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
14687      * Usage:
14688      *<pre><code>
14689 // default
14690 el.puff();
14691
14692 // common config options shown with default values
14693 el.puff({
14694     easing: 'easeOut',
14695     duration: 500,
14696     useDisplay: false
14697 });
14698 </code></pre>
14699      * @param {Object} options (optional) Object literal with any of the Fx config options
14700      * @return {Ext.core.Element} The Element
14701      */
14702
14703     puff: function(obj) {
14704         var me = this,
14705             beforeAnim;
14706         obj = Ext.applyIf(obj || {}, {
14707             easing: 'ease-out',
14708             duration: 500,
14709             useDisplay: false
14710         });
14711
14712         beforeAnim = function() {
14713             me.clearOpacity();
14714             me.show();
14715
14716             var box = me.getBox(),
14717                 fontSize = me.getStyle('fontSize'),
14718                 position = me.getPositioning();
14719             this.to = {
14720                 width: box.width * 2,
14721                 height: box.height * 2,
14722                 x: box.x - (box.width / 2),
14723                 y: box.y - (box.height /2),
14724                 opacity: 0,
14725                 fontSize: '200%'
14726             };
14727             this.on('afteranimate',function() {
14728                 if (me.dom) {
14729                     if (obj.useDisplay) {
14730                         me.setDisplayed(false);
14731                     } else {
14732                         me.hide();
14733                     }
14734                     me.clearOpacity();  
14735                     me.setPositioning(position);
14736                     me.setStyle({fontSize: fontSize});
14737                 }
14738             });
14739         };
14740
14741         me.animate({
14742             duration: obj.duration,
14743             easing: obj.easing,
14744             listeners: {
14745                 beforeanimate: {
14746                     fn: beforeAnim
14747                 }
14748             }
14749         });
14750         return me;
14751     },
14752
14753     /**
14754      * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
14755      * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still 
14756      * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
14757      * Usage:
14758      *<pre><code>
14759 // default
14760 el.switchOff();
14761
14762 // all config options shown with default values
14763 el.switchOff({
14764     easing: 'easeIn',
14765     duration: .3,
14766     remove: false,
14767     useDisplay: false
14768 });
14769 </code></pre>
14770      * @param {Object} options (optional) Object literal with any of the Fx config options
14771      * @return {Ext.core.Element} The Element
14772      */
14773     switchOff: function(obj) {
14774         var me = this,
14775             beforeAnim;
14776         
14777         obj = Ext.applyIf(obj || {}, {
14778             easing: 'ease-in',
14779             duration: 500,
14780             remove: false,
14781             useDisplay: false
14782         });
14783
14784         beforeAnim = function() {
14785             var animScope = this,
14786                 size = me.getSize(),
14787                 xy = me.getXY(),
14788                 keyframe, position;
14789             me.clearOpacity();
14790             me.clip();
14791             position = me.getPositioning();
14792
14793             keyframe = Ext.create('Ext.fx.Animator', {
14794                 target: me,
14795                 duration: obj.duration,
14796                 easing: obj.easing,
14797                 keyframes: {
14798                     33: {
14799                         opacity: 0.3
14800                     },
14801                     66: {
14802                         height: 1,
14803                         y: xy[1] + size.height / 2
14804                     },
14805                     100: {
14806                         width: 1,
14807                         x: xy[0] + size.width / 2
14808                     }
14809                 }
14810             });
14811             keyframe.on('afteranimate', function() {
14812                 if (obj.useDisplay) {
14813                     me.setDisplayed(false);
14814                 } else {
14815                     me.hide();
14816                 }  
14817                 me.clearOpacity();
14818                 me.setPositioning(position);
14819                 me.setSize(size);
14820                 animScope.end();
14821             });
14822         };
14823         me.animate({
14824             duration: (obj.duration * 2),
14825             listeners: {
14826                 beforeanimate: {
14827                     fn: beforeAnim
14828                 }
14829             }
14830         });
14831         return me;
14832     },
14833
14834    /**
14835     * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
14836     * Usage:
14837 <pre><code>
14838 // default: a single light blue ripple
14839 el.frame();
14840
14841 // custom: 3 red ripples lasting 3 seconds total
14842 el.frame("#ff0000", 3, { duration: 3 });
14843
14844 // common config options shown with default values
14845 el.frame("#C3DAF9", 1, {
14846     duration: 1 //duration of each individual ripple.
14847     // Note: Easing is not configurable and will be ignored if included
14848 });
14849 </code></pre>
14850     * @param {String} color (optional) The color of the border.  Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
14851     * @param {Number} count (optional) The number of ripples to display (defaults to 1)
14852     * @param {Object} options (optional) Object literal with any of the Fx config options
14853     * @return {Ext.core.Element} The Element
14854     */
14855     frame : function(color, count, obj){
14856         var me = this,
14857             beforeAnim;
14858
14859         color = color || '#C3DAF9';
14860         count = count || 1;
14861         obj = obj || {};
14862
14863         beforeAnim = function() {
14864             me.show();
14865             var animScope = this,
14866                 box = me.getBox(),
14867                 proxy = Ext.getBody().createChild({
14868                     style: {
14869                         position : 'absolute',
14870                         'pointer-events': 'none',
14871                         'z-index': 35000,
14872                         border : '0px solid ' + color
14873                     }
14874                 }),
14875                 proxyAnim;
14876             proxyAnim = Ext.create('Ext.fx.Anim', {
14877                 target: proxy,
14878                 duration: obj.duration || 1000,
14879                 iterations: count,
14880                 from: {
14881                     top: box.y,
14882                     left: box.x,
14883                     borderWidth: 0,
14884                     opacity: 1,
14885                     height: box.height,
14886                     width: box.width
14887                 },
14888                 to: {
14889                     top: box.y - 20,
14890                     left: box.x - 20,
14891                     borderWidth: 10,
14892                     opacity: 0,
14893                     height: box.height + 40,
14894                     width: box.width + 40
14895                 }
14896             });
14897             proxyAnim.on('afteranimate', function() {
14898                 proxy.remove();
14899                 animScope.end();
14900             });
14901         };
14902
14903         me.animate({
14904             duration: (obj.duration * 2) || 2000,
14905             listeners: {
14906                 beforeanimate: {
14907                     fn: beforeAnim
14908                 }
14909             }
14910         });
14911         return me;
14912     },
14913
14914     /**
14915      * Slides the element while fading it out of view.  An anchor point can be optionally passed to set the 
14916      * ending point of the effect.
14917      * Usage:
14918      *<pre><code>
14919 // default: slide the element downward while fading out
14920 el.ghost();
14921
14922 // custom: slide the element out to the right with a 2-second duration
14923 el.ghost('r', { duration: 2 });
14924
14925 // common config options shown with default values
14926 el.ghost('b', {
14927     easing: 'easeOut',
14928     duration: 500
14929 });
14930 </code></pre>
14931      * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
14932      * @param {Object} options (optional) Object literal with any of the Fx config options
14933      * @return {Ext.core.Element} The Element
14934      */
14935     ghost: function(anchor, obj) {
14936         var me = this,
14937             beforeAnim;
14938
14939         anchor = anchor || "b";
14940         beforeAnim = function() {
14941             var width = me.getWidth(),
14942                 height = me.getHeight(),
14943                 xy = me.getXY(),
14944                 position = me.getPositioning(),
14945                 to = {
14946                     opacity: 0
14947                 };
14948             switch (anchor) {
14949                 case 't':
14950                     to.y = xy[1] - height;
14951                     break;
14952                 case 'l':
14953                     to.x = xy[0] - width;
14954                     break;
14955                 case 'r':
14956                     to.x = xy[0] + width;
14957                     break;
14958                 case 'b':
14959                     to.y = xy[1] + height;
14960                     break;
14961                 case 'tl':
14962                     to.x = xy[0] - width;
14963                     to.y = xy[1] - height;
14964                     break;
14965                 case 'bl':
14966                     to.x = xy[0] - width;
14967                     to.y = xy[1] + height;
14968                     break;
14969                 case 'br':
14970                     to.x = xy[0] + width;
14971                     to.y = xy[1] + height;
14972                     break;
14973                 case 'tr':
14974                     to.x = xy[0] + width;
14975                     to.y = xy[1] - height;
14976                     break;
14977             }
14978             this.to = to;
14979             this.on('afteranimate', function () {
14980                 if (me.dom) {
14981                     me.hide();
14982                     me.clearOpacity();
14983                     me.setPositioning(position);
14984                 }
14985             });
14986         };
14987
14988         me.animate(Ext.applyIf(obj || {}, {
14989             duration: 500,
14990             easing: 'ease-out',
14991             listeners: {
14992                 beforeanimate: {
14993                     fn: beforeAnim
14994                 }
14995             }
14996         }));
14997         return me;
14998     },
14999
15000     /**
15001      * Highlights the Element by setting a color (applies to the background-color by default, but can be
15002      * changed using the "attr" config option) and then fading back to the original color. If no original
15003      * color is available, you should provide the "endColor" config option which will be cleared after the animation.
15004      * Usage:
15005 <pre><code>
15006 // default: highlight background to yellow
15007 el.highlight();
15008
15009 // custom: highlight foreground text to blue for 2 seconds
15010 el.highlight("0000ff", { attr: 'color', duration: 2 });
15011
15012 // common config options shown with default values
15013 el.highlight("ffff9c", {
15014     attr: "backgroundColor", //can be any valid CSS property (attribute) that supports a color value
15015     endColor: (current color) or "ffffff",
15016     easing: 'easeIn',
15017     duration: 1000
15018 });
15019 </code></pre>
15020      * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
15021      * @param {Object} options (optional) Object literal with any of the Fx config options
15022      * @return {Ext.core.Element} The Element
15023      */ 
15024     highlight: function(color, o) {
15025         var me = this,
15026             dom = me.dom,
15027             from = {},
15028             restore, to, attr, lns, event, fn;
15029
15030         o = o || {};
15031         lns = o.listeners || {};
15032         attr = o.attr || 'backgroundColor';
15033         from[attr] = color || 'ffff9c';
15034         
15035         if (!o.to) {
15036             to = {};
15037             to[attr] = o.endColor || me.getColor(attr, 'ffffff', '');
15038         }
15039         else {
15040             to = o.to;
15041         }
15042         
15043         // Don't apply directly on lns, since we reference it in our own callbacks below
15044         o.listeners = Ext.apply(Ext.apply({}, lns), {
15045             beforeanimate: function() {
15046                 restore = dom.style[attr];
15047                 me.clearOpacity();
15048                 me.show();
15049                 
15050                 event = lns.beforeanimate;
15051                 if (event) {
15052                     fn = event.fn || event;
15053                     return fn.apply(event.scope || lns.scope || window, arguments);
15054                 }
15055             },
15056             afteranimate: function() {
15057                 if (dom) {
15058                     dom.style[attr] = restore;
15059                 }
15060                 
15061                 event = lns.afteranimate;
15062                 if (event) {
15063                     fn = event.fn || event;
15064                     fn.apply(event.scope || lns.scope || window, arguments);
15065                 }
15066             }
15067         });
15068
15069         me.animate(Ext.apply({}, o, {
15070             duration: 1000,
15071             easing: 'ease-in',
15072             from: from,
15073             to: to
15074         }));
15075         return me;
15076     },
15077
15078    /**
15079     * @deprecated 4.0
15080     * Creates a pause before any subsequent queued effects begin.  If there are
15081     * no effects queued after the pause it will have no effect.
15082     * Usage:
15083 <pre><code>
15084 el.pause(1);
15085 </code></pre>
15086     * @param {Number} seconds The length of time to pause (in seconds)
15087     * @return {Ext.Element} The Element
15088     */
15089     pause: function(ms) {
15090         var me = this;
15091         Ext.fx.Manager.setFxDefaults(me.id, {
15092             delay: ms
15093         });
15094         return me;
15095     },
15096
15097    /**
15098     * Fade an element in (from transparent to opaque).  The ending opacity can be specified
15099     * using the <tt>{@link #endOpacity}</tt> config option.
15100     * Usage:
15101 <pre><code>
15102 // default: fade in from opacity 0 to 100%
15103 el.fadeIn();
15104
15105 // custom: fade in from opacity 0 to 75% over 2 seconds
15106 el.fadeIn({ endOpacity: .75, duration: 2});
15107
15108 // common config options shown with default values
15109 el.fadeIn({
15110     endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
15111     easing: 'easeOut',
15112     duration: 500
15113 });
15114 </code></pre>
15115     * @param {Object} options (optional) Object literal with any of the Fx config options
15116     * @return {Ext.Element} The Element
15117     */
15118     fadeIn: function(o) {
15119         this.animate(Ext.apply({}, o, {
15120             opacity: 1
15121         }));
15122         return this;
15123     },
15124
15125    /**
15126     * Fade an element out (from opaque to transparent).  The ending opacity can be specified
15127     * using the <tt>{@link #endOpacity}</tt> config option.  Note that IE may require
15128     * <tt>{@link #useDisplay}:true</tt> in order to redisplay correctly.
15129     * Usage:
15130 <pre><code>
15131 // default: fade out from the element's current opacity to 0
15132 el.fadeOut();
15133
15134 // custom: fade out from the element's current opacity to 25% over 2 seconds
15135 el.fadeOut({ endOpacity: .25, duration: 2});
15136
15137 // common config options shown with default values
15138 el.fadeOut({
15139     endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
15140     easing: 'easeOut',
15141     duration: 500,
15142     remove: false,
15143     useDisplay: false
15144 });
15145 </code></pre>
15146     * @param {Object} options (optional) Object literal with any of the Fx config options
15147     * @return {Ext.Element} The Element
15148     */
15149     fadeOut: function(o) {
15150         this.animate(Ext.apply({}, o, {
15151             opacity: 0
15152         }));
15153         return this;
15154     },
15155
15156    /**
15157     * @deprecated 4.0
15158     * Animates the transition of an element's dimensions from a starting height/width
15159     * to an ending height/width.  This method is a convenience implementation of {@link shift}.
15160     * Usage:
15161 <pre><code>
15162 // change height and width to 100x100 pixels
15163 el.scale(100, 100);
15164
15165 // common config options shown with default values.  The height and width will default to
15166 // the element&#39;s existing values if passed as null.
15167 el.scale(
15168     [element&#39;s width],
15169     [element&#39;s height], {
15170         easing: 'easeOut',
15171         duration: .35
15172     }
15173 );
15174 </code></pre>
15175     * @param {Number} width  The new width (pass undefined to keep the original width)
15176     * @param {Number} height  The new height (pass undefined to keep the original height)
15177     * @param {Object} options (optional) Object literal with any of the Fx config options
15178     * @return {Ext.Element} The Element
15179     */
15180     scale: function(w, h, o) {
15181         this.animate(Ext.apply({}, o, {
15182             width: w,
15183             height: h
15184         }));
15185         return this;
15186     },
15187
15188    /**
15189     * @deprecated 4.0
15190     * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
15191     * Any of these properties not specified in the config object will not be changed.  This effect 
15192     * requires that at least one new dimension, position or opacity setting must be passed in on
15193     * the config object in order for the function to have any effect.
15194     * Usage:
15195 <pre><code>
15196 // slide the element horizontally to x position 200 while changing the height and opacity
15197 el.shift({ x: 200, height: 50, opacity: .8 });
15198
15199 // common config options shown with default values.
15200 el.shift({
15201     width: [element&#39;s width],
15202     height: [element&#39;s height],
15203     x: [element&#39;s x position],
15204     y: [element&#39;s y position],
15205     opacity: [element&#39;s opacity],
15206     easing: 'easeOut',
15207     duration: .35
15208 });
15209 </code></pre>
15210     * @param {Object} options  Object literal with any of the Fx config options
15211     * @return {Ext.Element} The Element
15212     */
15213     shift: function(config) {
15214         this.animate(config);
15215         return this;
15216     }
15217 });
15218
15219 /**
15220  * @class Ext.core.Element
15221  */
15222 Ext.applyIf(Ext.core.Element, {
15223     unitRe: /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i,
15224     camelRe: /(-[a-z])/gi,
15225     opacityRe: /alpha\(opacity=(.*)\)/i,
15226     cssRe: /([a-z0-9-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi,
15227     propertyCache: {},
15228     defaultUnit : "px",
15229     borders: {l: 'border-left-width', r: 'border-right-width', t: 'border-top-width', b: 'border-bottom-width'},
15230     paddings: {l: 'padding-left', r: 'padding-right', t: 'padding-top', b: 'padding-bottom'},
15231     margins: {l: 'margin-left', r: 'margin-right', t: 'margin-top', b: 'margin-bottom'},
15232
15233     // Reference the prototype's version of the method. Signatures are identical.
15234     addUnits : Ext.core.Element.prototype.addUnits,
15235
15236     /**
15237      * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
15238      * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
15239      * @static
15240      * @param {Number|String} box The encoded margins
15241      * @return {Object} An object with margin sizes for top, right, bottom and left
15242      */
15243     parseBox : function(box) {
15244         if (Ext.isObject(box)) {
15245             return {
15246                 top: box.top || 0,
15247                 right: box.right || 0,
15248                 bottom: box.bottom || 0,
15249                 left: box.left || 0
15250             };
15251         } else {
15252             if (typeof box != 'string') {
15253                 box = box.toString();
15254             }
15255             var parts  = box.split(' '),
15256                 ln = parts.length;
15257     
15258             if (ln == 1) {
15259                 parts[1] = parts[2] = parts[3] = parts[0];
15260             }
15261             else if (ln == 2) {
15262                 parts[2] = parts[0];
15263                 parts[3] = parts[1];
15264             }
15265             else if (ln == 3) {
15266                 parts[3] = parts[1];
15267             }
15268     
15269             return {
15270                 top   :parseFloat(parts[0]) || 0,
15271                 right :parseFloat(parts[1]) || 0,
15272                 bottom:parseFloat(parts[2]) || 0,
15273                 left  :parseFloat(parts[3]) || 0
15274             };
15275         }
15276         
15277     },
15278     
15279     /**
15280      * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
15281      * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
15282      * @static
15283      * @param {Number|String} box The encoded margins
15284      * @param {String} units The type of units to add
15285      * @return {String} An string with unitized (px if units is not specified) metrics for top, right, bottom and left
15286      */
15287     unitizeBox : function(box, units) {
15288         var A = this.addUnits,
15289             B = this.parseBox(box);
15290             
15291         return A(B.top, units) + ' ' +
15292                A(B.right, units) + ' ' +
15293                A(B.bottom, units) + ' ' +
15294                A(B.left, units);
15295         
15296     },
15297
15298     // private
15299     camelReplaceFn : function(m, a) {
15300         return a.charAt(1).toUpperCase();
15301     },
15302
15303     /**
15304      * Normalizes CSS property keys from dash delimited to camel case JavaScript Syntax.
15305      * For example:
15306      * <ul>
15307      *  <li>border-width -> borderWidth</li>
15308      *  <li>padding-top -> paddingTop</li>
15309      * </ul>
15310      * @static
15311      * @param {String} prop The property to normalize
15312      * @return {String} The normalized string
15313      */
15314     normalize : function(prop) {
15315         if (prop == 'float') {
15316             prop = Ext.supports.Float ? 'cssFloat' : 'styleFloat';
15317         }
15318         return this.propertyCache[prop] || (this.propertyCache[prop] = prop.replace(this.camelRe, this.camelReplaceFn));
15319     },
15320
15321     /**
15322      * Retrieves the document height
15323      * @static
15324      * @return {Number} documentHeight
15325      */
15326     getDocumentHeight: function() {
15327         return Math.max(!Ext.isStrict ? document.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight());
15328     },
15329
15330     /**
15331      * Retrieves the document width
15332      * @static
15333      * @return {Number} documentWidth
15334      */
15335     getDocumentWidth: function() {
15336         return Math.max(!Ext.isStrict ? document.body.scrollWidth : document.documentElement.scrollWidth, this.getViewportWidth());
15337     },
15338
15339     /**
15340      * Retrieves the viewport height of the window.
15341      * @static
15342      * @return {Number} viewportHeight
15343      */
15344     getViewportHeight: function(){
15345         return window.innerHeight;
15346     },
15347
15348     /**
15349      * Retrieves the viewport width of the window.
15350      * @static
15351      * @return {Number} viewportWidth
15352      */
15353     getViewportWidth : function() {
15354         return window.innerWidth;
15355     },
15356
15357     /**
15358      * Retrieves the viewport size of the window.
15359      * @static
15360      * @return {Object} object containing width and height properties
15361      */
15362     getViewSize : function() {
15363         return {
15364             width: window.innerWidth,
15365             height: window.innerHeight
15366         };
15367     },
15368
15369     /**
15370      * Retrieves the current orientation of the window. This is calculated by
15371      * determing if the height is greater than the width.
15372      * @static
15373      * @return {String} Orientation of window: 'portrait' or 'landscape'
15374      */
15375     getOrientation : function() {
15376         if (Ext.supports.OrientationChange) {
15377             return (window.orientation == 0) ? 'portrait' : 'landscape';
15378         }
15379         
15380         return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape';
15381     },
15382
15383     /** 
15384      * Returns the top Element that is located at the passed coordinates
15385      * @static
15386      * @param {Number} x The x coordinate
15387      * @param {Number} x The y coordinate
15388      * @return {String} The found Element
15389      */
15390     fromPoint: function(x, y) {
15391         return Ext.get(document.elementFromPoint(x, y));
15392     },
15393     
15394     /**
15395      * Converts a CSS string into an object with a property for each style.
15396      * <p>
15397      * The sample code below would return an object with 2 properties, one
15398      * for background-color and one for color.</p>
15399      * <pre><code>
15400 var css = 'background-color: red;color: blue; ';
15401 console.log(Ext.core.Element.parseStyles(css));
15402      * </code></pre>
15403      * @static
15404      * @param {String} styles A CSS string
15405      * @return {Object} styles
15406      */
15407     parseStyles: function(styles){
15408         var out = {},
15409             cssRe = this.cssRe,
15410             matches;
15411             
15412         if (styles) {
15413             // Since we're using the g flag on the regex, we need to set the lastIndex.
15414             // This automatically happens on some implementations, but not others, see:
15415             // http://stackoverflow.com/questions/2645273/javascript-regular-expression-literal-persists-between-function-calls
15416             // http://blog.stevenlevithan.com/archives/fixing-javascript-regexp
15417             cssRe.lastIndex = 0;
15418             while ((matches = cssRe.exec(styles))) {
15419                 out[matches[1]] = matches[2];
15420             }
15421         }
15422         return out;
15423     }
15424 });
15425
15426 /**
15427  * @class Ext.CompositeElementLite
15428  * <p>This class encapsulates a <i>collection</i> of DOM elements, providing methods to filter
15429  * members, or to perform collective actions upon the whole set.</p>
15430  * <p>Although they are not listed, this class supports all of the methods of {@link Ext.core.Element} and
15431  * {@link Ext.fx.Anim}. The methods from these classes will be performed on all the elements in this collection.</p>
15432  * Example:<pre><code>
15433 var els = Ext.select("#some-el div.some-class");
15434 // or select directly from an existing element
15435 var el = Ext.get('some-el');
15436 el.select('div.some-class');
15437
15438 els.setWidth(100); // all elements become 100 width
15439 els.hide(true); // all elements fade out and hide
15440 // or
15441 els.setWidth(100).hide(true);
15442 </code></pre>
15443  */
15444 Ext.CompositeElementLite = function(els, root){
15445     /**
15446      * <p>The Array of DOM elements which this CompositeElement encapsulates. Read-only.</p>
15447      * <p>This will not <i>usually</i> be accessed in developers' code, but developers wishing
15448      * to augment the capabilities of the CompositeElementLite class may use it when adding
15449      * methods to the class.</p>
15450      * <p>For example to add the <code>nextAll</code> method to the class to <b>add</b> all
15451      * following siblings of selected elements, the code would be</p><code><pre>
15452 Ext.override(Ext.CompositeElementLite, {
15453     nextAll: function() {
15454         var els = this.elements, i, l = els.length, n, r = [], ri = -1;
15455
15456 //      Loop through all elements in this Composite, accumulating
15457 //      an Array of all siblings.
15458         for (i = 0; i < l; i++) {
15459             for (n = els[i].nextSibling; n; n = n.nextSibling) {
15460                 r[++ri] = n;
15461             }
15462         }
15463
15464 //      Add all found siblings to this Composite
15465         return this.add(r);
15466     }
15467 });</pre></code>
15468      * @type Array
15469      * @property elements
15470      */
15471     this.elements = [];
15472     this.add(els, root);
15473     this.el = new Ext.core.Element.Flyweight();
15474 };
15475
15476 Ext.CompositeElementLite.prototype = {
15477     isComposite: true,
15478
15479     // private
15480     getElement : function(el){
15481         // Set the shared flyweight dom property to the current element
15482         var e = this.el;
15483         e.dom = el;
15484         e.id = el.id;
15485         return e;
15486     },
15487
15488     // private
15489     transformElement : function(el){
15490         return Ext.getDom(el);
15491     },
15492
15493     /**
15494      * Returns the number of elements in this Composite.
15495      * @return Number
15496      */
15497     getCount : function(){
15498         return this.elements.length;
15499     },
15500     /**
15501      * Adds elements to this Composite object.
15502      * @param {Mixed} els Either an Array of DOM elements to add, or another Composite object who's elements should be added.
15503      * @return {CompositeElement} This Composite object.
15504      */
15505     add : function(els, root){
15506         var me = this,
15507             elements = me.elements;
15508         if(!els){
15509             return this;
15510         }
15511         if(typeof els == "string"){
15512             els = Ext.core.Element.selectorFunction(els, root);
15513         }else if(els.isComposite){
15514             els = els.elements;
15515         }else if(!Ext.isIterable(els)){
15516             els = [els];
15517         }
15518
15519         for(var i = 0, len = els.length; i < len; ++i){
15520             elements.push(me.transformElement(els[i]));
15521         }
15522         return me;
15523     },
15524
15525     invoke : function(fn, args){
15526         var me = this,
15527             els = me.elements,
15528             len = els.length,
15529             e,
15530             i;
15531
15532         for(i = 0; i < len; i++) {
15533             e = els[i];
15534             if(e){
15535                 Ext.core.Element.prototype[fn].apply(me.getElement(e), args);
15536             }
15537         }
15538         return me;
15539     },
15540     /**
15541      * Returns a flyweight Element of the dom element object at the specified index
15542      * @param {Number} index
15543      * @return {Ext.core.Element}
15544      */
15545     item : function(index){
15546         var me = this,
15547             el = me.elements[index],
15548             out = null;
15549
15550         if(el){
15551             out = me.getElement(el);
15552         }
15553         return out;
15554     },
15555
15556     // fixes scope with flyweight
15557     addListener : function(eventName, handler, scope, opt){
15558         var els = this.elements,
15559             len = els.length,
15560             i, e;
15561
15562         for(i = 0; i<len; i++) {
15563             e = els[i];
15564             if(e) {
15565                 Ext.EventManager.on(e, eventName, handler, scope || e, opt);
15566             }
15567         }
15568         return this;
15569     },
15570     /**
15571      * <p>Calls the passed function for each element in this composite.</p>
15572      * @param {Function} fn The function to call. The function is passed the following parameters:<ul>
15573      * <li><b>el</b> : Element<div class="sub-desc">The current Element in the iteration.
15574      * <b>This is the flyweight (shared) Ext.core.Element instance, so if you require a
15575      * a reference to the dom node, use el.dom.</b></div></li>
15576      * <li><b>c</b> : Composite<div class="sub-desc">This Composite object.</div></li>
15577      * <li><b>idx</b> : Number<div class="sub-desc">The zero-based index in the iteration.</div></li>
15578      * </ul>
15579      * @param {Object} scope (optional) The scope (<i>this</i> reference) in which the function is executed. (defaults to the Element)
15580      * @return {CompositeElement} this
15581      */
15582     each : function(fn, scope){
15583         var me = this,
15584             els = me.elements,
15585             len = els.length,
15586             i, e;
15587
15588         for(i = 0; i<len; i++) {
15589             e = els[i];
15590             if(e){
15591                 e = this.getElement(e);
15592                 if(fn.call(scope || e, e, me, i) === false){
15593                     break;
15594                 }
15595             }
15596         }
15597         return me;
15598     },
15599
15600     /**
15601     * Clears this Composite and adds the elements passed.
15602     * @param {Mixed} els Either an array of DOM elements, or another Composite from which to fill this Composite.
15603     * @return {CompositeElement} this
15604     */
15605     fill : function(els){
15606         var me = this;
15607         me.elements = [];
15608         me.add(els);
15609         return me;
15610     },
15611
15612     /**
15613      * Filters this composite to only elements that match the passed selector.
15614      * @param {String/Function} selector A string CSS selector or a comparison function.
15615      * The comparison function will be called with the following arguments:<ul>
15616      * <li><code>el</code> : Ext.core.Element<div class="sub-desc">The current DOM element.</div></li>
15617      * <li><code>index</code> : Number<div class="sub-desc">The current index within the collection.</div></li>
15618      * </ul>
15619      * @return {CompositeElement} this
15620      */
15621     filter : function(selector){
15622         var els = [],
15623             me = this,
15624             fn = Ext.isFunction(selector) ? selector
15625                 : function(el){
15626                     return el.is(selector);
15627                 };
15628
15629         me.each(function(el, self, i) {
15630             if (fn(el, i) !== false) {
15631                 els[els.length] = me.transformElement(el);
15632             }
15633         });
15634         
15635         me.elements = els;
15636         return me;
15637     },
15638
15639     /**
15640      * Find the index of the passed element within the composite collection.
15641      * @param el {Mixed} The id of an element, or an Ext.core.Element, or an HtmlElement to find within the composite collection.
15642      * @return Number The index of the passed Ext.core.Element in the composite collection, or -1 if not found.
15643      */
15644     indexOf : function(el){
15645         return Ext.Array.indexOf(this.elements, this.transformElement(el));
15646     },
15647
15648     /**
15649     * Replaces the specified element with the passed element.
15650     * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
15651     * to replace.
15652     * @param {Mixed} replacement The id of an element or the Element itself.
15653     * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
15654     * @return {CompositeElement} this
15655     */
15656     replaceElement : function(el, replacement, domReplace){
15657         var index = !isNaN(el) ? el : this.indexOf(el),
15658             d;
15659         if(index > -1){
15660             replacement = Ext.getDom(replacement);
15661             if(domReplace){
15662                 d = this.elements[index];
15663                 d.parentNode.insertBefore(replacement, d);
15664                 Ext.removeNode(d);
15665             }
15666             this.elements.splice(index, 1, replacement);
15667         }
15668         return this;
15669     },
15670
15671     /**
15672      * Removes all elements.
15673      */
15674     clear : function(){
15675         this.elements = [];
15676     }
15677 };
15678
15679 Ext.CompositeElementLite.prototype.on = Ext.CompositeElementLite.prototype.addListener;
15680
15681 /**
15682  * @private
15683  * Copies all of the functions from Ext.core.Element's prototype onto CompositeElementLite's prototype.
15684  * This is called twice - once immediately below, and once again after additional Ext.core.Element
15685  * are added in Ext JS
15686  */
15687 Ext.CompositeElementLite.importElementMethods = function() {
15688     var fnName,
15689         ElProto = Ext.core.Element.prototype,
15690         CelProto = Ext.CompositeElementLite.prototype;
15691
15692     for (fnName in ElProto) {
15693         if (typeof ElProto[fnName] == 'function'){
15694             (function(fnName) {
15695                 CelProto[fnName] = CelProto[fnName] || function() {
15696                     return this.invoke(fnName, arguments);
15697                 };
15698             }).call(CelProto, fnName);
15699
15700         }
15701     }
15702 };
15703
15704 Ext.CompositeElementLite.importElementMethods();
15705
15706 if(Ext.DomQuery){
15707     Ext.core.Element.selectorFunction = Ext.DomQuery.select;
15708 }
15709
15710 /**
15711  * Selects elements based on the passed CSS selector to enable {@link Ext.core.Element Element} methods
15712  * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
15713  * {@link Ext.CompositeElementLite CompositeElementLite} object.
15714  * @param {String/Array} selector The CSS selector or an array of elements
15715  * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
15716  * @return {CompositeElementLite/CompositeElement}
15717  * @member Ext.core.Element
15718  * @method select
15719  */
15720 Ext.core.Element.select = function(selector, root){
15721     var els;
15722     if(typeof selector == "string"){
15723         els = Ext.core.Element.selectorFunction(selector, root);
15724     }else if(selector.length !== undefined){
15725         els = selector;
15726     }else{
15727         Ext.Error.raise({
15728             sourceClass: "Ext.core.Element",
15729             sourceMethod: "select",
15730             selector: selector,
15731             root: root,
15732             msg: "Invalid selector specified: " + selector
15733         });
15734     }
15735     return new Ext.CompositeElementLite(els);
15736 };
15737 /**
15738  * Selects elements based on the passed CSS selector to enable {@link Ext.core.Element Element} methods
15739  * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
15740  * {@link Ext.CompositeElementLite CompositeElementLite} object.
15741  * @param {String/Array} selector The CSS selector or an array of elements
15742  * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
15743  * @return {CompositeElementLite/CompositeElement}
15744  * @member Ext
15745  * @method select
15746  */
15747 Ext.select = Ext.core.Element.select;
15748
15749 /**
15750  * @class Ext.util.DelayedTask
15751  * 
15752  * The DelayedTask class provides a convenient way to "buffer" the execution of a method,
15753  * performing setTimeout where a new timeout cancels the old timeout. When called, the
15754  * task will wait the specified time period before executing. If durng that time period,
15755  * the task is called again, the original call will be cancelled. This continues so that
15756  * the function is only called a single time for each iteration.
15757  * 
15758  * This method is especially useful for things like detecting whether a user has finished
15759  * typing in a text field. An example would be performing validation on a keypress. You can
15760  * use this class to buffer the keypress events for a certain number of milliseconds, and
15761  * perform only if they stop for that amount of time.  
15762  * 
15763  * ## Usage
15764  * 
15765  *     var task = new Ext.util.DelayedTask(function(){
15766  *         alert(Ext.getDom('myInputField').value.length);
15767  *     });
15768  *     
15769  *     // Wait 500ms before calling our function. If the user presses another key
15770  *     // during that 500ms, it will be cancelled and we'll wait another 500ms.
15771  *     Ext.get('myInputField').on('keypress', function(){
15772  *         task.{@link #delay}(500);
15773  *     });
15774  * 
15775  * Note that we are using a DelayedTask here to illustrate a point. The configuration
15776  * option `buffer` for {@link Ext.util.Observable#addListener addListener/on} will
15777  * also setup a delayed task for you to buffer events.
15778  * 
15779  * @constructor The parameters to this constructor serve as defaults and are not required.
15780  * @param {Function} fn (optional) The default function to call.
15781  * @param {Object} scope The default scope (The <code><b>this</b></code> reference) in which the
15782  * function is called. If not specified, <code>this</code> will refer to the browser window.
15783  * @param {Array} args (optional) The default Array of arguments.
15784  */
15785 Ext.util.DelayedTask = function(fn, scope, args) {
15786     var me = this,
15787         id,
15788         call = function() {
15789             clearInterval(id);
15790             id = null;
15791             fn.apply(scope, args || []);
15792         };
15793
15794     /**
15795      * Cancels any pending timeout and queues a new one
15796      * @param {Number} delay The milliseconds to delay
15797      * @param {Function} newFn (optional) Overrides function passed to constructor
15798      * @param {Object} newScope (optional) Overrides scope passed to constructor. Remember that if no scope
15799      * is specified, <code>this</code> will refer to the browser window.
15800      * @param {Array} newArgs (optional) Overrides args passed to constructor
15801      */
15802     this.delay = function(delay, newFn, newScope, newArgs) {
15803         me.cancel();
15804         fn = newFn || fn;
15805         scope = newScope || scope;
15806         args = newArgs || args;
15807         id = setInterval(call, delay);
15808     };
15809
15810     /**
15811      * Cancel the last queued timeout
15812      */
15813     this.cancel = function(){
15814         if (id) {
15815             clearInterval(id);
15816             id = null;
15817         }
15818     };
15819 };
15820 Ext.require('Ext.util.DelayedTask', function() {
15821
15822     Ext.util.Event = Ext.extend(Object, (function() {
15823         function createBuffered(handler, listener, o, scope) {
15824             listener.task = new Ext.util.DelayedTask();
15825             return function() {
15826                 listener.task.delay(o.buffer, handler, scope, Ext.Array.toArray(arguments));
15827             };
15828         }
15829
15830         function createDelayed(handler, listener, o, scope) {
15831             return function() {
15832                 var task = new Ext.util.DelayedTask();
15833                 if (!listener.tasks) {
15834                     listener.tasks = [];
15835                 }
15836                 listener.tasks.push(task);
15837                 task.delay(o.delay || 10, handler, scope, Ext.Array.toArray(arguments));
15838             };
15839         }
15840
15841         function createSingle(handler, listener, o, scope) {
15842             return function() {
15843                 listener.ev.removeListener(listener.fn, scope);
15844                 return handler.apply(scope, arguments);
15845             };
15846         }
15847
15848         return {
15849             isEvent: true,
15850
15851             constructor: function(observable, name) {
15852                 this.name = name;
15853                 this.observable = observable;
15854                 this.listeners = [];
15855             },
15856
15857             addListener: function(fn, scope, options) {
15858                 var me = this,
15859                     listener;
15860                     scope = scope || me.observable;
15861
15862                 if (!fn) {
15863                     Ext.Error.raise({
15864                         sourceClass: Ext.getClassName(this.observable),
15865                         sourceMethod: "addListener",
15866                         msg: "The specified callback function is undefined"
15867                     });
15868                 }
15869
15870                 if (!me.isListening(fn, scope)) {
15871                     listener = me.createListener(fn, scope, options);
15872                     if (me.firing) {
15873                         // if we are currently firing this event, don't disturb the listener loop
15874                         me.listeners = me.listeners.slice(0);
15875                     }
15876                     me.listeners.push(listener);
15877                 }
15878             },
15879
15880             createListener: function(fn, scope, o) {
15881                 o = o || {};
15882                 scope = scope || this.observable;
15883
15884                 var listener = {
15885                         fn: fn,
15886                         scope: scope,
15887                         o: o,
15888                         ev: this
15889                     },
15890                     handler = fn;
15891
15892                 // The order is important. The 'single' wrapper must be wrapped by the 'buffer' and 'delayed' wrapper
15893                 // because the event removal that the single listener does destroys the listener's DelayedTask(s)
15894                 if (o.single) {
15895                     handler = createSingle(handler, listener, o, scope);
15896                 }
15897                 if (o.delay) {
15898                     handler = createDelayed(handler, listener, o, scope);
15899                 }
15900                 if (o.buffer) {
15901                     handler = createBuffered(handler, listener, o, scope);
15902                 }
15903
15904                 listener.fireFn = handler;
15905                 return listener;
15906             },
15907
15908             findListener: function(fn, scope) {
15909                 var listeners = this.listeners,
15910                 i = listeners.length,
15911                 listener,
15912                 s;
15913
15914                 while (i--) {
15915                     listener = listeners[i];
15916                     if (listener) {
15917                         s = listener.scope;
15918                         if (listener.fn == fn && (s == scope || s == this.observable)) {
15919                             return i;
15920                         }
15921                     }
15922                 }
15923
15924                 return - 1;
15925             },
15926
15927             isListening: function(fn, scope) {
15928                 return this.findListener(fn, scope) !== -1;
15929             },
15930
15931             removeListener: function(fn, scope) {
15932                 var me = this,
15933                     index,
15934                     listener,
15935                     k;
15936                 index = me.findListener(fn, scope);
15937                 if (index != -1) {
15938                     listener = me.listeners[index];
15939
15940                     if (me.firing) {
15941                         me.listeners = me.listeners.slice(0);
15942                     }
15943
15944                     // cancel and remove a buffered handler that hasn't fired yet
15945                     if (listener.task) {
15946                         listener.task.cancel();
15947                         delete listener.task;
15948                     }
15949
15950                     // cancel and remove all delayed handlers that haven't fired yet
15951                     k = listener.tasks && listener.tasks.length;
15952                     if (k) {
15953                         while (k--) {
15954                             listener.tasks[k].cancel();
15955                         }
15956                         delete listener.tasks;
15957                     }
15958
15959                     // remove this listener from the listeners array
15960                     me.listeners.splice(index, 1);
15961                     return true;
15962                 }
15963
15964                 return false;
15965             },
15966
15967             // Iterate to stop any buffered/delayed events
15968             clearListeners: function() {
15969                 var listeners = this.listeners,
15970                     i = listeners.length;
15971
15972                 while (i--) {
15973                     this.removeListener(listeners[i].fn, listeners[i].scope);
15974                 }
15975             },
15976
15977             fire: function() {
15978                 var me = this,
15979                     listeners = me.listeners,
15980                     count = listeners.length,
15981                     i,
15982                     args,
15983                     listener;
15984
15985                 if (count > 0) {
15986                     me.firing = true;
15987                     for (i = 0; i < count; i++) {
15988                         listener = listeners[i];
15989                         args = arguments.length ? Array.prototype.slice.call(arguments, 0) : [];
15990                         if (listener.o) {
15991                             args.push(listener.o);
15992                         }
15993                         if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) {
15994                             return (me.firing = false);
15995                         }
15996                     }
15997                 }
15998                 me.firing = false;
15999                 return true;
16000             }
16001         };
16002     })());
16003 });
16004
16005 /**
16006  * @class Ext.EventManager
16007  * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
16008  * several useful events directly.
16009  * See {@link Ext.EventObject} for more details on normalized event objects.
16010  * @singleton
16011  */
16012 Ext.EventManager = {
16013
16014     // --------------------- onReady ---------------------
16015
16016     /**
16017      * Check if we have bound our global onReady listener
16018      * @private
16019      */
16020     hasBoundOnReady: false,
16021
16022     /**
16023      * Check if fireDocReady has been called
16024      * @private
16025      */
16026     hasFiredReady: false,
16027
16028     /**
16029      * Timer for the document ready event in old IE versions
16030      * @private
16031      */
16032     readyTimeout: null,
16033
16034     /**
16035      * Checks if we have bound an onreadystatechange event
16036      * @private
16037      */
16038     hasOnReadyStateChange: false,
16039
16040     /**
16041      * Holds references to any onReady functions
16042      * @private
16043      */
16044     readyEvent: new Ext.util.Event(),
16045
16046     /**
16047      * Check the ready state for old IE versions
16048      * @private
16049      * @return {Boolean} True if the document is ready
16050      */
16051     checkReadyState: function(){
16052         var me = Ext.EventManager;
16053
16054         if(window.attachEvent){
16055             // See here for reference: http://javascript.nwbox.com/IEContentLoaded/
16056             if (window != top) {
16057                 return false;
16058             }
16059             try{
16060                 document.documentElement.doScroll('left');
16061             }catch(e){
16062                 return false;
16063             }
16064             me.fireDocReady();
16065             return true;
16066         }
16067         if (document.readyState == 'complete') {
16068             me.fireDocReady();
16069             return true;
16070         }
16071         me.readyTimeout = setTimeout(arguments.callee, 2);
16072         return false;
16073     },
16074
16075     /**
16076      * Binds the appropriate browser event for checking if the DOM has loaded.
16077      * @private
16078      */
16079     bindReadyEvent: function(){
16080         var me = Ext.EventManager;
16081         if (me.hasBoundOnReady) {
16082             return;
16083         }
16084
16085         if (document.addEventListener) {
16086             document.addEventListener('DOMContentLoaded', me.fireDocReady, false);
16087             // fallback, load will ~always~ fire
16088             window.addEventListener('load', me.fireDocReady, false);
16089         } else {
16090             // check if the document is ready, this will also kick off the scroll checking timer
16091             if (!me.checkReadyState()) {
16092                 document.attachEvent('onreadystatechange', me.checkReadyState);
16093                 me.hasOnReadyStateChange = true;
16094             }
16095             // fallback, onload will ~always~ fire
16096             window.attachEvent('onload', me.fireDocReady, false);
16097         }
16098         me.hasBoundOnReady = true;
16099     },
16100
16101     /**
16102      * We know the document is loaded, so trigger any onReady events.
16103      * @private
16104      */
16105     fireDocReady: function(){
16106         var me = Ext.EventManager;
16107
16108         // only unbind these events once
16109         if (!me.hasFiredReady) {
16110             me.hasFiredReady = true;
16111
16112             if (document.addEventListener) {
16113                 document.removeEventListener('DOMContentLoaded', me.fireDocReady, false);
16114                 window.removeEventListener('load', me.fireDocReady, false);
16115             } else {
16116                 if (me.readyTimeout !== null) {
16117                     clearTimeout(me.readyTimeout);
16118                 }
16119                 if (me.hasOnReadyStateChange) {
16120                     document.detachEvent('onreadystatechange', me.checkReadyState);
16121                 }
16122                 window.detachEvent('onload', me.fireDocReady);
16123             }
16124             Ext.supports.init();
16125         }
16126         if (!Ext.isReady) {
16127             Ext.isReady = true;
16128             me.onWindowUnload();
16129             me.readyEvent.fire();
16130         }
16131     },
16132
16133     /**
16134      * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
16135      * accessed shorthanded as Ext.onReady().
16136      * @param {Function} fn The method the event invokes.
16137      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
16138      * @param {boolean} options (optional) Options object as passed to {@link Ext.core.Element#addListener}.
16139      */
16140     onDocumentReady: function(fn, scope, options){
16141         options = options || {};
16142         var me = Ext.EventManager,
16143             readyEvent = me.readyEvent;
16144
16145         // force single to be true so our event is only ever fired once.
16146         options.single = true;
16147
16148         // Document already loaded, let's just fire it
16149         if (Ext.isReady) {
16150             readyEvent.addListener(fn, scope, options);
16151             readyEvent.fire();
16152         } else {
16153             options.delay = options.delay || 1;
16154             readyEvent.addListener(fn, scope, options);
16155             me.bindReadyEvent();
16156         }
16157     },
16158
16159
16160     // --------------------- event binding ---------------------
16161
16162     /**
16163      * Contains a list of all document mouse downs, so we can ensure they fire even when stopEvent is called.
16164      * @private
16165      */
16166     stoppedMouseDownEvent: new Ext.util.Event(),
16167
16168     /**
16169      * Options to parse for the 4th argument to addListener.
16170      * @private
16171      */
16172     propRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|freezeEvent)$/,
16173
16174     /**
16175      * Get the id of the element. If one has not been assigned, automatically assign it.
16176      * @param {Mixed} element The element to get the id for.
16177      * @return {String} id
16178      */
16179     getId : function(element) {
16180         var skipGarbageCollection = false,
16181             id;
16182     
16183         element = Ext.getDom(element);
16184     
16185         if (element === document || element === window) {
16186             id = element === document ? Ext.documentId : Ext.windowId;
16187         }
16188         else {
16189             id = Ext.id(element);
16190         }
16191         // skip garbage collection for special elements (window, document, iframes)
16192         if (element && (element.getElementById || element.navigator)) {
16193             skipGarbageCollection = true;
16194         }
16195     
16196         if (!Ext.cache[id]){
16197             Ext.core.Element.addToCache(new Ext.core.Element(element), id);
16198             if (skipGarbageCollection) {
16199                 Ext.cache[id].skipGarbageCollection = true;
16200             }
16201         }
16202         return id;
16203     },
16204
16205     /**
16206      * Convert a "config style" listener into a set of flat arguments so they can be passed to addListener
16207      * @private
16208      * @param {Object} element The element the event is for
16209      * @param {Object} event The event configuration
16210      * @param {Object} isRemove True if a removal should be performed, otherwise an add will be done.
16211      */
16212     prepareListenerConfig: function(element, config, isRemove){
16213         var me = this,
16214             propRe = me.propRe,
16215             key, value, args;
16216
16217         // loop over all the keys in the object
16218         for (key in config) {
16219             if (config.hasOwnProperty(key)) {
16220                 // if the key is something else then an event option
16221                 if (!propRe.test(key)) {
16222                     value = config[key];
16223                     // if the value is a function it must be something like click: function(){}, scope: this
16224                     // which means that there might be multiple event listeners with shared options
16225                     if (Ext.isFunction(value)) {
16226                         // shared options
16227                         args = [element, key, value, config.scope, config];
16228                     } else {
16229                         // if its not a function, it must be an object like click: {fn: function(){}, scope: this}
16230                         args = [element, key, value.fn, value.scope, value];
16231                     }
16232
16233                     if (isRemove === true) {
16234                         me.removeListener.apply(this, args);
16235                     } else {
16236                         me.addListener.apply(me, args);
16237                     }
16238                 }
16239             }
16240         }
16241     },
16242
16243     /**
16244      * Normalize cross browser event differences
16245      * @private
16246      * @param {Object} eventName The event name
16247      * @param {Object} fn The function to execute
16248      * @return {Object} The new event name/function
16249      */
16250     normalizeEvent: function(eventName, fn){
16251         if (/mouseenter|mouseleave/.test(eventName) && !Ext.supports.MouseEnterLeave) {
16252             if (fn) {
16253                 fn = Ext.Function.createInterceptor(fn, this.contains, this);
16254             }
16255             eventName = eventName == 'mouseenter' ? 'mouseover' : 'mouseout';
16256         } else if (eventName == 'mousewheel' && !Ext.supports.MouseWheel && !Ext.isOpera){
16257             eventName = 'DOMMouseScroll';
16258         }
16259         return {
16260             eventName: eventName,
16261             fn: fn
16262         };
16263     },
16264
16265     /**
16266      * Checks whether the event's relatedTarget is contained inside (or <b>is</b>) the element.
16267      * @private
16268      * @param {Object} event
16269      */
16270     contains: function(event){
16271         var parent = event.browserEvent.currentTarget,
16272             child = this.getRelatedTarget(event);
16273
16274         if (parent && parent.firstChild) {
16275             while (child) {
16276                 if (child === parent) {
16277                     return false;
16278                 }
16279                 child = child.parentNode;
16280                 if (child && (child.nodeType != 1)) {
16281                     child = null;
16282                 }
16283             }
16284         }
16285         return true;
16286     },
16287
16288     /**
16289     * Appends an event handler to an element.  The shorthand version {@link #on} is equivalent.  Typically you will
16290     * use {@link Ext.core.Element#addListener} directly on an Element in favor of calling this version.
16291     * @param {String/HTMLElement} el The html element or id to assign the event handler to.
16292     * @param {String} eventName The name of the event to listen for.
16293     * @param {Function} handler The handler function the event invokes. This function is passed
16294     * the following parameters:<ul>
16295     * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
16296     * <li>t : Element<div class="sub-desc">The {@link Ext.core.Element Element} which was the target of the event.
16297     * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
16298     * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
16299     * </ul>
16300     * @param {Object} scope (optional) The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.
16301     * @param {Object} options (optional) An object containing handler configuration properties.
16302     * This may contain any of the following properties:<ul>
16303     * <li>scope : Object<div class="sub-desc">The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.</div></li>
16304     * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
16305     * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
16306     * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
16307     * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
16308     * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
16309     * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
16310     * <li>single : Boolean<div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li>
16311     * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
16312     * by the specified number of milliseconds. If the event fires again within that time, the original
16313     * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
16314     * <li>target : Element<div class="sub-desc">Only call the handler if the event was fired on the target Element, <i>not</i> if the event was bubbled up from a child node.</div></li>
16315     * </ul><br>
16316     * <p>See {@link Ext.core.Element#addListener} for examples of how to use these options.</p>
16317     */
16318     addListener: function(element, eventName, fn, scope, options){
16319         // Check if we've been passed a "config style" event.
16320         if (Ext.isObject(eventName)) {
16321             this.prepareListenerConfig(element, eventName);
16322             return;
16323         }
16324
16325         var dom = Ext.getDom(element),
16326             bind,
16327             wrap;
16328
16329         if (!dom){
16330             Ext.Error.raise({
16331                 sourceClass: 'Ext.EventManager',
16332                 sourceMethod: 'addListener',
16333                 targetElement: element,
16334                 eventName: eventName,
16335                 msg: 'Error adding "' + eventName + '\" listener for nonexistent element "' + element + '"'
16336             });
16337         }
16338         if (!fn) {
16339             Ext.Error.raise({
16340                 sourceClass: 'Ext.EventManager',
16341                 sourceMethod: 'addListener',
16342                 targetElement: element,
16343                 eventName: eventName,
16344                 msg: 'Error adding "' + eventName + '\" listener. The handler function is undefined.'
16345             });
16346         }
16347
16348         // create the wrapper function
16349         options = options || {};
16350
16351         bind = this.normalizeEvent(eventName, fn);
16352         wrap = this.createListenerWrap(dom, eventName, bind.fn, scope, options);
16353
16354
16355         if (dom.attachEvent) {
16356             dom.attachEvent('on' + bind.eventName, wrap);
16357         } else {
16358             dom.addEventListener(bind.eventName, wrap, options.capture || false);
16359         }
16360
16361         if (dom == document && eventName == 'mousedown') {
16362             this.stoppedMouseDownEvent.addListener(wrap);
16363         }
16364
16365         // add all required data into the event cache
16366         this.getEventListenerCache(dom, eventName).push({
16367             fn: fn,
16368             wrap: wrap,
16369             scope: scope
16370         });
16371     },
16372
16373     /**
16374     * Removes an event handler from an element.  The shorthand version {@link #un} is equivalent.  Typically
16375     * you will use {@link Ext.core.Element#removeListener} directly on an Element in favor of calling this version.
16376     * @param {String/HTMLElement} el The id or html element from which to remove the listener.
16377     * @param {String} eventName The name of the event.
16378     * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
16379     * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
16380     * then this must refer to the same object.
16381     */
16382     removeListener : function(element, eventName, fn, scope) {
16383         // handle our listener config object syntax
16384         if (Ext.isObject(eventName)) {
16385             this.prepareListenerConfig(element, eventName, true);
16386             return;
16387         }
16388
16389         var dom = Ext.getDom(element),
16390             cache = this.getEventListenerCache(dom, eventName),
16391             bindName = this.normalizeEvent(eventName).eventName,
16392             i = cache.length, j,
16393             listener, wrap, tasks;
16394
16395
16396         while (i--) {
16397             listener = cache[i];
16398
16399             if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) {
16400                 wrap = listener.wrap;
16401
16402                 // clear buffered calls
16403                 if (wrap.task) {
16404                     clearTimeout(wrap.task);
16405                     delete wrap.task;
16406                 }
16407
16408                 // clear delayed calls
16409                 j = wrap.tasks && wrap.tasks.length;
16410                 if (j) {
16411                     while (j--) {
16412                         clearTimeout(wrap.tasks[j]);
16413                     }
16414                     delete wrap.tasks;
16415                 }
16416
16417                 if (dom.detachEvent) {
16418                     dom.detachEvent('on' + bindName, wrap);
16419                 } else {
16420                     dom.removeEventListener(bindName, wrap, false);
16421                 }
16422
16423                 if (wrap && dom == document && eventName == 'mousedown') {
16424                     this.stoppedMouseDownEvent.removeListener(wrap);
16425                 }
16426
16427                 // remove listener from cache
16428                 cache.splice(i, 1);
16429             }
16430         }
16431     },
16432
16433     /**
16434     * Removes all event handers from an element.  Typically you will use {@link Ext.core.Element#removeAllListeners}
16435     * directly on an Element in favor of calling this version.
16436     * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
16437     */
16438     removeAll : function(element){
16439         var dom = Ext.getDom(element),
16440             cache, ev;
16441         if (!dom) {
16442             return;
16443         }
16444         cache = this.getElementEventCache(dom);
16445
16446         for (ev in cache) {
16447             if (cache.hasOwnProperty(ev)) {
16448                 this.removeListener(dom, ev);
16449             }
16450         }
16451         Ext.cache[dom.id].events = {};
16452     },
16453
16454     /**
16455      * Recursively removes all previous added listeners from an element and its children. Typically you will use {@link Ext.core.Element#purgeAllListeners}
16456      * directly on an Element in favor of calling this version.
16457      * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
16458      * @param {String} eventName (optional) The name of the event.
16459      */
16460     purgeElement : function(element, eventName) {
16461         var dom = Ext.getDom(element),
16462             i = 0, len;
16463
16464         if(eventName) {
16465             this.removeListener(dom, eventName);
16466         }
16467         else {
16468             this.removeAll(dom);
16469         }
16470
16471         if(dom && dom.childNodes) {
16472             for(len = element.childNodes.length; i < len; i++) {
16473                 this.purgeElement(element.childNodes[i], eventName);
16474             }
16475         }
16476     },
16477
16478     /**
16479      * Create the wrapper function for the event
16480      * @private
16481      * @param {HTMLElement} dom The dom element
16482      * @param {String} ename The event name
16483      * @param {Function} fn The function to execute
16484      * @param {Object} scope The scope to execute callback in
16485      * @param {Object} o The options
16486      */
16487     createListenerWrap : function(dom, ename, fn, scope, options) {
16488         options = !Ext.isObject(options) ? {} : options;
16489
16490         var f = ['if(!Ext) {return;}'],
16491             gen;
16492
16493         if(options.buffer || options.delay || options.freezeEvent) {
16494             f.push('e = new Ext.EventObjectImpl(e, ' + (options.freezeEvent ? 'true' : 'false' ) + ');');
16495         } else {
16496             f.push('e = Ext.EventObject.setEvent(e);');
16497         }
16498
16499         if (options.delegate) {
16500             f.push('var t = e.getTarget("' + options.delegate + '", this);');
16501             f.push('if(!t) {return;}');
16502         } else {
16503             f.push('var t = e.target;');
16504         }
16505
16506         if (options.target) {
16507             f.push('if(e.target !== options.target) {return;}');
16508         }
16509
16510         if(options.stopEvent) {
16511             f.push('e.stopEvent();');
16512         } else {
16513             if(options.preventDefault) {
16514                 f.push('e.preventDefault();');
16515             }
16516             if(options.stopPropagation) {
16517                 f.push('e.stopPropagation();');
16518             }
16519         }
16520
16521         if(options.normalized === false) {
16522             f.push('e = e.browserEvent;');
16523         }
16524
16525         if(options.buffer) {
16526             f.push('(wrap.task && clearTimeout(wrap.task));');
16527             f.push('wrap.task = setTimeout(function(){');
16528         }
16529
16530         if(options.delay) {
16531             f.push('wrap.tasks = wrap.tasks || [];');
16532             f.push('wrap.tasks.push(setTimeout(function(){');
16533         }
16534
16535         // finally call the actual handler fn
16536         f.push('fn.call(scope || dom, e, t, options);');
16537
16538         if(options.single) {
16539             f.push('Ext.EventManager.removeListener(dom, ename, fn, scope);');
16540         }
16541
16542         if(options.delay) {
16543             f.push('}, ' + options.delay + '));');
16544         }
16545
16546         if(options.buffer) {
16547             f.push('}, ' + options.buffer + ');');
16548         }
16549
16550         gen = Ext.functionFactory('e', 'options', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', f.join('\n'));
16551
16552         return function wrap(e, args) {
16553             gen.call(dom, e, options, fn, scope, ename, dom, wrap, args);
16554         };
16555     },
16556
16557     /**
16558      * Get the event cache for a particular element for a particular event
16559      * @private
16560      * @param {HTMLElement} element The element
16561      * @param {Object} eventName The event name
16562      * @return {Array} The events for the element
16563      */
16564     getEventListenerCache : function(element, eventName) {
16565         var eventCache = this.getElementEventCache(element);
16566         return eventCache[eventName] || (eventCache[eventName] = []);
16567     },
16568
16569     /**
16570      * Gets the event cache for the object
16571      * @private
16572      * @param {HTMLElement} element The element
16573      * @return {Object} The event cache for the object
16574      */
16575     getElementEventCache : function(element) {
16576         var elementCache = Ext.cache[this.getId(element)];
16577         return elementCache.events || (elementCache.events = {});
16578     },
16579
16580     // --------------------- utility methods ---------------------
16581     mouseLeaveRe: /(mouseout|mouseleave)/,
16582     mouseEnterRe: /(mouseover|mouseenter)/,
16583
16584     /**
16585      * Stop the event (preventDefault and stopPropagation)
16586      * @param {Event} The event to stop
16587      */
16588     stopEvent: function(event) {
16589         this.stopPropagation(event);
16590         this.preventDefault(event);
16591     },
16592
16593     /**
16594      * Cancels bubbling of the event.
16595      * @param {Event} The event to stop bubbling.
16596      */
16597     stopPropagation: function(event) {
16598         event = event.browserEvent || event;
16599         if (event.stopPropagation) {
16600             event.stopPropagation();
16601         } else {
16602             event.cancelBubble = true;
16603         }
16604     },
16605
16606     /**
16607      * Prevents the browsers default handling of the event.
16608      * @param {Event} The event to prevent the default
16609      */
16610     preventDefault: function(event) {
16611         event = event.browserEvent || event;
16612         if (event.preventDefault) {
16613             event.preventDefault();
16614         } else {
16615             event.returnValue = false;
16616             // Some keys events require setting the keyCode to -1 to be prevented
16617             try {
16618               // all ctrl + X and F1 -> F12
16619               if (event.ctrlKey || event.keyCode > 111 && event.keyCode < 124) {
16620                   event.keyCode = -1;
16621               }
16622             } catch (e) {
16623                 // see this outdated document http://support.microsoft.com/kb/934364/en-us for more info
16624             }
16625         }
16626     },
16627
16628     /**
16629      * Gets the related target from the event.
16630      * @param {Object} event The event
16631      * @return {HTMLElement} The related target.
16632      */
16633     getRelatedTarget: function(event) {
16634         event = event.browserEvent || event;
16635         var target = event.relatedTarget;
16636         if (!target) {
16637             if (this.mouseLeaveRe.test(event.type)) {
16638                 target = event.toElement;
16639             } else if (this.mouseEnterRe.test(event.type)) {
16640                 target = event.fromElement;
16641             }
16642         }
16643         return this.resolveTextNode(target);
16644     },
16645
16646     /**
16647      * Gets the x coordinate from the event
16648      * @param {Object} event The event
16649      * @return {Number} The x coordinate
16650      */
16651     getPageX: function(event) {
16652         return this.getXY(event)[0];
16653     },
16654
16655     /**
16656      * Gets the y coordinate from the event
16657      * @param {Object} event The event
16658      * @return {Number} The y coordinate
16659      */
16660     getPageY: function(event) {
16661         return this.getXY(event)[1];
16662     },
16663
16664     /**
16665      * Gets the x & ycoordinate from the event
16666      * @param {Object} event The event
16667      * @return {Array} The x/y coordinate
16668      */
16669     getPageXY: function(event) {
16670         event = event.browserEvent || event;
16671         var x = event.pageX,
16672             y = event.pageY,
16673             doc = document.documentElement,
16674             body = document.body;
16675
16676         // pageX/pageY not available (undefined, not null), use clientX/clientY instead
16677         if (!x && x !== 0) {
16678             x = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
16679             y = event.clientY + (doc && doc.scrollTop  || body && body.scrollTop  || 0) - (doc && doc.clientTop  || body && body.clientTop  || 0);
16680         }
16681         return [x, y];
16682     },
16683
16684     /**
16685      * Gets the target of the event.
16686      * @param {Object} event The event
16687      * @return {HTMLElement} target
16688      */
16689     getTarget: function(event) {
16690         event = event.browserEvent || event;
16691         return this.resolveTextNode(event.target || event.srcElement);
16692     },
16693
16694     /**
16695      * Resolve any text nodes accounting for browser differences.
16696      * @private
16697      * @param {HTMLElement} node The node
16698      * @return {HTMLElement} The resolved node
16699      */
16700     // technically no need to browser sniff this, however it makes no sense to check this every time, for every event, whether the string is equal.
16701     resolveTextNode: Ext.isGecko ?
16702         function(node) {
16703             if (!node) {
16704                 return;
16705             }
16706             // work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197
16707             var s = HTMLElement.prototype.toString.call(node);
16708             if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') {
16709                 return;
16710             }
16711                 return node.nodeType == 3 ? node.parentNode: node;
16712             }: function(node) {
16713                 return node && node.nodeType == 3 ? node.parentNode: node;
16714             },
16715
16716     // --------------------- custom event binding ---------------------
16717
16718     // Keep track of the current width/height
16719     curWidth: 0,
16720     curHeight: 0,
16721
16722     /**
16723      * Adds a listener to be notified when the browser window is resized and provides resize event buffering (100 milliseconds),
16724      * passes new viewport width and height to handlers.
16725      * @param {Function} fn      The handler function the window resize event invokes.
16726      * @param {Object}   scope   The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
16727      * @param {boolean}  options Options object as passed to {@link Ext.core.Element#addListener}
16728      */
16729     onWindowResize: function(fn, scope, options){
16730         var resize = this.resizeEvent;
16731         if(!resize){
16732             this.resizeEvent = resize = new Ext.util.Event();
16733             this.on(window, 'resize', this.fireResize, this, {buffer: 100});
16734         }
16735         resize.addListener(fn, scope, options);
16736     },
16737
16738     /**
16739      * Fire the resize event.
16740      * @private
16741      */
16742     fireResize: function(){
16743         var me = this,
16744             w = Ext.core.Element.getViewWidth(),
16745             h = Ext.core.Element.getViewHeight();
16746
16747          //whacky problem in IE where the resize event will sometimes fire even though the w/h are the same.
16748          if(me.curHeight != h || me.curWidth != w){
16749              me.curHeight = h;
16750              me.curWidth = w;
16751              me.resizeEvent.fire(w, h);
16752          }
16753     },
16754
16755     /**
16756      * Removes the passed window resize listener.
16757      * @param {Function} fn        The method the event invokes
16758      * @param {Object}   scope    The scope of handler
16759      */
16760     removeResizeListener: function(fn, scope){
16761         if (this.resizeEvent) {
16762             this.resizeEvent.removeListener(fn, scope);
16763         }
16764     },
16765
16766     onWindowUnload: function() {
16767         var unload = this.unloadEvent;
16768         if (!unload) {
16769             this.unloadEvent = unload = new Ext.util.Event();
16770             this.addListener(window, 'unload', this.fireUnload, this);
16771         }
16772     },
16773
16774     /**
16775      * Fires the unload event for items bound with onWindowUnload
16776      * @private
16777      */
16778     fireUnload: function() {
16779         // wrap in a try catch, could have some problems during unload
16780         try {
16781             this.removeUnloadListener();
16782             // Work around FF3 remembering the last scroll position when refreshing the grid and then losing grid view
16783             if (Ext.isGecko3) {
16784                 var gridviews = Ext.ComponentQuery.query('gridview'),
16785                     i = 0,
16786                     ln = gridviews.length;
16787                 for (; i < ln; i++) {
16788                     gridviews[i].scrollToTop();
16789                 }
16790             }
16791             // Purge all elements in the cache
16792             var el,
16793                 cache = Ext.cache;
16794             for (el in cache) {
16795                 if (cache.hasOwnProperty(el)) {
16796                     Ext.EventManager.removeAll(el);
16797                 }
16798             }
16799         } catch(e) {
16800         }
16801     },
16802
16803     /**
16804      * Removes the passed window unload listener.
16805      * @param {Function} fn        The method the event invokes
16806      * @param {Object}   scope    The scope of handler
16807      */
16808     removeUnloadListener: function(){
16809         if (this.unloadEvent) {
16810             this.removeListener(window, 'unload', this.fireUnload);
16811         }
16812     },
16813
16814     /**
16815      * note 1: IE fires ONLY the keydown event on specialkey autorepeat
16816      * note 2: Safari < 3.1, Gecko (Mac/Linux) & Opera fire only the keypress event on specialkey autorepeat
16817      * (research done by @Jan Wolter at http://unixpapa.com/js/key.html)
16818      * @private
16819      */
16820     useKeyDown: Ext.isWebKit ?
16821                    parseInt(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1], 10) >= 525 :
16822                    !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera),
16823
16824     /**
16825      * Indicates which event to use for getting key presses.
16826      * @return {String} The appropriate event name.
16827      */
16828     getKeyEvent: function(){
16829         return this.useKeyDown ? 'keydown' : 'keypress';
16830     }
16831 };
16832
16833 /**
16834  * Alias for {@link Ext.Loader#onReady Ext.Loader.onReady} with withDomReady set to true
16835  * @member Ext
16836  * @method onReady
16837  */
16838 Ext.onReady = function(fn, scope, options) {
16839     Ext.Loader.onReady(fn, scope, true, options);
16840 };
16841
16842 /**
16843  * Alias for {@link Ext.EventManager#onDocumentReady Ext.EventManager.onDocumentReady}
16844  * @member Ext
16845  * @method onDocumentReady
16846  */
16847 Ext.onDocumentReady = Ext.EventManager.onDocumentReady;
16848
16849 /**
16850  * Alias for {@link Ext.EventManager#addListener Ext.EventManager.addListener}
16851  * @member Ext.EventManager
16852  * @method on
16853  */
16854 Ext.EventManager.on = Ext.EventManager.addListener;
16855
16856 /**
16857  * Alias for {@link Ext.EventManager#removeListener Ext.EventManager.removeListener}
16858  * @member Ext.EventManager
16859  * @method un
16860  */
16861 Ext.EventManager.un = Ext.EventManager.removeListener;
16862
16863 (function(){
16864     var initExtCss = function() {
16865         // find the body element
16866         var bd = document.body || document.getElementsByTagName('body')[0],
16867             baseCSSPrefix = Ext.baseCSSPrefix,
16868             cls = [],
16869             htmlCls = [],
16870             html;
16871
16872         if (!bd) {
16873             return false;
16874         }
16875
16876         html = bd.parentNode;
16877
16878         //Let's keep this human readable!
16879         if (Ext.isIE) {
16880             cls.push(baseCSSPrefix + 'ie');
16881         }
16882         if (Ext.isIE6) {
16883             cls.push(baseCSSPrefix + 'ie6');
16884         }
16885         if (Ext.isIE7) {
16886             cls.push(baseCSSPrefix + 'ie7');
16887         }
16888         if (Ext.isIE8) {
16889             cls.push(baseCSSPrefix + 'ie8');
16890         }
16891         if (Ext.isIE9) {
16892             cls.push(baseCSSPrefix + 'ie9');
16893         }
16894         if (Ext.isGecko) {
16895             cls.push(baseCSSPrefix + 'gecko');
16896         }
16897         if (Ext.isGecko3) {
16898             cls.push(baseCSSPrefix + 'gecko3');
16899         }
16900         if (Ext.isGecko4) {
16901             cls.push(baseCSSPrefix + 'gecko4');
16902         }
16903         if (Ext.isOpera) {
16904             cls.push(baseCSSPrefix + 'opera');
16905         }
16906         if (Ext.isWebKit) {
16907             cls.push(baseCSSPrefix + 'webkit');
16908         }
16909         if (Ext.isSafari) {
16910             cls.push(baseCSSPrefix + 'safari');
16911         }
16912         if (Ext.isSafari2) {
16913             cls.push(baseCSSPrefix + 'safari2');
16914         }
16915         if (Ext.isSafari3) {
16916             cls.push(baseCSSPrefix + 'safari3');
16917         }
16918         if (Ext.isSafari4) {
16919             cls.push(baseCSSPrefix + 'safari4');
16920         }
16921         if (Ext.isChrome) {
16922             cls.push(baseCSSPrefix + 'chrome');
16923         }
16924         if (Ext.isMac) {
16925             cls.push(baseCSSPrefix + 'mac');
16926         }
16927         if (Ext.isLinux) {
16928             cls.push(baseCSSPrefix + 'linux');
16929         }
16930         if (!Ext.supports.CSS3BorderRadius) {
16931             cls.push(baseCSSPrefix + 'nbr');
16932         }
16933         if (!Ext.supports.CSS3LinearGradient) {
16934             cls.push(baseCSSPrefix + 'nlg');
16935         }
16936         if (!Ext.scopeResetCSS) {
16937             cls.push(baseCSSPrefix + 'reset');
16938         }
16939
16940         // add to the parent to allow for selectors x-strict x-border-box, also set the isBorderBox property correctly
16941         if (html) {
16942             if (Ext.isStrict && (Ext.isIE6 || Ext.isIE7)) {
16943                 Ext.isBorderBox = false;
16944             }
16945             else {
16946                 Ext.isBorderBox = true;
16947             }
16948
16949             htmlCls.push(baseCSSPrefix + (Ext.isBorderBox ? 'border-box' : 'strict'));
16950             if (!Ext.isStrict) {
16951                 htmlCls.push(baseCSSPrefix + 'quirks');
16952                 if (Ext.isIE && !Ext.isStrict) {
16953                     Ext.isIEQuirks = true;
16954                 }
16955             }
16956             Ext.fly(html, '_internal').addCls(htmlCls);
16957         }
16958
16959         Ext.fly(bd, '_internal').addCls(cls);
16960         return true;
16961     };
16962
16963     Ext.onReady(initExtCss);
16964 })();
16965
16966 /**
16967  * @class Ext.EventObject
16968
16969 Just as {@link Ext.core.Element} wraps around a native DOM node, Ext.EventObject
16970 wraps the browser's native event-object normalizing cross-browser differences,
16971 such as which mouse button is clicked, keys pressed, mechanisms to stop
16972 event-propagation along with a method to prevent default actions from taking place.
16973
16974 For example:
16975
16976     function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
16977         e.preventDefault();
16978         var target = e.getTarget(); // same as t (the target HTMLElement)
16979         ...
16980     }
16981
16982     var myDiv = {@link Ext#get Ext.get}("myDiv");  // get reference to an {@link Ext.core.Element}
16983     myDiv.on(         // 'on' is shorthand for addListener
16984         "click",      // perform an action on click of myDiv
16985         handleClick   // reference to the action handler
16986     );
16987
16988     // other methods to do the same:
16989     Ext.EventManager.on("myDiv", 'click', handleClick);
16990     Ext.EventManager.addListener("myDiv", 'click', handleClick);
16991
16992  * @singleton
16993  * @markdown
16994  */
16995 Ext.define('Ext.EventObjectImpl', {
16996     uses: ['Ext.util.Point'],
16997
16998     /** Key constant @type Number */
16999     BACKSPACE: 8,
17000     /** Key constant @type Number */
17001     TAB: 9,
17002     /** Key constant @type Number */
17003     NUM_CENTER: 12,
17004     /** Key constant @type Number */
17005     ENTER: 13,
17006     /** Key constant @type Number */
17007     RETURN: 13,
17008     /** Key constant @type Number */
17009     SHIFT: 16,
17010     /** Key constant @type Number */
17011     CTRL: 17,
17012     /** Key constant @type Number */
17013     ALT: 18,
17014     /** Key constant @type Number */
17015     PAUSE: 19,
17016     /** Key constant @type Number */
17017     CAPS_LOCK: 20,
17018     /** Key constant @type Number */
17019     ESC: 27,
17020     /** Key constant @type Number */
17021     SPACE: 32,
17022     /** Key constant @type Number */
17023     PAGE_UP: 33,
17024     /** Key constant @type Number */
17025     PAGE_DOWN: 34,
17026     /** Key constant @type Number */
17027     END: 35,
17028     /** Key constant @type Number */
17029     HOME: 36,
17030     /** Key constant @type Number */
17031     LEFT: 37,
17032     /** Key constant @type Number */
17033     UP: 38,
17034     /** Key constant @type Number */
17035     RIGHT: 39,
17036     /** Key constant @type Number */
17037     DOWN: 40,
17038     /** Key constant @type Number */
17039     PRINT_SCREEN: 44,
17040     /** Key constant @type Number */
17041     INSERT: 45,
17042     /** Key constant @type Number */
17043     DELETE: 46,
17044     /** Key constant @type Number */
17045     ZERO: 48,
17046     /** Key constant @type Number */
17047     ONE: 49,
17048     /** Key constant @type Number */
17049     TWO: 50,
17050     /** Key constant @type Number */
17051     THREE: 51,
17052     /** Key constant @type Number */
17053     FOUR: 52,
17054     /** Key constant @type Number */
17055     FIVE: 53,
17056     /** Key constant @type Number */
17057     SIX: 54,
17058     /** Key constant @type Number */
17059     SEVEN: 55,
17060     /** Key constant @type Number */
17061     EIGHT: 56,
17062     /** Key constant @type Number */
17063     NINE: 57,
17064     /** Key constant @type Number */
17065     A: 65,
17066     /** Key constant @type Number */
17067     B: 66,
17068     /** Key constant @type Number */
17069     C: 67,
17070     /** Key constant @type Number */
17071     D: 68,
17072     /** Key constant @type Number */
17073     E: 69,
17074     /** Key constant @type Number */
17075     F: 70,
17076     /** Key constant @type Number */
17077     G: 71,
17078     /** Key constant @type Number */
17079     H: 72,
17080     /** Key constant @type Number */
17081     I: 73,
17082     /** Key constant @type Number */
17083     J: 74,
17084     /** Key constant @type Number */
17085     K: 75,
17086     /** Key constant @type Number */
17087     L: 76,
17088     /** Key constant @type Number */
17089     M: 77,
17090     /** Key constant @type Number */
17091     N: 78,
17092     /** Key constant @type Number */
17093     O: 79,
17094     /** Key constant @type Number */
17095     P: 80,
17096     /** Key constant @type Number */
17097     Q: 81,
17098     /** Key constant @type Number */
17099     R: 82,
17100     /** Key constant @type Number */
17101     S: 83,
17102     /** Key constant @type Number */
17103     T: 84,
17104     /** Key constant @type Number */
17105     U: 85,
17106     /** Key constant @type Number */
17107     V: 86,
17108     /** Key constant @type Number */
17109     W: 87,
17110     /** Key constant @type Number */
17111     X: 88,
17112     /** Key constant @type Number */
17113     Y: 89,
17114     /** Key constant @type Number */
17115     Z: 90,
17116     /** Key constant @type Number */
17117     CONTEXT_MENU: 93,
17118     /** Key constant @type Number */
17119     NUM_ZERO: 96,
17120     /** Key constant @type Number */
17121     NUM_ONE: 97,
17122     /** Key constant @type Number */
17123     NUM_TWO: 98,
17124     /** Key constant @type Number */
17125     NUM_THREE: 99,
17126     /** Key constant @type Number */
17127     NUM_FOUR: 100,
17128     /** Key constant @type Number */
17129     NUM_FIVE: 101,
17130     /** Key constant @type Number */
17131     NUM_SIX: 102,
17132     /** Key constant @type Number */
17133     NUM_SEVEN: 103,
17134     /** Key constant @type Number */
17135     NUM_EIGHT: 104,
17136     /** Key constant @type Number */
17137     NUM_NINE: 105,
17138     /** Key constant @type Number */
17139     NUM_MULTIPLY: 106,
17140     /** Key constant @type Number */
17141     NUM_PLUS: 107,
17142     /** Key constant @type Number */
17143     NUM_MINUS: 109,
17144     /** Key constant @type Number */
17145     NUM_PERIOD: 110,
17146     /** Key constant @type Number */
17147     NUM_DIVISION: 111,
17148     /** Key constant @type Number */
17149     F1: 112,
17150     /** Key constant @type Number */
17151     F2: 113,
17152     /** Key constant @type Number */
17153     F3: 114,
17154     /** Key constant @type Number */
17155     F4: 115,
17156     /** Key constant @type Number */
17157     F5: 116,
17158     /** Key constant @type Number */
17159     F6: 117,
17160     /** Key constant @type Number */
17161     F7: 118,
17162     /** Key constant @type Number */
17163     F8: 119,
17164     /** Key constant @type Number */
17165     F9: 120,
17166     /** Key constant @type Number */
17167     F10: 121,
17168     /** Key constant @type Number */
17169     F11: 122,
17170     /** Key constant @type Number */
17171     F12: 123,
17172
17173     /**
17174      * Simple click regex
17175      * @private
17176      */
17177     clickRe: /(dbl)?click/,
17178     // safari keypress events for special keys return bad keycodes
17179     safariKeys: {
17180         3: 13, // enter
17181         63234: 37, // left
17182         63235: 39, // right
17183         63232: 38, // up
17184         63233: 40, // down
17185         63276: 33, // page up
17186         63277: 34, // page down
17187         63272: 46, // delete
17188         63273: 36, // home
17189         63275: 35 // end
17190     },
17191     // normalize button clicks, don't see any way to feature detect this.
17192     btnMap: Ext.isIE ? {
17193         1: 0,
17194         4: 1,
17195         2: 2
17196     } : {
17197         0: 0,
17198         1: 1,
17199         2: 2
17200     },
17201
17202     constructor: function(event, freezeEvent){
17203         if (event) {
17204             this.setEvent(event.browserEvent || event, freezeEvent);
17205         }
17206     },
17207
17208     setEvent: function(event, freezeEvent){
17209         var me = this, button, options;
17210
17211         if (event == me || (event && event.browserEvent)) { // already wrapped
17212             return event;
17213         }
17214         me.browserEvent = event;
17215         if (event) {
17216             // normalize buttons
17217             button = event.button ? me.btnMap[event.button] : (event.which ? event.which - 1 : -1);
17218             if (me.clickRe.test(event.type) && button == -1) {
17219                 button = 0;
17220             }
17221             options = {
17222                 type: event.type,
17223                 button: button,
17224                 shiftKey: event.shiftKey,
17225                 // mac metaKey behaves like ctrlKey
17226                 ctrlKey: event.ctrlKey || event.metaKey || false,
17227                 altKey: event.altKey,
17228                 // in getKey these will be normalized for the mac
17229                 keyCode: event.keyCode,
17230                 charCode: event.charCode,
17231                 // cache the targets for the delayed and or buffered events
17232                 target: Ext.EventManager.getTarget(event),
17233                 relatedTarget: Ext.EventManager.getRelatedTarget(event),
17234                 currentTarget: event.currentTarget,
17235                 xy: (freezeEvent ? me.getXY() : null)
17236             };
17237         } else {
17238             options = {
17239                 button: -1,
17240                 shiftKey: false,
17241                 ctrlKey: false,
17242                 altKey: false,
17243                 keyCode: 0,
17244                 charCode: 0,
17245                 target: null,
17246                 xy: [0, 0]
17247             };
17248         }
17249         Ext.apply(me, options);
17250         return me;
17251     },
17252
17253     /**
17254      * Stop the event (preventDefault and stopPropagation)
17255      */
17256     stopEvent: function(){
17257         this.stopPropagation();
17258         this.preventDefault();
17259     },
17260
17261     /**
17262      * Prevents the browsers default handling of the event.
17263      */
17264     preventDefault: function(){
17265         if (this.browserEvent) {
17266             Ext.EventManager.preventDefault(this.browserEvent);
17267         }
17268     },
17269
17270     /**
17271      * Cancels bubbling of the event.
17272      */
17273     stopPropagation: function(){
17274         var browserEvent = this.browserEvent;
17275
17276         if (browserEvent) {
17277             if (browserEvent.type == 'mousedown') {
17278                 Ext.EventManager.stoppedMouseDownEvent.fire(this);
17279             }
17280             Ext.EventManager.stopPropagation(browserEvent);
17281         }
17282     },
17283
17284     /**
17285      * Gets the character code for the event.
17286      * @return {Number}
17287      */
17288     getCharCode: function(){
17289         return this.charCode || this.keyCode;
17290     },
17291
17292     /**
17293      * Returns a normalized keyCode for the event.
17294      * @return {Number} The key code
17295      */
17296     getKey: function(){
17297         return this.normalizeKey(this.keyCode || this.charCode);
17298     },
17299
17300     /**
17301      * Normalize key codes across browsers
17302      * @private
17303      * @param {Number} key The key code
17304      * @return {Number} The normalized code
17305      */
17306     normalizeKey: function(key){
17307         // can't feature detect this
17308         return Ext.isWebKit ? (this.safariKeys[key] || key) : key;
17309     },
17310
17311     /**
17312      * Gets the x coordinate of the event.
17313      * @return {Number}
17314      * @deprecated 4.0 Replaced by {@link #getX}
17315      */
17316     getPageX: function(){
17317         return this.getX();
17318     },
17319
17320     /**
17321      * Gets the y coordinate of the event.
17322      * @return {Number}
17323      * @deprecated 4.0 Replaced by {@link #getY}
17324      */
17325     getPageY: function(){
17326         return this.getY();
17327     },
17328     
17329     /**
17330      * Gets the x coordinate of the event.
17331      * @return {Number}
17332      */
17333     getX: function() {
17334         return this.getXY()[0];
17335     },    
17336     
17337     /**
17338      * Gets the y coordinate of the event.
17339      * @return {Number}
17340      */
17341     getY: function() {
17342         return this.getXY()[1];
17343     },
17344         
17345     /**
17346      * Gets the page coordinates of the event.
17347      * @return {Array} The xy values like [x, y]
17348      */
17349     getXY: function() {
17350         if (!this.xy) {
17351             // same for XY
17352             this.xy = Ext.EventManager.getPageXY(this.browserEvent);
17353         }
17354         return this.xy;
17355     },
17356
17357     /**
17358      * Gets the target for the event.
17359      * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
17360      * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body)
17361      * @param {Boolean} returnEl (optional) True to return a Ext.core.Element object instead of DOM node
17362      * @return {HTMLelement}
17363      */
17364     getTarget : function(selector, maxDepth, returnEl){
17365         if (selector) {
17366             return Ext.fly(this.target).findParent(selector, maxDepth, returnEl);
17367         }
17368         return returnEl ? Ext.get(this.target) : this.target;
17369     },
17370
17371     /**
17372      * Gets the related target.
17373      * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
17374      * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body)
17375      * @param {Boolean} returnEl (optional) True to return a Ext.core.Element object instead of DOM node
17376      * @return {HTMLElement}
17377      */
17378     getRelatedTarget : function(selector, maxDepth, returnEl){
17379         if (selector) {
17380             return Ext.fly(this.relatedTarget).findParent(selector, maxDepth, returnEl);
17381         }
17382         return returnEl ? Ext.get(this.relatedTarget) : this.relatedTarget;
17383     },
17384
17385     /**
17386      * Normalizes mouse wheel delta across browsers
17387      * @return {Number} The delta
17388      */
17389     getWheelDelta : function(){
17390         var event = this.browserEvent,
17391             delta = 0;
17392
17393         if (event.wheelDelta) { /* IE/Opera. */
17394             delta = event.wheelDelta / 120;
17395         } else if (event.detail){ /* Mozilla case. */
17396             delta = -event.detail / 3;
17397         }
17398         return delta;
17399     },
17400
17401     /**
17402     * Returns true if the target of this event is a child of el.  Unless the allowEl parameter is set, it will return false if if the target is el.
17403     * Example usage:<pre><code>
17404 // Handle click on any child of an element
17405 Ext.getBody().on('click', function(e){
17406     if(e.within('some-el')){
17407         alert('Clicked on a child of some-el!');
17408     }
17409 });
17410
17411 // Handle click directly on an element, ignoring clicks on child nodes
17412 Ext.getBody().on('click', function(e,t){
17413     if((t.id == 'some-el') && !e.within(t, true)){
17414         alert('Clicked directly on some-el!');
17415     }
17416 });
17417 </code></pre>
17418      * @param {Mixed} el The id, DOM element or Ext.core.Element to check
17419      * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
17420      * @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
17421      * @return {Boolean}
17422      */
17423     within : function(el, related, allowEl){
17424         if(el){
17425             var t = related ? this.getRelatedTarget() : this.getTarget(),
17426                 result;
17427
17428             if (t) {
17429                 result = Ext.fly(el).contains(t);
17430                 if (!result && allowEl) {
17431                     result = t == Ext.getDom(el);
17432                 }
17433                 return result;
17434             }
17435         }
17436         return false;
17437     },
17438
17439     /**
17440      * Checks if the key pressed was a "navigation" key
17441      * @return {Boolean} True if the press is a navigation keypress
17442      */
17443     isNavKeyPress : function(){
17444         var me = this,
17445             k = this.normalizeKey(me.keyCode);
17446
17447        return (k >= 33 && k <= 40) ||  // Page Up/Down, End, Home, Left, Up, Right, Down
17448        k == me.RETURN ||
17449        k == me.TAB ||
17450        k == me.ESC;
17451     },
17452
17453     /**
17454      * Checks if the key pressed was a "special" key
17455      * @return {Boolean} True if the press is a special keypress
17456      */
17457     isSpecialKey : function(){
17458         var k = this.normalizeKey(this.keyCode);
17459         return (this.type == 'keypress' && this.ctrlKey) ||
17460         this.isNavKeyPress() ||
17461         (k == this.BACKSPACE) || // Backspace
17462         (k >= 16 && k <= 20) || // Shift, Ctrl, Alt, Pause, Caps Lock
17463         (k >= 44 && k <= 46);   // Print Screen, Insert, Delete
17464     },
17465
17466     /**
17467      * Returns a point object that consists of the object coordinates.
17468      * @return {Ext.util.Point} point
17469      */
17470     getPoint : function(){
17471         var xy = this.getXY();
17472         return Ext.create('Ext.util.Point', xy[0], xy[1]);
17473     },
17474
17475    /**
17476     * Returns true if the control, meta, shift or alt key was pressed during this event.
17477     * @return {Boolean}
17478     */
17479     hasModifier : function(){
17480         return this.ctrlKey || this.altKey || this.shiftKey || this.metaKey;
17481     },
17482
17483     /**
17484      * Injects a DOM event using the data in this object and (optionally) a new target.
17485      * This is a low-level technique and not likely to be used by application code. The
17486      * currently supported event types are:
17487      * <p><b>HTMLEvents</b></p>
17488      * <ul>
17489      * <li>load</li>
17490      * <li>unload</li>
17491      * <li>select</li>
17492      * <li>change</li>
17493      * <li>submit</li>
17494      * <li>reset</li>
17495      * <li>resize</li>
17496      * <li>scroll</li>
17497      * </ul>
17498      * <p><b>MouseEvents</b></p>
17499      * <ul>
17500      * <li>click</li>
17501      * <li>dblclick</li>
17502      * <li>mousedown</li>
17503      * <li>mouseup</li>
17504      * <li>mouseover</li>
17505      * <li>mousemove</li>
17506      * <li>mouseout</li>
17507      * </ul>
17508      * <p><b>UIEvents</b></p>
17509      * <ul>
17510      * <li>focusin</li>
17511      * <li>focusout</li>
17512      * <li>activate</li>
17513      * <li>focus</li>
17514      * <li>blur</li>
17515      * </ul>
17516      * @param {Element/HTMLElement} target If specified, the target for the event. This
17517      * is likely to be used when relaying a DOM event. If not specified, {@link #getTarget}
17518      * is used to determine the target.
17519      */
17520     injectEvent: function () {
17521         var API,
17522             dispatchers = {}; // keyed by event type (e.g., 'mousedown')
17523
17524         // Good reference: http://developer.yahoo.com/yui/docs/UserAction.js.html
17525
17526         // IE9 has createEvent, but this code causes major problems with htmleditor (it
17527         // blocks all mouse events and maybe more). TODO
17528
17529         if (!Ext.isIE && document.createEvent) { // if (DOM compliant)
17530             API = {
17531                 createHtmlEvent: function (doc, type, bubbles, cancelable) {
17532                     var event = doc.createEvent('HTMLEvents');
17533
17534                     event.initEvent(type, bubbles, cancelable);
17535                     return event;
17536                 },
17537
17538                 createMouseEvent: function (doc, type, bubbles, cancelable, detail,
17539                                             clientX, clientY, ctrlKey, altKey, shiftKey, metaKey,
17540                                             button, relatedTarget) {
17541                     var event = doc.createEvent('MouseEvents'),
17542                         view = doc.defaultView || window;
17543
17544                     if (event.initMouseEvent) {
17545                         event.initMouseEvent(type, bubbles, cancelable, view, detail,
17546                                     clientX, clientY, clientX, clientY, ctrlKey, altKey,
17547                                     shiftKey, metaKey, button, relatedTarget);
17548                     } else { // old Safari
17549                         event = doc.createEvent('UIEvents');
17550                         event.initEvent(type, bubbles, cancelable);
17551                         event.view = view;
17552                         event.detail = detail;
17553                         event.screenX = clientX;
17554                         event.screenY = clientY;
17555                         event.clientX = clientX;
17556                         event.clientY = clientY;
17557                         event.ctrlKey = ctrlKey;
17558                         event.altKey = altKey;
17559                         event.metaKey = metaKey;
17560                         event.shiftKey = shiftKey;
17561                         event.button = button;
17562                         event.relatedTarget = relatedTarget;
17563                     }
17564
17565                     return event;
17566                 },
17567
17568                 createUIEvent: function (doc, type, bubbles, cancelable, detail) {
17569                     var event = doc.createEvent('UIEvents'),
17570                         view = doc.defaultView || window;
17571
17572                     event.initUIEvent(type, bubbles, cancelable, view, detail);
17573                     return event;
17574                 },
17575
17576                 fireEvent: function (target, type, event) {
17577                     target.dispatchEvent(event);
17578                 },
17579
17580                 fixTarget: function (target) {
17581                     // Safari3 doesn't have window.dispatchEvent()
17582                     if (target == window && !target.dispatchEvent) {
17583                         return document;
17584                     }
17585
17586                     return target;
17587                 }
17588             }
17589         } else if (document.createEventObject) { // else if (IE)
17590             var crazyIEButtons = { 0: 1, 1: 4, 2: 2 };
17591
17592             API = {
17593                 createHtmlEvent: function (doc, type, bubbles, cancelable) {
17594                     var event = doc.createEventObject();
17595                     event.bubbles = bubbles;
17596                     event.cancelable = cancelable;
17597                     return event;
17598                 },
17599
17600                 createMouseEvent: function (doc, type, bubbles, cancelable, detail,
17601                                             clientX, clientY, ctrlKey, altKey, shiftKey, metaKey,
17602                                             button, relatedTarget) {
17603                     var event = doc.createEventObject();
17604                     event.bubbles = bubbles;
17605                     event.cancelable = cancelable;
17606                     event.detail = detail;
17607                     event.screenX = clientX;
17608                     event.screenY = clientY;
17609                     event.clientX = clientX;
17610                     event.clientY = clientY;
17611                     event.ctrlKey = ctrlKey;
17612                     event.altKey = altKey;
17613                     event.shiftKey = shiftKey;
17614                     event.metaKey = metaKey;
17615                     event.button = crazyIEButtons[button] || button;
17616                     event.relatedTarget = relatedTarget; // cannot assign to/fromElement
17617                     return event;
17618                 },
17619
17620                 createUIEvent: function (doc, type, bubbles, cancelable, detail) {
17621                     var event = doc.createEventObject();
17622                     event.bubbles = bubbles;
17623                     event.cancelable = cancelable;
17624                     return event;
17625                 },
17626
17627                 fireEvent: function (target, type, event) {
17628                     target.fireEvent('on' + type, event);
17629                 },
17630
17631                 fixTarget: function (target) {
17632                     if (target == document) {
17633                         // IE6,IE7 thinks window==document and doesn't have window.fireEvent()
17634                         // IE6,IE7 cannot properly call document.fireEvent()
17635                         return document.documentElement;
17636                     }
17637
17638                     return target;
17639                 }
17640             };
17641         }
17642
17643         //----------------
17644         // HTMLEvents
17645
17646         Ext.Object.each({
17647                 load:   [false, false],
17648                 unload: [false, false],
17649                 select: [true, false],
17650                 change: [true, false],
17651                 submit: [true, true],
17652                 reset:  [true, false],
17653                 resize: [true, false],
17654                 scroll: [true, false]
17655             },
17656             function (name, value) {
17657                 var bubbles = value[0], cancelable = value[1];
17658                 dispatchers[name] = function (targetEl, srcEvent) {
17659                     var e = API.createHtmlEvent(name, bubbles, cancelable);
17660                     API.fireEvent(targetEl, name, e);
17661                 };
17662             });
17663
17664         //----------------
17665         // MouseEvents
17666
17667         function createMouseEventDispatcher (type, detail) {
17668             var cancelable = (type != 'mousemove');
17669             return function (targetEl, srcEvent) {
17670                 var xy = srcEvent.getXY(),
17671                     e = API.createMouseEvent(targetEl.ownerDocument, type, true, cancelable,
17672                                 detail, xy[0], xy[1], srcEvent.ctrlKey, srcEvent.altKey,
17673                                 srcEvent.shiftKey, srcEvent.metaKey, srcEvent.button,
17674                                 srcEvent.relatedTarget);
17675                 API.fireEvent(targetEl, type, e);
17676             };
17677         }
17678
17679         Ext.each(['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout'],
17680             function (eventName) {
17681                 dispatchers[eventName] = createMouseEventDispatcher(eventName, 1);
17682             });
17683
17684         //----------------
17685         // UIEvents
17686
17687         Ext.Object.each({
17688                 focusin:  [true, false],
17689                 focusout: [true, false],
17690                 activate: [true, true],
17691                 focus:    [false, false],
17692                 blur:     [false, false]
17693             },
17694             function (name, value) {
17695                 var bubbles = value[0], cancelable = value[1];
17696                 dispatchers[name] = function (targetEl, srcEvent) {
17697                     var e = API.createUIEvent(targetEl.ownerDocument, name, bubbles, cancelable, 1);
17698                     API.fireEvent(targetEl, name, e);
17699                 };
17700             });
17701
17702         //---------
17703         if (!API) {
17704             // not even sure what ancient browsers fall into this category...
17705
17706             dispatchers = {}; // never mind all those we just built :P
17707
17708             API = {
17709                 fixTarget: function (t) {
17710                     return t;
17711                 }
17712             };
17713         }
17714
17715         function cannotInject (target, srcEvent) {
17716             // TODO log something
17717         }
17718
17719         return function (target) {
17720             var me = this,
17721                 dispatcher = dispatchers[me.type] || cannotInject,
17722                 t = target ? (target.dom || target) : me.getTarget();
17723
17724             t = API.fixTarget(t);
17725             dispatcher(t, me);
17726         };
17727     }() // call to produce method
17728
17729 }, function() {
17730
17731 Ext.EventObject = new Ext.EventObjectImpl();
17732
17733 });
17734
17735
17736 /**
17737  * @class Ext.core.Element
17738  */
17739 (function(){
17740     var doc = document,
17741         isCSS1 = doc.compatMode == "CSS1Compat",
17742         ELEMENT = Ext.core.Element,
17743         fly = function(el){
17744             if (!_fly) {
17745                 _fly = new Ext.core.Element.Flyweight();
17746             }
17747             _fly.dom = el;
17748             return _fly;
17749         }, _fly;
17750
17751     Ext.apply(ELEMENT, {
17752         isAncestor : function(p, c) {
17753             var ret = false;
17754
17755             p = Ext.getDom(p);
17756             c = Ext.getDom(c);
17757             if (p && c) {
17758                 if (p.contains) {
17759                     return p.contains(c);
17760                 } else if (p.compareDocumentPosition) {
17761                     return !!(p.compareDocumentPosition(c) & 16);
17762                 } else {
17763                     while ((c = c.parentNode)) {
17764                         ret = c == p || ret;
17765                     }
17766                 }
17767             }
17768             return ret;
17769         },
17770
17771         getViewWidth : function(full) {
17772             return full ? ELEMENT.getDocumentWidth() : ELEMENT.getViewportWidth();
17773         },
17774
17775         getViewHeight : function(full) {
17776             return full ? ELEMENT.getDocumentHeight() : ELEMENT.getViewportHeight();
17777         },
17778
17779         getDocumentHeight: function() {
17780             return Math.max(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, ELEMENT.getViewportHeight());
17781         },
17782
17783         getDocumentWidth: function() {
17784             return Math.max(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, ELEMENT.getViewportWidth());
17785         },
17786
17787         getViewportHeight: function(){
17788             return Ext.isIE ?
17789                    (Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) :
17790                    self.innerHeight;
17791         },
17792
17793         getViewportWidth : function() {
17794             return (!Ext.isStrict && !Ext.isOpera) ? doc.body.clientWidth :
17795                    Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth;
17796         },
17797
17798         getY : function(el) {
17799             return ELEMENT.getXY(el)[1];
17800         },
17801
17802         getX : function(el) {
17803             return ELEMENT.getXY(el)[0];
17804         },
17805
17806         getXY : function(el) {
17807             var p,
17808                 pe,
17809                 b,
17810                 bt,
17811                 bl,
17812                 dbd,
17813                 x = 0,
17814                 y = 0,
17815                 scroll,
17816                 hasAbsolute,
17817                 bd = (doc.body || doc.documentElement),
17818                 ret = [0,0];
17819
17820             el = Ext.getDom(el);
17821
17822             if(el != bd){
17823                 hasAbsolute = fly(el).isStyle("position", "absolute");
17824
17825                 if (el.getBoundingClientRect) {
17826                     b = el.getBoundingClientRect();
17827                     scroll = fly(document).getScroll();
17828                     ret = [Math.round(b.left + scroll.left), Math.round(b.top + scroll.top)];
17829                 } else {
17830                     p = el;
17831
17832                     while (p) {
17833                         pe = fly(p);
17834                         x += p.offsetLeft;
17835                         y += p.offsetTop;
17836
17837                         hasAbsolute = hasAbsolute || pe.isStyle("position", "absolute");
17838
17839                         if (Ext.isGecko) {
17840                             y += bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
17841                             x += bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
17842
17843                             if (p != el && !pe.isStyle('overflow','visible')) {
17844                                 x += bl;
17845                                 y += bt;
17846                             }
17847                         }
17848                         p = p.offsetParent;
17849                     }
17850
17851                     if (Ext.isSafari && hasAbsolute) {
17852                         x -= bd.offsetLeft;
17853                         y -= bd.offsetTop;
17854                     }
17855
17856                     if (Ext.isGecko && !hasAbsolute) {
17857                         dbd = fly(bd);
17858                         x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
17859                         y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
17860                     }
17861
17862                     p = el.parentNode;
17863                     while (p && p != bd) {
17864                         if (!Ext.isOpera || (p.tagName != 'TR' && !fly(p).isStyle("display", "inline"))) {
17865                             x -= p.scrollLeft;
17866                             y -= p.scrollTop;
17867                         }
17868                         p = p.parentNode;
17869                     }
17870                     ret = [x,y];
17871                 }
17872             }
17873             return ret;
17874         },
17875
17876         setXY : function(el, xy) {
17877             (el = Ext.fly(el, '_setXY')).position();
17878
17879             var pts = el.translatePoints(xy),
17880                 style = el.dom.style,
17881                 pos;
17882
17883             for (pos in pts) {
17884                 if (!isNaN(pts[pos])) {
17885                     style[pos] = pts[pos] + "px";
17886                 }
17887             }
17888         },
17889
17890         setX : function(el, x) {
17891             ELEMENT.setXY(el, [x, false]);
17892         },
17893
17894         setY : function(el, y) {
17895             ELEMENT.setXY(el, [false, y]);
17896         },
17897
17898         /**
17899          * Serializes a DOM form into a url encoded string
17900          * @param {Object} form The form
17901          * @return {String} The url encoded form
17902          */
17903         serializeForm: function(form) {
17904             var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements,
17905                 hasSubmit = false,
17906                 encoder = encodeURIComponent,
17907                 name,
17908                 data = '',
17909                 type,
17910                 hasValue;
17911
17912             Ext.each(fElements, function(element){
17913                 name = element.name;
17914                 type = element.type;
17915
17916                 if (!element.disabled && name) {
17917                     if (/select-(one|multiple)/i.test(type)) {
17918                         Ext.each(element.options, function(opt){
17919                             if (opt.selected) {
17920                                 hasValue = opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttributeNode('value').specified;
17921                                 data += String.format("{0}={1}&", encoder(name), encoder(hasValue ? opt.value : opt.text));
17922                             }
17923                         });
17924                     } else if (!(/file|undefined|reset|button/i.test(type))) {
17925                         if (!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)) {
17926                             data += encoder(name) + '=' + encoder(element.value) + '&';
17927                             hasSubmit = /submit/i.test(type);
17928                         }
17929                     }
17930                 }
17931             });
17932             return data.substr(0, data.length - 1);
17933         }
17934     });
17935 })();
17936
17937 /**
17938  * @class Ext.core.Element
17939  */
17940
17941 Ext.core.Element.addMethods({
17942
17943     /**
17944      * Monitors this Element for the mouse leaving. Calls the function after the specified delay only if
17945      * the mouse was not moved back into the Element within the delay. If the mouse <i>was</i> moved
17946      * back in, the function is not called.
17947      * @param {Number} delay The delay <b>in milliseconds</b> to wait for possible mouse re-entry before calling the handler function.
17948      * @param {Function} handler The function to call if the mouse remains outside of this Element for the specified time.
17949      * @param {Object} scope The scope (<code>this</code> reference) in which the handler function executes. Defaults to this Element.
17950      * @return {Object} The listeners object which was added to this element so that monitoring can be stopped. Example usage:</pre><code>
17951 // Hide the menu if the mouse moves out for 250ms or more
17952 this.mouseLeaveMonitor = this.menuEl.monitorMouseLeave(250, this.hideMenu, this);
17953
17954 ...
17955 // Remove mouseleave monitor on menu destroy
17956 this.menuEl.un(this.mouseLeaveMonitor);
17957 </code></pre>
17958      */
17959     monitorMouseLeave: function(delay, handler, scope) {
17960         var me = this,
17961             timer,
17962             listeners = {
17963                 mouseleave: function(e) {
17964                     timer = setTimeout(Ext.Function.bind(handler, scope||me, [e]), delay);
17965                 },
17966                 mouseenter: function() {
17967                     clearTimeout(timer);
17968                 },
17969                 freezeEvent: true
17970             };
17971
17972         me.on(listeners);
17973         return listeners;
17974     },
17975
17976     /**
17977      * Stops the specified event(s) from bubbling and optionally prevents the default action
17978      * @param {String/Array} eventName an event / array of events to stop from bubbling
17979      * @param {Boolean} preventDefault (optional) true to prevent the default action too
17980      * @return {Ext.core.Element} this
17981      */
17982     swallowEvent : function(eventName, preventDefault) {
17983         var me = this;
17984         function fn(e) {
17985             e.stopPropagation();
17986             if (preventDefault) {
17987                 e.preventDefault();
17988             }
17989         }
17990         
17991         if (Ext.isArray(eventName)) {
17992             Ext.each(eventName, function(e) {
17993                  me.on(e, fn);
17994             });
17995             return me;
17996         }
17997         me.on(eventName, fn);
17998         return me;
17999     },
18000
18001     /**
18002      * Create an event handler on this element such that when the event fires and is handled by this element,
18003      * it will be relayed to another object (i.e., fired again as if it originated from that object instead).
18004      * @param {String} eventName The type of event to relay
18005      * @param {Object} object Any object that extends {@link Ext.util.Observable} that will provide the context
18006      * for firing the relayed event
18007      */
18008     relayEvent : function(eventName, observable) {
18009         this.on(eventName, function(e) {
18010             observable.fireEvent(eventName, e);
18011         });
18012     },
18013
18014     /**
18015      * Removes Empty, or whitespace filled text nodes. Combines adjacent text nodes.
18016      * @param {Boolean} forceReclean (optional) By default the element
18017      * keeps track if it has been cleaned already so
18018      * you can call this over and over. However, if you update the element and
18019      * need to force a reclean, you can pass true.
18020      */
18021     clean : function(forceReclean) {
18022         var me  = this,
18023             dom = me.dom,
18024             n   = dom.firstChild,
18025             nx,
18026             ni  = -1;
18027
18028         if (Ext.core.Element.data(dom, 'isCleaned') && forceReclean !== true) {
18029             return me;
18030         }
18031
18032         while (n) {
18033             nx = n.nextSibling;
18034             if (n.nodeType == 3) {
18035                 // Remove empty/whitespace text nodes
18036                 if (!(/\S/.test(n.nodeValue))) {
18037                     dom.removeChild(n);
18038                 // Combine adjacent text nodes
18039                 } else if (nx && nx.nodeType == 3) {
18040                     n.appendData(Ext.String.trim(nx.data));
18041                     dom.removeChild(nx);
18042                     nx = n.nextSibling;
18043                     n.nodeIndex = ++ni;
18044                 }
18045             } else {
18046                 // Recursively clean
18047                 Ext.fly(n).clean();
18048                 n.nodeIndex = ++ni;
18049             }
18050             n = nx;
18051         }
18052
18053         Ext.core.Element.data(dom, 'isCleaned', true);
18054         return me;
18055     },
18056
18057     /**
18058      * Direct access to the Ext.ElementLoader {@link Ext.ElementLoader#load} method. The method takes the same object
18059      * parameter as {@link Ext.ElementLoader#load}
18060      * @return {Ext.core.Element} this
18061      */
18062     load : function(options) {
18063         this.getLoader().load(options);
18064         return this;
18065     },
18066
18067     /**
18068     * Gets this element's {@link Ext.ElementLoader ElementLoader}
18069     * @return {Ext.ElementLoader} The loader
18070     */
18071     getLoader : function() {
18072         var dom = this.dom,
18073             data = Ext.core.Element.data,
18074             loader = data(dom, 'loader');
18075             
18076         if (!loader) {
18077             loader = Ext.create('Ext.ElementLoader', {
18078                 target: this
18079             });
18080             data(dom, 'loader', loader);
18081         }
18082         return loader;
18083     },
18084
18085     /**
18086     * Update the innerHTML of this element, optionally searching for and processing scripts
18087     * @param {String} html The new HTML
18088     * @param {Boolean} loadScripts (optional) True to look for and process scripts (defaults to false)
18089     * @param {Function} callback (optional) For async script loading you can be notified when the update completes
18090     * @return {Ext.core.Element} this
18091      */
18092     update : function(html, loadScripts, callback) {
18093         var me = this,
18094             id,
18095             dom,
18096             interval;
18097             
18098         if (!me.dom) {
18099             return me;
18100         }
18101         html = html || '';
18102         dom = me.dom;
18103
18104         if (loadScripts !== true) {
18105             dom.innerHTML = html;
18106             Ext.callback(callback, me);
18107             return me;
18108         }
18109
18110         id  = Ext.id();
18111         html += '<span id="' + id + '"></span>';
18112
18113         interval = setInterval(function(){
18114             if (!document.getElementById(id)) {
18115                 return false;    
18116             }
18117             clearInterval(interval);
18118             var DOC    = document,
18119                 hd     = DOC.getElementsByTagName("head")[0],
18120                 re     = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig,
18121                 srcRe  = /\ssrc=([\'\"])(.*?)\1/i,
18122                 typeRe = /\stype=([\'\"])(.*?)\1/i,
18123                 match,
18124                 attrs,
18125                 srcMatch,
18126                 typeMatch,
18127                 el,
18128                 s;
18129
18130             while ((match = re.exec(html))) {
18131                 attrs = match[1];
18132                 srcMatch = attrs ? attrs.match(srcRe) : false;
18133                 if (srcMatch && srcMatch[2]) {
18134                    s = DOC.createElement("script");
18135                    s.src = srcMatch[2];
18136                    typeMatch = attrs.match(typeRe);
18137                    if (typeMatch && typeMatch[2]) {
18138                        s.type = typeMatch[2];
18139                    }
18140                    hd.appendChild(s);
18141                 } else if (match[2] && match[2].length > 0) {
18142                     if (window.execScript) {
18143                        window.execScript(match[2]);
18144                     } else {
18145                        window.eval(match[2]);
18146                     }
18147                 }
18148             }
18149             
18150             el = DOC.getElementById(id);
18151             if (el) {
18152                 Ext.removeNode(el);
18153             }
18154             Ext.callback(callback, me);
18155         }, 20);
18156         dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, '');
18157         return me;
18158     },
18159
18160     // inherit docs, overridden so we can add removeAnchor
18161     removeAllListeners : function() {
18162         this.removeAnchor();
18163         Ext.EventManager.removeAll(this.dom);
18164         return this;
18165     },
18166
18167     /**
18168      * Creates a proxy element of this element
18169      * @param {String/Object} config The class name of the proxy element or a DomHelper config object
18170      * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
18171      * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
18172      * @return {Ext.core.Element} The new proxy element
18173      */
18174     createProxy : function(config, renderTo, matchBox) {
18175         config = (typeof config == 'object') ? config : {tag : "div", cls: config};
18176
18177         var me = this,
18178             proxy = renderTo ? Ext.core.DomHelper.append(renderTo, config, true) :
18179                                Ext.core.DomHelper.insertBefore(me.dom, config, true);
18180
18181         proxy.setVisibilityMode(Ext.core.Element.DISPLAY);
18182         proxy.hide();
18183         if (matchBox && me.setBox && me.getBox) { // check to make sure Element.position.js is loaded
18184            proxy.setBox(me.getBox());
18185         }
18186         return proxy;
18187     }
18188 });
18189 Ext.core.Element.prototype.clearListeners = Ext.core.Element.prototype.removeAllListeners;
18190
18191 /**
18192  * @class Ext.core.Element
18193  */
18194 Ext.core.Element.addMethods({
18195     /**
18196      * Gets the x,y coordinates specified by the anchor position on the element.
18197      * @param {String} anchor (optional) The specified anchor position (defaults to "c").  See {@link #alignTo}
18198      * for details on supported anchor positions.
18199      * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead
18200      * of page coordinates
18201      * @param {Object} size (optional) An object containing the size to use for calculating anchor position
18202      * {width: (target width), height: (target height)} (defaults to the element's current size)
18203      * @return {Array} [x, y] An array containing the element's x and y coordinates
18204      */
18205     getAnchorXY : function(anchor, local, s){
18206         //Passing a different size is useful for pre-calculating anchors,
18207         //especially for anchored animations that change the el size.
18208         anchor = (anchor || "tl").toLowerCase();
18209         s = s || {};
18210
18211         var me = this,
18212             vp = me.dom == document.body || me.dom == document,
18213             w = s.width || vp ? Ext.core.Element.getViewWidth() : me.getWidth(),
18214             h = s.height || vp ? Ext.core.Element.getViewHeight() : me.getHeight(),
18215             xy,
18216             r = Math.round,
18217             o = me.getXY(),
18218             scroll = me.getScroll(),
18219             extraX = vp ? scroll.left : !local ? o[0] : 0,
18220             extraY = vp ? scroll.top : !local ? o[1] : 0,
18221             hash = {
18222                 c  : [r(w * 0.5), r(h * 0.5)],
18223                 t  : [r(w * 0.5), 0],
18224                 l  : [0, r(h * 0.5)],
18225                 r  : [w, r(h * 0.5)],
18226                 b  : [r(w * 0.5), h],
18227                 tl : [0, 0],
18228                 bl : [0, h],
18229                 br : [w, h],
18230                 tr : [w, 0]
18231             };
18232
18233         xy = hash[anchor];
18234         return [xy[0] + extraX, xy[1] + extraY];
18235     },
18236
18237     /**
18238      * Anchors an element to another element and realigns it when the window is resized.
18239      * @param {Mixed} element The element to align to.
18240      * @param {String} position The position to align to.
18241      * @param {Array} offsets (optional) Offset the positioning by [x, y]
18242      * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
18243      * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
18244      * is a number, it is used as the buffer delay (defaults to 50ms).
18245      * @param {Function} callback The function to call after the animation finishes
18246      * @return {Ext.core.Element} this
18247      */
18248     anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
18249         var me = this,
18250             dom = me.dom,
18251             scroll = !Ext.isEmpty(monitorScroll),
18252             action = function(){
18253                 Ext.fly(dom).alignTo(el, alignment, offsets, animate);
18254                 Ext.callback(callback, Ext.fly(dom));
18255             },
18256             anchor = this.getAnchor();
18257
18258         // previous listener anchor, remove it
18259         this.removeAnchor();
18260         Ext.apply(anchor, {
18261             fn: action,
18262             scroll: scroll
18263         });
18264
18265         Ext.EventManager.onWindowResize(action, null);
18266
18267         if(scroll){
18268             Ext.EventManager.on(window, 'scroll', action, null,
18269                 {buffer: !isNaN(monitorScroll) ? monitorScroll : 50});
18270         }
18271         action.call(me); // align immediately
18272         return me;
18273     },
18274
18275     /**
18276      * Remove any anchor to this element. See {@link #anchorTo}.
18277      * @return {Ext.core.Element} this
18278      */
18279     removeAnchor : function(){
18280         var me = this,
18281             anchor = this.getAnchor();
18282
18283         if(anchor && anchor.fn){
18284             Ext.EventManager.removeResizeListener(anchor.fn);
18285             if(anchor.scroll){
18286                 Ext.EventManager.un(window, 'scroll', anchor.fn);
18287             }
18288             delete anchor.fn;
18289         }
18290         return me;
18291     },
18292
18293     // private
18294     getAnchor : function(){
18295         var data = Ext.core.Element.data,
18296             dom = this.dom;
18297             if (!dom) {
18298                 return;
18299             }
18300             var anchor = data(dom, '_anchor');
18301
18302         if(!anchor){
18303             anchor = data(dom, '_anchor', {});
18304         }
18305         return anchor;
18306     },
18307
18308     getAlignVector: function(el, spec, offset) {
18309         var me = this,
18310             side = {t:"top", l:"left", r:"right", b: "bottom"},
18311             thisRegion = me.getRegion(),
18312             elRegion;
18313
18314         el = Ext.get(el);
18315         if(!el || !el.dom){
18316             Ext.Error.raise({
18317                 sourceClass: 'Ext.core.Element',
18318                 sourceMethod: 'getAlignVector',
18319                 msg: 'Attempted to align an element that doesn\'t exist'
18320             });
18321         }
18322
18323         elRegion = el.getRegion();
18324     },
18325
18326     /**
18327      * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
18328      * supported position values.
18329      * @param {Mixed} element The element to align to.
18330      * @param {String} position (optional, defaults to "tl-bl?") The position to align to.
18331      * @param {Array} offsets (optional) Offset the positioning by [x, y]
18332      * @return {Array} [x, y]
18333      */
18334     getAlignToXY : function(el, p, o){
18335         el = Ext.get(el);
18336
18337         if(!el || !el.dom){
18338             Ext.Error.raise({
18339                 sourceClass: 'Ext.core.Element',
18340                 sourceMethod: 'getAlignToXY',
18341                 msg: 'Attempted to align an element that doesn\'t exist'
18342             });
18343         }
18344
18345         o = o || [0,0];
18346         p = (!p || p == "?" ? "tl-bl?" : (!(/-/).test(p) && p !== "" ? "tl-" + p : p || "tl-bl")).toLowerCase();
18347
18348         var me = this,
18349             d = me.dom,
18350             a1,
18351             a2,
18352             x,
18353             y,
18354             //constrain the aligned el to viewport if necessary
18355             w,
18356             h,
18357             r,
18358             dw = Ext.core.Element.getViewWidth() -10, // 10px of margin for ie
18359             dh = Ext.core.Element.getViewHeight()-10, // 10px of margin for ie
18360             p1y,
18361             p1x,
18362             p2y,
18363             p2x,
18364             swapY,
18365             swapX,
18366             doc = document,
18367             docElement = doc.documentElement,
18368             docBody = doc.body,
18369             scrollX = (docElement.scrollLeft || docBody.scrollLeft || 0)+5,
18370             scrollY = (docElement.scrollTop || docBody.scrollTop || 0)+5,
18371             c = false, //constrain to viewport
18372             p1 = "",
18373             p2 = "",
18374             m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
18375
18376         if(!m){
18377             Ext.Error.raise({
18378                 sourceClass: 'Ext.core.Element',
18379                 sourceMethod: 'getAlignToXY',
18380                 el: el,
18381                 position: p,
18382                 offset: o,
18383                 msg: 'Attemmpted to align an element with an invalid position: "' + p + '"'
18384             });
18385         }
18386
18387         p1 = m[1];
18388         p2 = m[2];
18389         c = !!m[3];
18390
18391         //Subtract the aligned el's internal xy from the target's offset xy
18392         //plus custom offset to get the aligned el's new offset xy
18393         a1 = me.getAnchorXY(p1, true);
18394         a2 = el.getAnchorXY(p2, false);
18395
18396         x = a2[0] - a1[0] + o[0];
18397         y = a2[1] - a1[1] + o[1];
18398
18399         if(c){
18400            w = me.getWidth();
18401            h = me.getHeight();
18402            r = el.getRegion();
18403            //If we are at a viewport boundary and the aligned el is anchored on a target border that is
18404            //perpendicular to the vp border, allow the aligned el to slide on that border,
18405            //otherwise swap the aligned el to the opposite border of the target.
18406            p1y = p1.charAt(0);
18407            p1x = p1.charAt(p1.length-1);
18408            p2y = p2.charAt(0);
18409            p2x = p2.charAt(p2.length-1);
18410            swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
18411            swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
18412
18413
18414            if (x + w > dw + scrollX) {
18415                 x = swapX ? r.left-w : dw+scrollX-w;
18416            }
18417            if (x < scrollX) {
18418                x = swapX ? r.right : scrollX;
18419            }
18420            if (y + h > dh + scrollY) {
18421                 y = swapY ? r.top-h : dh+scrollY-h;
18422             }
18423            if (y < scrollY){
18424                y = swapY ? r.bottom : scrollY;
18425            }
18426         }
18427         return [x,y];
18428     },
18429
18430     /**
18431      * Aligns this element with another element relative to the specified anchor points. If the other element is the
18432      * document it aligns it to the viewport.
18433      * The position parameter is optional, and can be specified in any one of the following formats:
18434      * <ul>
18435      *   <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
18436      *   <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
18437      *       The element being aligned will position its top-left corner (tl) to that point.  <i>This method has been
18438      *       deprecated in favor of the newer two anchor syntax below</i>.</li>
18439      *   <li><b>Two anchors</b>: If two values from the table below are passed separated by a dash, the first value is used as the
18440      *       element's anchor point, and the second value is used as the target's anchor point.</li>
18441      * </ul>
18442      * In addition to the anchor points, the position parameter also supports the "?" character.  If "?" is passed at the end of
18443      * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
18444      * the viewport if necessary.  Note that the element being aligned might be swapped to align to a different position than
18445      * that specified in order to enforce the viewport constraints.
18446      * Following are all of the supported anchor positions:
18447 <pre>
18448 Value  Description
18449 -----  -----------------------------
18450 tl     The top left corner (default)
18451 t      The center of the top edge
18452 tr     The top right corner
18453 l      The center of the left edge
18454 c      In the center of the element
18455 r      The center of the right edge
18456 bl     The bottom left corner
18457 b      The center of the bottom edge
18458 br     The bottom right corner
18459 </pre>
18460 Example Usage:
18461 <pre><code>
18462 // align el to other-el using the default positioning ("tl-bl", non-constrained)
18463 el.alignTo("other-el");
18464
18465 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
18466 el.alignTo("other-el", "tr?");
18467
18468 // align the bottom right corner of el with the center left edge of other-el
18469 el.alignTo("other-el", "br-l?");
18470
18471 // align the center of el with the bottom left corner of other-el and
18472 // adjust the x position by -6 pixels (and the y position by 0)
18473 el.alignTo("other-el", "c-bl", [-6, 0]);
18474 </code></pre>
18475      * @param {Mixed} element The element to align to.
18476      * @param {String} position (optional, defaults to "tl-bl?") The position to align to.
18477      * @param {Array} offsets (optional) Offset the positioning by [x, y]
18478      * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
18479      * @return {Ext.core.Element} this
18480      */
18481     alignTo : function(element, position, offsets, animate){
18482         var me = this;
18483         return me.setXY(me.getAlignToXY(element, position, offsets),
18484                         me.anim && !!animate ? me.anim(animate) : false);
18485     },
18486
18487     // private ==>  used outside of core
18488     adjustForConstraints : function(xy, parent) {
18489         var vector = this.getConstrainVector(parent, xy);
18490         if (vector) {
18491             xy[0] += vector[0];
18492             xy[1] += vector[1];
18493         }
18494         return xy;
18495     },
18496
18497     /**
18498      * <p>Returns the <code>[X, Y]</code> vector by which this element must be translated to make a best attempt
18499      * to constrain within the passed constraint. Returns <code>false</code> is this element does not need to be moved.</p>
18500      * <p>Priority is given to constraining the top and left within the constraint.</p>
18501      * <p>The constraint may either be an existing element into which this element is to be constrained, or
18502      * an {@link Ext.util.Region Region} into which this element is to be constrained.</p>
18503      * @param constrainTo {Mixed} The Element or {@link Ext.util.Region Region} into which this element is to be constrained.
18504      * @param proposedPosition {Array} A proposed <code>[X, Y]</code> position to test for validity and to produce a vector for instead
18505      * of using this Element's current position;
18506      * @returns {Array} <b>If</b> this element <i>needs</i> to be translated, an <code>[X, Y]</code>
18507      * vector by which this element must be translated. Otherwise, <code>false</code>.
18508      */
18509     getConstrainVector: function(constrainTo, proposedPosition) {
18510         if (!(constrainTo instanceof Ext.util.Region)) {
18511             constrainTo = Ext.get(constrainTo).getViewRegion();
18512         }
18513         var thisRegion = this.getRegion(),
18514             vector = [0, 0],
18515             shadowSize = this.shadow && this.shadow.offset,
18516             overflowed = false;
18517
18518         // Shift this region to occupy the proposed position
18519         if (proposedPosition) {
18520             thisRegion.translateBy(proposedPosition[0] - thisRegion.x, proposedPosition[1] - thisRegion.y);
18521         }
18522
18523         // Reduce the constrain region to allow for shadow
18524         // TODO: Rewrite the Shadow class. When that's done, get the extra for each side from the Shadow.
18525         if (shadowSize) {
18526             constrainTo.adjust(0, -shadowSize, -shadowSize, shadowSize);
18527         }
18528
18529         // Constrain the X coordinate by however much this Element overflows
18530         if (thisRegion.right > constrainTo.right) {
18531             overflowed = true;
18532             vector[0] = (constrainTo.right - thisRegion.right);    // overflowed the right
18533         }
18534         if (thisRegion.left + vector[0] < constrainTo.left) {
18535             overflowed = true;
18536             vector[0] = (constrainTo.left - thisRegion.left);      // overflowed the left
18537         }
18538
18539         // Constrain the Y coordinate by however much this Element overflows
18540         if (thisRegion.bottom > constrainTo.bottom) {
18541             overflowed = true;
18542             vector[1] = (constrainTo.bottom - thisRegion.bottom);  // overflowed the bottom
18543         }
18544         if (thisRegion.top + vector[1] < constrainTo.top) {
18545             overflowed = true;
18546             vector[1] = (constrainTo.top - thisRegion.top);        // overflowed the top
18547         }
18548         return overflowed ? vector : false;
18549     },
18550
18551     /**
18552     * Calculates the x, y to center this element on the screen
18553     * @return {Array} The x, y values [x, y]
18554     */
18555     getCenterXY : function(){
18556         return this.getAlignToXY(document, 'c-c');
18557     },
18558
18559     /**
18560     * Centers the Element in either the viewport, or another Element.
18561     * @param {Mixed} centerIn (optional) The element in which to center the element.
18562     */
18563     center : function(centerIn){
18564         return this.alignTo(centerIn || document, 'c-c');
18565     }
18566 });
18567
18568 /**
18569  * @class Ext.core.Element
18570  */
18571 (function(){
18572
18573 var ELEMENT = Ext.core.Element,
18574     LEFT = "left",
18575     RIGHT = "right",
18576     TOP = "top",
18577     BOTTOM = "bottom",
18578     POSITION = "position",
18579     STATIC = "static",
18580     RELATIVE = "relative",
18581     AUTO = "auto",
18582     ZINDEX = "z-index";
18583
18584 Ext.override(Ext.core.Element, {
18585     /**
18586       * Gets the current X position of the element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
18587       * @return {Number} The X position of the element
18588       */
18589     getX : function(){
18590         return ELEMENT.getX(this.dom);
18591     },
18592
18593     /**
18594       * Gets the current Y position of the element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
18595       * @return {Number} The Y position of the element
18596       */
18597     getY : function(){
18598         return ELEMENT.getY(this.dom);
18599     },
18600
18601     /**
18602       * Gets the current position of the element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
18603       * @return {Array} The XY position of the element
18604       */
18605     getXY : function(){
18606         return ELEMENT.getXY(this.dom);
18607     },
18608
18609     /**
18610       * Returns the offsets of this element from the passed element. Both element must be part of the DOM tree and not have display:none to have page coordinates.
18611       * @param {Mixed} element The element to get the offsets from.
18612       * @return {Array} The XY page offsets (e.g. [100, -200])
18613       */
18614     getOffsetsTo : function(el){
18615         var o = this.getXY(),
18616             e = Ext.fly(el, '_internal').getXY();
18617         return [o[0]-e[0],o[1]-e[1]];
18618     },
18619
18620     /**
18621      * Sets the X position of the element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
18622      * @param {Number} The X position of the element
18623      * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
18624      * @return {Ext.core.Element} this
18625      */
18626     setX : function(x, animate){
18627         return this.setXY([x, this.getY()], animate);
18628     },
18629
18630     /**
18631      * Sets the Y position of the element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
18632      * @param {Number} The Y position of the element
18633      * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
18634      * @return {Ext.core.Element} this
18635      */
18636     setY : function(y, animate){
18637         return this.setXY([this.getX(), y], animate);
18638     },
18639
18640     /**
18641      * Sets the element's left position directly using CSS style (instead of {@link #setX}).
18642      * @param {String} left The left CSS property value
18643      * @return {Ext.core.Element} this
18644      */
18645     setLeft : function(left){
18646         this.setStyle(LEFT, this.addUnits(left));
18647         return this;
18648     },
18649
18650     /**
18651      * Sets the element's top position directly using CSS style (instead of {@link #setY}).
18652      * @param {String} top The top CSS property value
18653      * @return {Ext.core.Element} this
18654      */
18655     setTop : function(top){
18656         this.setStyle(TOP, this.addUnits(top));
18657         return this;
18658     },
18659
18660     /**
18661      * Sets the element's CSS right style.
18662      * @param {String} right The right CSS property value
18663      * @return {Ext.core.Element} this
18664      */
18665     setRight : function(right){
18666         this.setStyle(RIGHT, this.addUnits(right));
18667         return this;
18668     },
18669
18670     /**
18671      * Sets the element's CSS bottom style.
18672      * @param {String} bottom The bottom CSS property value
18673      * @return {Ext.core.Element} this
18674      */
18675     setBottom : function(bottom){
18676         this.setStyle(BOTTOM, this.addUnits(bottom));
18677         return this;
18678     },
18679
18680     /**
18681      * Sets the position of the element in page coordinates, regardless of how the element is positioned.
18682      * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
18683      * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
18684      * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
18685      * @return {Ext.core.Element} this
18686      */
18687     setXY: function(pos, animate) {
18688         var me = this;
18689         if (!animate || !me.anim) {
18690             ELEMENT.setXY(me.dom, pos);
18691         }
18692         else {
18693             if (!Ext.isObject(animate)) {
18694                 animate = {};
18695             }
18696             me.animate(Ext.applyIf({ to: { x: pos[0], y: pos[1] } }, animate));
18697         }
18698         return me;
18699     },
18700
18701     /**
18702      * Sets the position of the element in page coordinates, regardless of how the element is positioned.
18703      * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
18704      * @param {Number} x X value for new position (coordinates are page-based)
18705      * @param {Number} y Y value for new position (coordinates are page-based)
18706      * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
18707      * @return {Ext.core.Element} this
18708      */
18709     setLocation : function(x, y, animate){
18710         return this.setXY([x, y], animate);
18711     },
18712
18713     /**
18714      * Sets the position of the element in page coordinates, regardless of how the element is positioned.
18715      * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
18716      * @param {Number} x X value for new position (coordinates are page-based)
18717      * @param {Number} y Y value for new position (coordinates are page-based)
18718      * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
18719      * @return {Ext.core.Element} this
18720      */
18721     moveTo : function(x, y, animate){
18722         return this.setXY([x, y], animate);
18723     },
18724
18725     /**
18726      * Gets the left X coordinate
18727      * @param {Boolean} local True to get the local css position instead of page coordinate
18728      * @return {Number}
18729      */
18730     getLeft : function(local){
18731         return !local ? this.getX() : parseInt(this.getStyle(LEFT), 10) || 0;
18732     },
18733
18734     /**
18735      * Gets the right X coordinate of the element (element X position + element width)
18736      * @param {Boolean} local True to get the local css position instead of page coordinate
18737      * @return {Number}
18738      */
18739     getRight : function(local){
18740         var me = this;
18741         return !local ? me.getX() + me.getWidth() : (me.getLeft(true) + me.getWidth()) || 0;
18742     },
18743
18744     /**
18745      * Gets the top Y coordinate
18746      * @param {Boolean} local True to get the local css position instead of page coordinate
18747      * @return {Number}
18748      */
18749     getTop : function(local) {
18750         return !local ? this.getY() : parseInt(this.getStyle(TOP), 10) || 0;
18751     },
18752
18753     /**
18754      * Gets the bottom Y coordinate of the element (element Y position + element height)
18755      * @param {Boolean} local True to get the local css position instead of page coordinate
18756      * @return {Number}
18757      */
18758     getBottom : function(local){
18759         var me = this;
18760         return !local ? me.getY() + me.getHeight() : (me.getTop(true) + me.getHeight()) || 0;
18761     },
18762
18763     /**
18764     * Initializes positioning on this element. If a desired position is not passed, it will make the
18765     * the element positioned relative IF it is not already positioned.
18766     * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
18767     * @param {Number} zIndex (optional) The zIndex to apply
18768     * @param {Number} x (optional) Set the page X position
18769     * @param {Number} y (optional) Set the page Y position
18770     */
18771     position : function(pos, zIndex, x, y) {
18772         var me = this;
18773
18774         if (!pos && me.isStyle(POSITION, STATIC)){
18775             me.setStyle(POSITION, RELATIVE);
18776         } else if(pos) {
18777             me.setStyle(POSITION, pos);
18778         }
18779         if (zIndex){
18780             me.setStyle(ZINDEX, zIndex);
18781         }
18782         if (x || y) {
18783             me.setXY([x || false, y || false]);
18784         }
18785     },
18786
18787     /**
18788     * Clear positioning back to the default when the document was loaded
18789     * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
18790     * @return {Ext.core.Element} this
18791      */
18792     clearPositioning : function(value){
18793         value = value || '';
18794         this.setStyle({
18795             left : value,
18796             right : value,
18797             top : value,
18798             bottom : value,
18799             "z-index" : "",
18800             position : STATIC
18801         });
18802         return this;
18803     },
18804
18805     /**
18806     * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
18807     * snapshot before performing an update and then restoring the element.
18808     * @return {Object}
18809     */
18810     getPositioning : function(){
18811         var l = this.getStyle(LEFT);
18812         var t = this.getStyle(TOP);
18813         return {
18814             "position" : this.getStyle(POSITION),
18815             "left" : l,
18816             "right" : l ? "" : this.getStyle(RIGHT),
18817             "top" : t,
18818             "bottom" : t ? "" : this.getStyle(BOTTOM),
18819             "z-index" : this.getStyle(ZINDEX)
18820         };
18821     },
18822
18823     /**
18824     * Set positioning with an object returned by getPositioning().
18825     * @param {Object} posCfg
18826     * @return {Ext.core.Element} this
18827      */
18828     setPositioning : function(pc){
18829         var me = this,
18830             style = me.dom.style;
18831
18832         me.setStyle(pc);
18833
18834         if(pc.right == AUTO){
18835             style.right = "";
18836         }
18837         if(pc.bottom == AUTO){
18838             style.bottom = "";
18839         }
18840
18841         return me;
18842     },
18843
18844     /**
18845      * Translates the passed page coordinates into left/top css values for this element
18846      * @param {Number/Array} x The page x or an array containing [x, y]
18847      * @param {Number} y (optional) The page y, required if x is not an array
18848      * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
18849      */
18850     translatePoints: function(x, y) {
18851         if (Ext.isArray(x)) {
18852              y = x[1];
18853              x = x[0];
18854         }
18855         var me = this,
18856             relative = me.isStyle(POSITION, RELATIVE),
18857             o = me.getXY(),
18858             left = parseInt(me.getStyle(LEFT), 10),
18859             top = parseInt(me.getStyle(TOP), 10);
18860
18861         if (!Ext.isNumber(left)) {
18862             left = relative ? 0 : me.dom.offsetLeft;
18863         }
18864         if (!Ext.isNumber(top)) {
18865             top = relative ? 0 : me.dom.offsetTop;
18866         }
18867         left = (Ext.isNumber(x)) ? x - o[0] + left : undefined;
18868         top = (Ext.isNumber(y)) ? y - o[1] + top : undefined;
18869         return {
18870             left: left,
18871             top: top
18872         };
18873     },
18874
18875     /**
18876      * Sets the element's box. Use getBox() on another element to get a box obj. If animate is true then width, height, x and y will be animated concurrently.
18877      * @param {Object} box The box to fill {x, y, width, height}
18878      * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
18879      * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
18880      * @return {Ext.core.Element} this
18881      */
18882     setBox: function(box, adjust, animate) {
18883         var me = this,
18884             w = box.width,
18885             h = box.height;
18886         if ((adjust && !me.autoBoxAdjust) && !me.isBorderBox()) {
18887             w -= (me.getBorderWidth("lr") + me.getPadding("lr"));
18888             h -= (me.getBorderWidth("tb") + me.getPadding("tb"));
18889         }
18890         me.setBounds(box.x, box.y, w, h, animate);
18891         return me;
18892     },
18893
18894     /**
18895      * Return an object defining the area of this Element which can be passed to {@link #setBox} to
18896      * set another Element's size/location to match this element.
18897      * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
18898      * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
18899      * @return {Object} box An object in the format<pre><code>
18900 {
18901     x: &lt;Element's X position>,
18902     y: &lt;Element's Y position>,
18903     width: &lt;Element's width>,
18904     height: &lt;Element's height>,
18905     bottom: &lt;Element's lower bound>,
18906     right: &lt;Element's rightmost bound>
18907 }
18908 </code></pre>
18909      * The returned object may also be addressed as an Array where index 0 contains the X position
18910      * and index 1 contains the Y position. So the result may also be used for {@link #setXY}
18911      */
18912     getBox: function(contentBox, local) {
18913         var me = this,
18914             xy,
18915             left,
18916             top,
18917             getBorderWidth = me.getBorderWidth,
18918             getPadding = me.getPadding,
18919             l, r, t, b, w, h, bx;
18920         if (!local) {
18921             xy = me.getXY();
18922         } else {
18923             left = parseInt(me.getStyle("left"), 10) || 0;
18924             top = parseInt(me.getStyle("top"), 10) || 0;
18925             xy = [left, top];
18926         }
18927         w = me.getWidth();
18928         h = me.getHeight();
18929         if (!contentBox) {
18930             bx = {
18931                 x: xy[0],
18932                 y: xy[1],
18933                 0: xy[0],
18934                 1: xy[1],
18935                 width: w,
18936                 height: h
18937             };
18938         } else {
18939             l = getBorderWidth.call(me, "l") + getPadding.call(me, "l");
18940             r = getBorderWidth.call(me, "r") + getPadding.call(me, "r");
18941             t = getBorderWidth.call(me, "t") + getPadding.call(me, "t");
18942             b = getBorderWidth.call(me, "b") + getPadding.call(me, "b");
18943             bx = {
18944                 x: xy[0] + l,
18945                 y: xy[1] + t,
18946                 0: xy[0] + l,
18947                 1: xy[1] + t,
18948                 width: w - (l + r),
18949                 height: h - (t + b)
18950             };
18951         }
18952         bx.right = bx.x + bx.width;
18953         bx.bottom = bx.y + bx.height;
18954         return bx;
18955     },
18956
18957     /**
18958      * Move this element relative to its current position.
18959      * @param {String} direction Possible values are: "l" (or "left"), "r" (or "right"), "t" (or "top", or "up"), "b" (or "bottom", or "down").
18960      * @param {Number} distance How far to move the element in pixels
18961      * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
18962      * @return {Ext.core.Element} this
18963      */
18964     move: function(direction, distance, animate) {
18965         var me = this,
18966             xy = me.getXY(),
18967             x = xy[0],
18968             y = xy[1],
18969             left = [x - distance, y],
18970             right = [x + distance, y],
18971             top = [x, y - distance],
18972             bottom = [x, y + distance],
18973             hash = {
18974                 l: left,
18975                 left: left,
18976                 r: right,
18977                 right: right,
18978                 t: top,
18979                 top: top,
18980                 up: top,
18981                 b: bottom,
18982                 bottom: bottom,
18983                 down: bottom
18984             };
18985
18986         direction = direction.toLowerCase();
18987         me.moveTo(hash[direction][0], hash[direction][1], animate);
18988     },
18989
18990     /**
18991      * Quick set left and top adding default units
18992      * @param {String} left The left CSS property value
18993      * @param {String} top The top CSS property value
18994      * @return {Ext.core.Element} this
18995      */
18996     setLeftTop: function(left, top) {
18997         var me = this,
18998             style = me.dom.style;
18999         style.left = me.addUnits(left);
19000         style.top = me.addUnits(top);
19001         return me;
19002     },
19003
19004     /**
19005      * Returns the region of this element.
19006      * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
19007      * @return {Region} A Ext.util.Region containing "top, left, bottom, right" member data.
19008      */
19009     getRegion: function() {
19010         return this.getPageBox(true);
19011     },
19012
19013     /**
19014      * Returns the <b>content</b> region of this element. That is the region within the borders and padding.
19015      * @return {Region} A Ext.util.Region containing "top, left, bottom, right" member data.
19016      */
19017     getViewRegion: function() {
19018         var me = this,
19019             isBody = me.dom === document.body,
19020             scroll, pos, top, left, width, height;
19021             
19022         // For the body we want to do some special logic
19023         if (isBody) {
19024             scroll = me.getScroll();
19025             left = scroll.left;
19026             top = scroll.top;
19027             width = Ext.core.Element.getViewportWidth();
19028             height = Ext.core.Element.getViewportHeight();
19029         }
19030         else {
19031             pos = me.getXY();
19032             left = pos[0] + me.getBorderWidth('l') + me.getPadding('l');
19033             top = pos[1] + me.getBorderWidth('t') + me.getPadding('t');
19034             width = me.getWidth(true);
19035             height = me.getHeight(true);
19036         }
19037
19038         return Ext.create('Ext.util.Region', top, left + width, top + height, left);
19039     },
19040
19041     /**
19042      * Return an object defining the area of this Element which can be passed to {@link #setBox} to
19043      * set another Element's size/location to match this element.
19044      * @param {Boolean} asRegion(optional) If true an Ext.util.Region will be returned
19045      * @return {Object} box An object in the format<pre><code>
19046 {
19047     x: &lt;Element's X position>,
19048     y: &lt;Element's Y position>,
19049     width: &lt;Element's width>,
19050     height: &lt;Element's height>,
19051     bottom: &lt;Element's lower bound>,
19052     right: &lt;Element's rightmost bound>
19053 }
19054 </code></pre>
19055      * The returned object may also be addressed as an Array where index 0 contains the X position
19056      * and index 1 contains the Y position. So the result may also be used for {@link #setXY}
19057      */
19058     getPageBox : function(getRegion) {
19059         var me = this,
19060             el = me.dom,
19061             isDoc = el === document.body,
19062             w = isDoc ? Ext.core.Element.getViewWidth()  : el.offsetWidth,
19063             h = isDoc ? Ext.core.Element.getViewHeight() : el.offsetHeight,
19064             xy = me.getXY(),
19065             t = xy[1],
19066             r = xy[0] + w,
19067             b = xy[1] + h,
19068             l = xy[0];
19069
19070         if (getRegion) {
19071             return Ext.create('Ext.util.Region', t, r, b, l);
19072         }
19073         else {
19074             return {
19075                 left: l,
19076                 top: t,
19077                 width: w,
19078                 height: h,
19079                 right: r,
19080                 bottom: b
19081             };
19082         }
19083     },
19084
19085     /**
19086      * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
19087      * @param {Number} x X value for new position (coordinates are page-based)
19088      * @param {Number} y Y value for new position (coordinates are page-based)
19089      * @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul>
19090      * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels)</li>
19091      * <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
19092      * </ul></div>
19093      * @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul>
19094      * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels)</li>
19095      * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
19096      * </ul></div>
19097      * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
19098      * @return {Ext.core.Element} this
19099      */
19100     setBounds: function(x, y, width, height, animate) {
19101         var me = this;
19102         if (!animate || !me.anim) {
19103             me.setSize(width, height);
19104             me.setLocation(x, y);
19105         } else {
19106             if (!Ext.isObject(animate)) {
19107                 animate = {};
19108             }
19109             me.animate(Ext.applyIf({
19110                 to: {
19111                     x: x,
19112                     y: y,
19113                     width: me.adjustWidth(width),
19114                     height: me.adjustHeight(height)
19115                 }
19116             }, animate));
19117         }
19118         return me;
19119     },
19120
19121     /**
19122      * Sets the element's position and size the specified region. If animation is true then width, height, x and y will be animated concurrently.
19123      * @param {Ext.util.Region} region The region to fill
19124      * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
19125      * @return {Ext.core.Element} this
19126      */
19127     setRegion: function(region, animate) {
19128         return this.setBounds(region.left, region.top, region.right - region.left, region.bottom - region.top, animate);
19129     }
19130 });
19131 })();
19132
19133 /**
19134  * @class Ext.core.Element
19135  */
19136 Ext.override(Ext.core.Element, {
19137     /**
19138      * Returns true if this element is scrollable.
19139      * @return {Boolean}
19140      */
19141     isScrollable : function(){
19142         var dom = this.dom;
19143         return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
19144     },
19145
19146     /**
19147      * Returns the current scroll position of the element.
19148      * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
19149      */
19150     getScroll : function() {
19151         var d = this.dom, 
19152             doc = document,
19153             body = doc.body,
19154             docElement = doc.documentElement,
19155             l,
19156             t,
19157             ret;
19158
19159         if (d == doc || d == body) {
19160             if (Ext.isIE && Ext.isStrict) {
19161                 l = docElement.scrollLeft; 
19162                 t = docElement.scrollTop;
19163             } else {
19164                 l = window.pageXOffset;
19165                 t = window.pageYOffset;
19166             }
19167             ret = {
19168                 left: l || (body ? body.scrollLeft : 0), 
19169                 top : t || (body ? body.scrollTop : 0)
19170             };
19171         } else {
19172             ret = {
19173                 left: d.scrollLeft, 
19174                 top : d.scrollTop
19175             };
19176         }
19177         
19178         return ret;
19179     },
19180     
19181     /**
19182      * Scrolls this element the specified scroll point. It does NOT do bounds checking so if you scroll to a weird value it will try to do it. For auto bounds checking, use scroll().
19183      * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
19184      * @param {Number} value The new scroll value
19185      * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
19186      * @return {Element} this
19187      */
19188     scrollTo : function(side, value, animate) {
19189         //check if we're scrolling top or left
19190         var top = /top/i.test(side),
19191             me = this,
19192             dom = me.dom,
19193             obj = {},
19194             prop;
19195         if (!animate || !me.anim) {
19196             // just setting the value, so grab the direction
19197             prop = 'scroll' + (top ? 'Top' : 'Left');
19198             dom[prop] = value;
19199         }
19200         else {
19201             if (!Ext.isObject(animate)) {
19202                 animate = {};
19203             }
19204             obj['scroll' + (top ? 'Top' : 'Left')] = value;
19205             me.animate(Ext.applyIf({
19206                 to: obj
19207             }, animate));
19208         }
19209         return me;
19210     },
19211
19212     /**
19213      * Scrolls this element into view within the passed container.
19214      * @param {Mixed} container (optional) The container element to scroll (defaults to document.body).  Should be a
19215      * string (id), dom node, or Ext.core.Element.
19216      * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
19217      * @return {Ext.core.Element} this
19218      */
19219     scrollIntoView : function(container, hscroll) {
19220         container = Ext.getDom(container) || Ext.getBody().dom;
19221         var el = this.dom,
19222             offsets = this.getOffsetsTo(container),
19223             // el's box
19224             left = offsets[0] + container.scrollLeft,
19225             top = offsets[1] + container.scrollTop,
19226             bottom = top + el.offsetHeight,
19227             right = left + el.offsetWidth,
19228             // ct's box
19229             ctClientHeight = container.clientHeight,
19230             ctScrollTop = parseInt(container.scrollTop, 10),
19231             ctScrollLeft = parseInt(container.scrollLeft, 10),
19232             ctBottom = ctScrollTop + ctClientHeight,
19233             ctRight = ctScrollLeft + container.clientWidth;
19234
19235         if (el.offsetHeight > ctClientHeight || top < ctScrollTop) {
19236             container.scrollTop = top;
19237         } else if (bottom > ctBottom) {
19238             container.scrollTop = bottom - ctClientHeight;
19239         }
19240         // corrects IE, other browsers will ignore
19241         container.scrollTop = container.scrollTop;
19242
19243         if (hscroll !== false) {
19244             if (el.offsetWidth > container.clientWidth || left < ctScrollLeft) {
19245                 container.scrollLeft = left;
19246             }
19247             else if (right > ctRight) {
19248                 container.scrollLeft = right - container.clientWidth;
19249             }
19250             container.scrollLeft = container.scrollLeft;
19251         }
19252         return this;
19253     },
19254
19255     // private
19256     scrollChildIntoView : function(child, hscroll) {
19257         Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
19258     },
19259
19260     /**
19261      * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
19262      * within this element's scrollable range.
19263      * @param {String} direction Possible values are: "l" (or "left"), "r" (or "right"), "t" (or "top", or "up"), "b" (or "bottom", or "down").
19264      * @param {Number} distance How far to scroll the element in pixels
19265      * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
19266      * @return {Boolean} Returns true if a scroll was triggered or false if the element
19267      * was scrolled as far as it could go.
19268      */
19269      scroll : function(direction, distance, animate) {
19270         if (!this.isScrollable()) {
19271             return false;
19272         }
19273         var el = this.dom,
19274             l = el.scrollLeft, t = el.scrollTop,
19275             w = el.scrollWidth, h = el.scrollHeight,
19276             cw = el.clientWidth, ch = el.clientHeight,
19277             scrolled = false, v,
19278             hash = {
19279                 l: Math.min(l + distance, w-cw),
19280                 r: v = Math.max(l - distance, 0),
19281                 t: Math.max(t - distance, 0),
19282                 b: Math.min(t + distance, h-ch)
19283             };
19284             hash.d = hash.b;
19285             hash.u = hash.t;
19286
19287         direction = direction.substr(0, 1);
19288         if ((v = hash[direction]) > -1) {
19289             scrolled = true;
19290             this.scrollTo(direction == 'l' || direction == 'r' ? 'left' : 'top', v, this.anim(animate));
19291         }
19292         return scrolled;
19293     }
19294 });
19295 /**
19296  * @class Ext.core.Element
19297  */
19298 Ext.core.Element.addMethods(
19299     function() {
19300         var VISIBILITY      = "visibility",
19301             DISPLAY         = "display",
19302             HIDDEN          = "hidden",
19303             NONE            = "none",
19304             XMASKED         = Ext.baseCSSPrefix + "masked",
19305             XMASKEDRELATIVE = Ext.baseCSSPrefix + "masked-relative",
19306             data            = Ext.core.Element.data;
19307
19308         return {
19309             /**
19310              * Checks whether the element is currently visible using both visibility and display properties.
19311              * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
19312              * @return {Boolean} True if the element is currently visible, else false
19313              */
19314             isVisible : function(deep) {
19315                 var vis = !this.isStyle(VISIBILITY, HIDDEN) && !this.isStyle(DISPLAY, NONE),
19316                     p   = this.dom.parentNode;
19317
19318                 if (deep !== true || !vis) {
19319                     return vis;
19320                 }
19321
19322                 while (p && !(/^body/i.test(p.tagName))) {
19323                     if (!Ext.fly(p, '_isVisible').isVisible()) {
19324                         return false;
19325                     }
19326                     p = p.parentNode;
19327                 }
19328                 return true;
19329             },
19330
19331             /**
19332              * Returns true if display is not "none"
19333              * @return {Boolean}
19334              */
19335             isDisplayed : function() {
19336                 return !this.isStyle(DISPLAY, NONE);
19337             },
19338
19339             /**
19340              * Convenience method for setVisibilityMode(Element.DISPLAY)
19341              * @param {String} display (optional) What to set display to when visible
19342              * @return {Ext.core.Element} this
19343              */
19344             enableDisplayMode : function(display) {
19345                 this.setVisibilityMode(Ext.core.Element.DISPLAY);
19346
19347                 if (!Ext.isEmpty(display)) {
19348                     data(this.dom, 'originalDisplay', display);
19349                 }
19350
19351                 return this;
19352             },
19353
19354             /**
19355              * Puts a mask over this element to disable user interaction. Requires core.css.
19356              * This method can only be applied to elements which accept child nodes.
19357              * @param {String} msg (optional) A message to display in the mask
19358              * @param {String} msgCls (optional) A css class to apply to the msg element
19359              * @return {Element} The mask element
19360              */
19361             mask : function(msg, msgCls) {
19362                 var me  = this,
19363                     dom = me.dom,
19364                     setExpression = dom.style.setExpression,
19365                     dh  = Ext.core.DomHelper,
19366                     EXTELMASKMSG = Ext.baseCSSPrefix + "mask-msg",
19367                     el,
19368                     mask;
19369
19370                 if (!(/^body/i.test(dom.tagName) && me.getStyle('position') == 'static')) {
19371                     me.addCls(XMASKEDRELATIVE);
19372                 }
19373                 el = data(dom, 'maskMsg');
19374                 if (el) {
19375                     el.remove();
19376                 }
19377                 el = data(dom, 'mask');
19378                 if (el) {
19379                     el.remove();
19380                 }
19381
19382                 mask = dh.append(dom, {cls : Ext.baseCSSPrefix + "mask"}, true);
19383                 data(dom, 'mask', mask);
19384
19385                 me.addCls(XMASKED);
19386                 mask.setDisplayed(true);
19387
19388                 if (typeof msg == 'string') {
19389                     var mm = dh.append(dom, {cls : EXTELMASKMSG, cn:{tag:'div'}}, true);
19390                     data(dom, 'maskMsg', mm);
19391                     mm.dom.className = msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG;
19392                     mm.dom.firstChild.innerHTML = msg;
19393                     mm.setDisplayed(true);
19394                     mm.center(me);
19395                 }
19396                 // NOTE: CSS expressions are resource intensive and to be used only as a last resort
19397                 // These expressions are removed as soon as they are no longer necessary - in the unmask method.
19398                 // In normal use cases an element will be masked for a limited period of time.
19399                 // Fix for https://sencha.jira.com/browse/EXTJSIV-19.
19400                 // IE6 strict mode and IE6-9 quirks mode takes off left+right padding when calculating width!
19401                 if (!Ext.supports.IncludePaddingInWidthCalculation && setExpression) {
19402                     mask.dom.style.setExpression('width', 'this.parentNode.offsetWidth + "px"');
19403                 }
19404
19405                 // Some versions and modes of IE subtract top+bottom padding when calculating height.
19406                 // Different versions from those which make the same error for width!
19407                 if (!Ext.supports.IncludePaddingInHeightCalculation && setExpression) {
19408                     mask.dom.style.setExpression('height', 'this.parentNode.offsetHeight + "px"');
19409                 }
19410                 // ie will not expand full height automatically
19411                 else if (Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && me.getStyle('height') == 'auto') {
19412                     mask.setSize(undefined, me.getHeight());
19413                 }
19414                 return mask;
19415             },
19416
19417             /**
19418              * Removes a previously applied mask.
19419              */
19420             unmask : function() {
19421                 var me      = this,
19422                     dom     = me.dom,
19423                     mask    = data(dom, 'mask'),
19424                     maskMsg = data(dom, 'maskMsg');
19425
19426                 if (mask) {
19427                     // Remove resource-intensive CSS expressions as soon as they are not required.
19428                     if (mask.dom.style.clearExpression) {
19429                         mask.dom.style.clearExpression('width');
19430                         mask.dom.style.clearExpression('height');
19431                     }
19432                     if (maskMsg) {
19433                         maskMsg.remove();
19434                         data(dom, 'maskMsg', undefined);
19435                     }
19436
19437                     mask.remove();
19438                     data(dom, 'mask', undefined);
19439                     me.removeCls([XMASKED, XMASKEDRELATIVE]);
19440                 }
19441             },
19442             /**
19443              * Returns true if this element is masked. Also re-centers any displayed message within the mask.
19444              * @return {Boolean}
19445              */
19446             isMasked : function() {
19447                 var me = this,
19448                     mask = data(me.dom, 'mask'),
19449                     maskMsg = data(me.dom, 'maskMsg');
19450
19451                 if (mask && mask.isVisible()) {
19452                     if (maskMsg) {
19453                         maskMsg.center(me);
19454                     }
19455                     return true;
19456                 }
19457                 return false;
19458             },
19459
19460             /**
19461              * Creates an iframe shim for this element to keep selects and other windowed objects from
19462              * showing through.
19463              * @return {Ext.core.Element} The new shim element
19464              */
19465             createShim : function() {
19466                 var el = document.createElement('iframe'),
19467                     shim;
19468
19469                 el.frameBorder = '0';
19470                 el.className = Ext.baseCSSPrefix + 'shim';
19471                 el.src = Ext.SSL_SECURE_URL;
19472                 shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom));
19473                 shim.autoBoxAdjust = false;
19474                 return shim;
19475             }
19476         };
19477     }()
19478 );
19479 /**
19480  * @class Ext.core.Element
19481  */
19482 Ext.core.Element.addMethods({
19483     /**
19484      * Convenience method for constructing a KeyMap
19485      * @param {Number/Array/Object/String} key Either a string with the keys to listen for, the numeric key code, array of key codes or an object with the following options:
19486      * <code>{key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}</code>
19487      * @param {Function} fn The function to call
19488      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the specified function is executed. Defaults to this Element.
19489      * @return {Ext.util.KeyMap} The KeyMap created
19490      */
19491     addKeyListener : function(key, fn, scope){
19492         var config;
19493         if(typeof key != 'object' || Ext.isArray(key)){
19494             config = {
19495                 key: key,
19496                 fn: fn,
19497                 scope: scope
19498             };
19499         }else{
19500             config = {
19501                 key : key.key,
19502                 shift : key.shift,
19503                 ctrl : key.ctrl,
19504                 alt : key.alt,
19505                 fn: fn,
19506                 scope: scope
19507             };
19508         }
19509         return Ext.create('Ext.util.KeyMap', this, config);
19510     },
19511
19512     /**
19513      * Creates a KeyMap for this element
19514      * @param {Object} config The KeyMap config. See {@link Ext.util.KeyMap} for more details
19515      * @return {Ext.util.KeyMap} The KeyMap created
19516      */
19517     addKeyMap : function(config){
19518         return Ext.create('Ext.util.KeyMap', this, config);
19519     }
19520 });
19521
19522 //Import the newly-added Ext.core.Element functions into CompositeElementLite. We call this here because
19523 //Element.keys.js is the last extra Ext.core.Element include in the ext-all.js build
19524 Ext.CompositeElementLite.importElementMethods();
19525
19526 /**
19527  * @class Ext.CompositeElementLite
19528  */
19529 Ext.apply(Ext.CompositeElementLite.prototype, {
19530     addElements : function(els, root){
19531         if(!els){
19532             return this;
19533         }
19534         if(typeof els == "string"){
19535             els = Ext.core.Element.selectorFunction(els, root);
19536         }
19537         var yels = this.elements;
19538         Ext.each(els, function(e) {
19539             yels.push(Ext.get(e));
19540         });
19541         return this;
19542     },
19543
19544     /**
19545      * Returns the first Element
19546      * @return {Ext.core.Element}
19547      */
19548     first : function(){
19549         return this.item(0);
19550     },
19551
19552     /**
19553      * Returns the last Element
19554      * @return {Ext.core.Element}
19555      */
19556     last : function(){
19557         return this.item(this.getCount()-1);
19558     },
19559
19560     /**
19561      * Returns true if this composite contains the passed element
19562      * @param el {Mixed} The id of an element, or an Ext.core.Element, or an HtmlElement to find within the composite collection.
19563      * @return Boolean
19564      */
19565     contains : function(el){
19566         return this.indexOf(el) != -1;
19567     },
19568
19569     /**
19570     * Removes the specified element(s).
19571     * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
19572     * or an array of any of those.
19573     * @param {Boolean} removeDom (optional) True to also remove the element from the document
19574     * @return {CompositeElement} this
19575     */
19576     removeElement : function(keys, removeDom){
19577         var me = this,
19578             els = this.elements,
19579             el;
19580         Ext.each(keys, function(val){
19581             if ((el = (els[val] || els[val = me.indexOf(val)]))) {
19582                 if(removeDom){
19583                     if(el.dom){
19584                         el.remove();
19585                     }else{
19586                         Ext.removeNode(el);
19587                     }
19588                 }
19589                 els.splice(val, 1);
19590             }
19591         });
19592         return this;
19593     }
19594 });
19595
19596 /**
19597  * @class Ext.CompositeElement
19598  * @extends Ext.CompositeElementLite
19599  * <p>This class encapsulates a <i>collection</i> of DOM elements, providing methods to filter
19600  * members, or to perform collective actions upon the whole set.</p>
19601  * <p>Although they are not listed, this class supports all of the methods of {@link Ext.core.Element} and
19602  * {@link Ext.fx.Anim}. The methods from these classes will be performed on all the elements in this collection.</p>
19603  * <p>All methods return <i>this</i> and can be chained.</p>
19604  * Usage:
19605 <pre><code>
19606 var els = Ext.select("#some-el div.some-class", true);
19607 // or select directly from an existing element
19608 var el = Ext.get('some-el');
19609 el.select('div.some-class', true);
19610
19611 els.setWidth(100); // all elements become 100 width
19612 els.hide(true); // all elements fade out and hide
19613 // or
19614 els.setWidth(100).hide(true);
19615 </code></pre>
19616  */
19617 Ext.CompositeElement = Ext.extend(Ext.CompositeElementLite, {
19618     
19619     constructor : function(els, root){
19620         this.elements = [];
19621         this.add(els, root);
19622     },
19623     
19624     // private
19625     getElement : function(el){
19626         // In this case just return it, since we already have a reference to it
19627         return el;
19628     },
19629     
19630     // private
19631     transformElement : function(el){
19632         return Ext.get(el);
19633     }
19634
19635     /**
19636     * Adds elements to this composite.
19637     * @param {String/Array} els A string CSS selector, an array of elements or an element
19638     * @return {CompositeElement} this
19639     */
19640
19641     /**
19642      * Returns the Element object at the specified index
19643      * @param {Number} index
19644      * @return {Ext.core.Element}
19645      */
19646
19647     /**
19648      * Iterates each `element` in this `composite` calling the supplied function using {@link Ext#each Ext.each}.
19649      * @param {Function} fn 
19650
19651 The function to be called with each
19652 `element`. If the supplied function returns <tt>false</tt>,
19653 iteration stops. This function is called with the following arguments:
19654
19655 - `element` : __Ext.core.Element++
19656     The element at the current `index` in the `composite`
19657     
19658 - `composite` : __Object__ 
19659     This composite.
19660
19661 - `index` : __Number__ 
19662     The current index within the `composite`
19663
19664      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the specified function is executed.
19665      * Defaults to the <code>element</code> at the current <code>index</code>
19666      * within the composite.
19667      * @return {CompositeElement} this
19668      * @markdown
19669      */
19670 });
19671
19672 /**
19673  * Selects elements based on the passed CSS selector to enable {@link Ext.core.Element Element} methods
19674  * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
19675  * {@link Ext.CompositeElementLite CompositeElementLite} object.
19676  * @param {String/Array} selector The CSS selector or an array of elements
19677  * @param {Boolean} unique (optional) true to create a unique Ext.core.Element for each element (defaults to a shared flyweight object)
19678  * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
19679  * @return {CompositeElementLite/CompositeElement}
19680  * @member Ext.core.Element
19681  * @method select
19682  */
19683 Ext.core.Element.select = function(selector, unique, root){
19684     var els;
19685     if(typeof selector == "string"){
19686         els = Ext.core.Element.selectorFunction(selector, root);
19687     }else if(selector.length !== undefined){
19688         els = selector;
19689     }else{
19690         Ext.Error.raise({
19691             sourceClass: "Ext.core.Element",
19692             sourceMethod: "select",
19693             selector: selector,
19694             unique: unique,
19695             root: root,
19696             msg: "Invalid selector specified: " + selector
19697         });
19698     }
19699     return (unique === true) ? new Ext.CompositeElement(els) : new Ext.CompositeElementLite(els);
19700 };
19701
19702 /**
19703  * Selects elements based on the passed CSS selector to enable {@link Ext.core.Element Element} methods
19704  * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
19705  * {@link Ext.CompositeElementLite CompositeElementLite} object.
19706  * @param {String/Array} selector The CSS selector or an array of elements
19707  * @param {Boolean} unique (optional) true to create a unique Ext.core.Element for each element (defaults to a shared flyweight object)
19708  * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
19709  * @return {CompositeElementLite/CompositeElement}
19710  * @member Ext
19711  * @method select
19712  */
19713 Ext.select = Ext.core.Element.select;
19714
19715
19716 /*
19717 Ext JS - JavaScript Library
19718 Copyright (c) 2006-2011, Sencha Inc.
19719 All rights reserved.
19720 licensing@sencha.com
19721 */
19722 /**
19723  * @class Ext.util.Observable
19724  * Base class that provides a common interface for publishing events. Subclasses are expected to
19725  * to have a property "events" with all the events defined, and, optionally, a property "listeners"
19726  * with configured listeners defined.<br>
19727  * For example:
19728  * <pre><code>
19729 Employee = Ext.extend(Ext.util.Observable, {
19730     constructor: function(config){
19731         this.name = config.name;
19732         this.addEvents({
19733             "fired" : true,
19734             "quit" : true
19735         });
19736
19737         // Copy configured listeners into *this* object so that the base class&#39;s
19738         // constructor will add them.
19739         this.listeners = config.listeners;
19740
19741         // Call our superclass constructor to complete construction process.
19742         Employee.superclass.constructor.call(this, config)
19743     }
19744 });
19745 </code></pre>
19746  * This could then be used like this:<pre><code>
19747 var newEmployee = new Employee({
19748     name: employeeName,
19749     listeners: {
19750         quit: function() {
19751             // By default, "this" will be the object that fired the event.
19752             alert(this.name + " has quit!");
19753         }
19754     }
19755 });
19756 </code></pre>
19757  */
19758
19759 Ext.define('Ext.util.Observable', {
19760
19761     /* Begin Definitions */
19762
19763     requires: ['Ext.util.Event'],
19764
19765     statics: {
19766         /**
19767          * Removes <b>all</b> added captures from the Observable.
19768          * @param {Observable} o The Observable to release
19769          * @static
19770          */
19771         releaseCapture: function(o) {
19772             o.fireEvent = this.prototype.fireEvent;
19773         },
19774
19775         /**
19776          * Starts capture on the specified Observable. All events will be passed
19777          * to the supplied function with the event name + standard signature of the event
19778          * <b>before</b> the event is fired. If the supplied function returns false,
19779          * the event will not fire.
19780          * @param {Observable} o The Observable to capture events from.
19781          * @param {Function} fn The function to call when an event is fired.
19782          * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Observable firing the event.
19783          * @static
19784          */
19785         capture: function(o, fn, scope) {
19786             o.fireEvent = Ext.Function.createInterceptor(o.fireEvent, fn, scope);
19787         },
19788
19789         /**
19790 Sets observability on the passed class constructor.
19791
19792 This makes any event fired on any instance of the passed class also fire a single event through
19793 the __class__ allowing for central handling of events on many instances at once.
19794
19795 Usage:
19796
19797     Ext.util.Observable.observe(Ext.data.Connection);
19798     Ext.data.Connection.on('beforerequest', function(con, options) {
19799         console.log('Ajax request made to ' + options.url);
19800     });
19801
19802          * @param {Function} c The class constructor to make observable.
19803          * @param {Object} listeners An object containing a series of listeners to add. See {@link #addListener}.
19804          * @static
19805          * @markdown
19806          */
19807         observe: function(cls, listeners) {
19808             if (cls) {
19809                 if (!cls.isObservable) {
19810                     Ext.applyIf(cls, new this());
19811                     this.capture(cls.prototype, cls.fireEvent, cls);
19812                 }
19813                 if (Ext.isObject(listeners)) {
19814                     cls.on(listeners);
19815                 }
19816                 return cls;
19817             }
19818         }
19819     },
19820
19821     /* End Definitions */
19822
19823     /**
19824     * @cfg {Object} listeners (optional) <p>A config object containing one or more event handlers to be added to this
19825     * object during initialization.  This should be a valid listeners config object as specified in the
19826     * {@link #addListener} example for attaching multiple handlers at once.</p>
19827     * <br><p><b><u>DOM events from ExtJs {@link Ext.Component Components}</u></b></p>
19828     * <br><p>While <i>some</i> ExtJs Component classes export selected DOM events (e.g. "click", "mouseover" etc), this
19829     * is usually only done when extra value can be added. For example the {@link Ext.view.View DataView}'s
19830     * <b><code>{@link Ext.view.View#click click}</code></b> event passing the node clicked on. To access DOM
19831     * events directly from a child element of a Component, we need to specify the <code>element</code> option to
19832     * identify the Component property to add a DOM listener to:
19833     * <pre><code>
19834 new Ext.panel.Panel({
19835     width: 400,
19836     height: 200,
19837     dockedItems: [{
19838         xtype: 'toolbar'
19839     }],
19840     listeners: {
19841         click: {
19842             element: 'el', //bind to the underlying el property on the panel
19843             fn: function(){ console.log('click el'); }
19844         },
19845         dblclick: {
19846             element: 'body', //bind to the underlying body property on the panel
19847             fn: function(){ console.log('dblclick body'); }
19848         }
19849     }
19850 });
19851 </code></pre>
19852     * </p>
19853     */
19854     // @private
19855     isObservable: true,
19856
19857     constructor: function(config) {
19858         var me = this;
19859
19860         Ext.apply(me, config);
19861         if (me.listeners) {
19862             me.on(me.listeners);
19863             delete me.listeners;
19864         }
19865         me.events = me.events || {};
19866
19867         if (me.bubbleEvents) {
19868             me.enableBubble(me.bubbleEvents);
19869         }
19870     },
19871
19872     // @private
19873     eventOptionsRe : /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|element|vertical|horizontal)$/,
19874
19875     /**
19876      * <p>Adds listeners to any Observable object (or Element) which are automatically removed when this Component
19877      * is destroyed.
19878      * @param {Observable/Element} item The item to which to add a listener/listeners.
19879      * @param {Object/String} ename The event name, or an object containing event name properties.
19880      * @param {Function} fn Optional. If the <code>ename</code> parameter was an event name, this
19881      * is the handler function.
19882      * @param {Object} scope Optional. If the <code>ename</code> parameter was an event name, this
19883      * is the scope (<code>this</code> reference) in which the handler function is executed.
19884      * @param {Object} opt Optional. If the <code>ename</code> parameter was an event name, this
19885      * is the {@link Ext.util.Observable#addListener addListener} options.
19886      */
19887     addManagedListener : function(item, ename, fn, scope, options) {
19888         var me = this,
19889             managedListeners = me.managedListeners = me.managedListeners || [],
19890             config;
19891
19892         if (Ext.isObject(ename)) {
19893             options = ename;
19894             for (ename in options) {
19895                 if (options.hasOwnProperty(ename)) {
19896                     config = options[ename];
19897                     if (!me.eventOptionsRe.test(ename)) {
19898                         me.addManagedListener(item, ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
19899                     }
19900                 }
19901             }
19902         }
19903         else {
19904             managedListeners.push({
19905                 item: item,
19906                 ename: ename,
19907                 fn: fn,
19908                 scope: scope,
19909                 options: options
19910             });
19911
19912             item.on(ename, fn, scope, options);
19913         }
19914     },
19915
19916     /**
19917      * Removes listeners that were added by the {@link #mon} method.
19918      * @param {Observable|Element} item The item from which to remove a listener/listeners.
19919      * @param {Object|String} ename The event name, or an object containing event name properties.
19920      * @param {Function} fn Optional. If the <code>ename</code> parameter was an event name, this
19921      * is the handler function.
19922      * @param {Object} scope Optional. If the <code>ename</code> parameter was an event name, this
19923      * is the scope (<code>this</code> reference) in which the handler function is executed.
19924      */
19925      removeManagedListener : function(item, ename, fn, scope) {
19926         var me = this,
19927             options,
19928             config,
19929             managedListeners,
19930             managedListener,
19931             length,
19932             i;
19933
19934         if (Ext.isObject(ename)) {
19935             options = ename;
19936             for (ename in options) {
19937                 if (options.hasOwnProperty(ename)) {
19938                     config = options[ename];
19939                     if (!me.eventOptionsRe.test(ename)) {
19940                         me.removeManagedListener(item, ename, config.fn || config, config.scope || options.scope);
19941                     }
19942                 }
19943             }
19944         }
19945
19946         managedListeners = me.managedListeners ? me.managedListeners.slice() : [];
19947         length = managedListeners.length;
19948
19949         for (i = 0; i < length; i++) {
19950             managedListener = managedListeners[i];
19951             if (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope)) {
19952                 Ext.Array.remove(me.managedListeners, managedListener);
19953                 item.un(managedListener.ename, managedListener.fn, managedListener.scope);
19954             }
19955         }
19956     },
19957
19958     /**
19959      * <p>Fires the specified event with the passed parameters (minus the event name).</p>
19960      * <p>An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget})
19961      * by calling {@link #enableBubble}.</p>
19962      * @param {String} eventName The name of the event to fire.
19963      * @param {Object...} args Variable number of parameters are passed to handlers.
19964      * @return {Boolean} returns false if any of the handlers return false otherwise it returns true.
19965      */
19966     fireEvent: function() {
19967         var me = this,
19968             args = Ext.Array.toArray(arguments),
19969             ename = args[0].toLowerCase(),
19970             ret = true,
19971             event = me.events[ename],
19972             queue = me.eventQueue,
19973             parent;
19974
19975         if (me.eventsSuspended === true) {
19976             if (queue) {
19977                 queue.push(args);
19978             }
19979         } else if (event && Ext.isObject(event) && event.bubble) {
19980             if (event.fire.apply(event, args.slice(1)) === false) {
19981                 return false;
19982             }
19983             parent = me.getBubbleTarget && me.getBubbleTarget();
19984             if (parent && parent.isObservable) {
19985                 if (!parent.events[ename] || !Ext.isObject(parent.events[ename]) || !parent.events[ename].bubble) {
19986                     parent.enableBubble(ename);
19987                 }
19988                 return parent.fireEvent.apply(parent, args);
19989             }
19990         } else if (event && Ext.isObject(event)) {
19991             args.shift();
19992             ret = event.fire.apply(event, args);
19993         }
19994         return ret;
19995     },
19996
19997     /**
19998      * Appends an event handler to this object.
19999      * @param {String}   eventName The name of the event to listen for. May also be an object who's property names are event names. See
20000      * @param {Function} handler The method the event invokes.
20001      * @param {Object}   scope (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed.
20002      * <b>If omitted, defaults to the object which fired the event.</b>
20003      * @param {Object}   options (optional) An object containing handler configuration.
20004      * properties. This may contain any of the following properties:<ul>
20005      * <li><b>scope</b> : Object<div class="sub-desc">The scope (<code><b>this</b></code> reference) in which the handler function is executed.
20006      * <b>If omitted, defaults to the object which fired the event.</b></div></li>
20007      * <li><b>delay</b> : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after the event fires.</div></li>
20008      * <li><b>single</b> : Boolean<div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li>
20009      * <li><b>buffer</b> : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
20010      * by the specified number of milliseconds. If the event fires again within that time, the original
20011      * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
20012      * <li><b>target</b> : Observable<div class="sub-desc">Only call the handler if the event was fired on the target Observable, <i>not</i>
20013      * if the event was bubbled up from a child Observable.</div></li>
20014      * <li><b>element</b> : String<div class="sub-desc"><b>This option is only valid for listeners bound to {@link Ext.Component Components}.</b>
20015      * The name of a Component property which references an element to add a listener to.
20016      * <p>This option is useful during Component construction to add DOM event listeners to elements of {@link Ext.Component Components} which
20017      * will exist only after the Component is rendered. For example, to add a click listener to a Panel's body:<pre><code>
20018 new Ext.panel.Panel({
20019     title: 'The title',
20020     listeners: {
20021         click: this.handlePanelClick,
20022         element: 'body'
20023     }
20024 });
20025 </code></pre></p>
20026      * <p>When added in this way, the options available are the options applicable to {@link Ext.core.Element#addListener}</p></div></li>
20027      * </ul><br>
20028      * <p>
20029      * <b>Combining Options</b><br>
20030      * Using the options argument, it is possible to combine different types of listeners:<br>
20031      * <br>
20032      * A delayed, one-time listener.
20033      * <pre><code>
20034 myPanel.on('hide', this.handleClick, this, {
20035 single: true,
20036 delay: 100
20037 });</code></pre>
20038      * <p>
20039      * <b>Attaching multiple handlers in 1 call</b><br>
20040      * The method also allows for a single argument to be passed which is a config object containing properties
20041      * which specify multiple events. For example:<pre><code>
20042 myGridPanel.on({
20043     cellClick: this.onCellClick,
20044     mouseover: this.onMouseOver,
20045     mouseout: this.onMouseOut,
20046     scope: this // Important. Ensure "this" is correct during handler execution
20047 });
20048 </code></pre>.
20049      * <p>
20050      */
20051     addListener: function(ename, fn, scope, options) {
20052         var me = this,
20053             config,
20054             event;
20055
20056         if (Ext.isObject(ename)) {
20057             options = ename;
20058             for (ename in options) {
20059                 if (options.hasOwnProperty(ename)) {
20060                     config = options[ename];
20061                     if (!me.eventOptionsRe.test(ename)) {
20062                         me.addListener(ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
20063                     }
20064                 }
20065             }
20066         }
20067         else {
20068             ename = ename.toLowerCase();
20069             me.events[ename] = me.events[ename] || true;
20070             event = me.events[ename] || true;
20071             if (Ext.isBoolean(event)) {
20072                 me.events[ename] = event = new Ext.util.Event(me, ename);
20073             }
20074             event.addListener(fn, scope, Ext.isObject(options) ? options : {});
20075         }
20076     },
20077
20078     /**
20079      * Removes an event handler.
20080      * @param {String}   eventName The type of event the handler was associated with.
20081      * @param {Function} handler   The handler to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
20082      * @param {Object}   scope     (optional) The scope originally specified for the handler.
20083      */
20084     removeListener: function(ename, fn, scope) {
20085         var me = this,
20086             config,
20087             event,
20088             options;
20089
20090         if (Ext.isObject(ename)) {
20091             options = ename;
20092             for (ename in options) {
20093                 if (options.hasOwnProperty(ename)) {
20094                     config = options[ename];
20095                     if (!me.eventOptionsRe.test(ename)) {
20096                         me.removeListener(ename, config.fn || config, config.scope || options.scope);
20097                     }
20098                 }
20099             }
20100         } else {
20101             ename = ename.toLowerCase();
20102             event = me.events[ename];
20103             if (event.isEvent) {
20104                 event.removeListener(fn, scope);
20105             }
20106         }
20107     },
20108
20109     /**
20110      * Removes all listeners for this object including the managed listeners
20111      */
20112     clearListeners: function() {
20113         var events = this.events,
20114             event,
20115             key;
20116
20117         for (key in events) {
20118             if (events.hasOwnProperty(key)) {
20119                 event = events[key];
20120                 if (event.isEvent) {
20121                     event.clearListeners();
20122                 }
20123             }
20124         }
20125
20126         this.clearManagedListeners();
20127     },
20128
20129     purgeListeners : function() {
20130         console.warn('Observable: purgeListeners has been deprecated. Please use clearListeners.');
20131         return this.clearListeners.apply(this, arguments);
20132     },
20133
20134     /**
20135      * Removes all managed listeners for this object.
20136      */
20137     clearManagedListeners : function() {
20138         var managedListeners = this.managedListeners || [],
20139             i = 0,
20140             len = managedListeners.length,
20141             managedListener;
20142
20143         for (; i < len; i++) {
20144             managedListener = managedListeners[i];
20145             managedListener.item.un(managedListener.ename, managedListener.fn, managedListener.scope);
20146         }
20147
20148         this.managedListeners = [];
20149     },
20150
20151     purgeManagedListeners : function() {
20152         console.warn('Observable: purgeManagedListeners has been deprecated. Please use clearManagedListeners.');
20153         return this.clearManagedListeners.apply(this, arguments);
20154     },
20155
20156     /**
20157      * Adds the specified events to the list of events which this Observable may fire.
20158      * @param {Object/String} o Either an object with event names as properties with a value of <code>true</code>
20159      * or the first event name string if multiple event names are being passed as separate parameters.
20160      * @param {String} [additional] Optional additional event names if multiple event names are being passed as separate parameters.
20161      * Usage:<pre><code>
20162 this.addEvents('storeloaded', 'storecleared');
20163 </code></pre>
20164      */
20165     addEvents: function(o) {
20166         var me = this,
20167             args,
20168             len,
20169             i;
20170             
20171             me.events = me.events || {};
20172         if (Ext.isString(o)) {
20173             args = arguments;
20174             i = args.length;
20175             
20176             while (i--) {
20177                 me.events[args[i]] = me.events[args[i]] || true;
20178             }
20179         } else {
20180             Ext.applyIf(me.events, o);
20181         }
20182     },
20183
20184     /**
20185      * Checks to see if this object has any listeners for a specified event
20186      * @param {String} eventName The name of the event to check for
20187      * @return {Boolean} True if the event is being listened for, else false
20188      */
20189     hasListener: function(ename) {
20190         var event = this.events[ename.toLowerCase()];
20191         return event && event.isEvent === true && event.listeners.length > 0;
20192     },
20193
20194     /**
20195      * Suspend the firing of all events. (see {@link #resumeEvents})
20196      * @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired
20197      * after the {@link #resumeEvents} call instead of discarding all suspended events;
20198      */
20199     suspendEvents: function(queueSuspended) {
20200         this.eventsSuspended = true;
20201         if (queueSuspended && !this.eventQueue) {
20202             this.eventQueue = [];
20203         }
20204     },
20205
20206     /**
20207      * Resume firing events. (see {@link #suspendEvents})
20208      * If events were suspended using the <code><b>queueSuspended</b></code> parameter, then all
20209      * events fired during event suspension will be sent to any listeners now.
20210      */
20211     resumeEvents: function() {
20212         var me = this,
20213             queued = me.eventQueue || [];
20214
20215         me.eventsSuspended = false;
20216         delete me.eventQueue;
20217
20218         Ext.each(queued,
20219         function(e) {
20220             me.fireEvent.apply(me, e);
20221         });
20222     },
20223
20224     /**
20225      * Relays selected events from the specified Observable as if the events were fired by <code><b>this</b></code>.
20226      * @param {Object} origin The Observable whose events this object is to relay.
20227      * @param {Array} events Array of event names to relay.
20228      */
20229     relayEvents : function(origin, events, prefix) {
20230         prefix = prefix || '';
20231         var me = this,
20232             len = events.length,
20233             i = 0,
20234             oldName,
20235             newName;
20236
20237         for (; i < len; i++) {
20238             oldName = events[i].substr(prefix.length);
20239             newName = prefix + oldName;
20240             me.events[newName] = me.events[newName] || true;
20241             origin.on(oldName, me.createRelayer(newName));
20242         }
20243     },
20244
20245     /**
20246      * @private
20247      * Creates an event handling function which refires the event from this object as the passed event name.
20248      * @param newName
20249      * @returns {Function}
20250      */
20251     createRelayer: function(newName){
20252         var me = this;
20253         return function(){
20254             return me.fireEvent.apply(me, [newName].concat(Array.prototype.slice.call(arguments, 0, -1)));
20255         };
20256     },
20257
20258     /**
20259      * <p>Enables events fired by this Observable to bubble up an owner hierarchy by calling
20260      * <code>this.getBubbleTarget()</code> if present. There is no implementation in the Observable base class.</p>
20261      * <p>This is commonly used by Ext.Components to bubble events to owner Containers. See {@link Ext.Component#getBubbleTarget}. The default
20262      * implementation in Ext.Component returns the Component's immediate owner. But if a known target is required, this can be overridden to
20263      * access the required target more quickly.</p>
20264      * <p>Example:</p><pre><code>
20265 Ext.override(Ext.form.field.Base, {
20266 //  Add functionality to Field&#39;s initComponent to enable the change event to bubble
20267 initComponent : Ext.Function.createSequence(Ext.form.field.Base.prototype.initComponent, function() {
20268     this.enableBubble('change');
20269 }),
20270
20271 //  We know that we want Field&#39;s events to bubble directly to the FormPanel.
20272 getBubbleTarget : function() {
20273     if (!this.formPanel) {
20274         this.formPanel = this.findParentByType('form');
20275     }
20276     return this.formPanel;
20277 }
20278 });
20279
20280 var myForm = new Ext.formPanel({
20281 title: 'User Details',
20282 items: [{
20283     ...
20284 }],
20285 listeners: {
20286     change: function() {
20287         // Title goes red if form has been modified.
20288         myForm.header.setStyle('color', 'red');
20289     }
20290 }
20291 });
20292 </code></pre>
20293      * @param {String/Array} events The event name to bubble, or an Array of event names.
20294      */
20295     enableBubble: function(events) {
20296         var me = this;
20297         if (!Ext.isEmpty(events)) {
20298             events = Ext.isArray(events) ? events: Ext.Array.toArray(arguments);
20299             Ext.each(events,
20300             function(ename) {
20301                 ename = ename.toLowerCase();
20302                 var ce = me.events[ename] || true;
20303                 if (Ext.isBoolean(ce)) {
20304                     ce = new Ext.util.Event(me, ename);
20305                     me.events[ename] = ce;
20306                 }
20307                 ce.bubble = true;
20308             });
20309         }
20310     }
20311 }, function() {
20312     /**
20313      * Removes an event handler (shorthand for {@link #removeListener}.)
20314      * @param {String}   eventName     The type of event the handler was associated with.
20315      * @param {Function} handler       The handler to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
20316      * @param {Object}   scope         (optional) The scope originally specified for the handler.
20317      * @method un
20318      */
20319
20320     /**
20321      * Appends an event handler to this object (shorthand for {@link #addListener}.)
20322      * @param {String}   eventName     The type of event to listen for
20323      * @param {Function} handler       The method the event invokes
20324      * @param {Object}   scope         (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed.
20325      * <b>If omitted, defaults to the object which fired the event.</b>
20326      * @param {Object}   options       (optional) An object containing handler configuration.
20327      * @method on
20328      */
20329
20330     this.createAlias({
20331         on: 'addListener',
20332         un: 'removeListener',
20333         mon: 'addManagedListener',
20334         mun: 'removeManagedListener'
20335     });
20336
20337     //deprecated, will be removed in 5.0
20338     this.observeClass = this.observe;
20339
20340     Ext.apply(Ext.util.Observable.prototype, function(){
20341         // this is considered experimental (along with beforeMethod, afterMethod, removeMethodListener?)
20342         // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
20343         // private
20344         function getMethodEvent(method){
20345             var e = (this.methodEvents = this.methodEvents || {})[method],
20346                 returnValue,
20347                 v,
20348                 cancel,
20349                 obj = this;
20350
20351             if (!e) {
20352                 this.methodEvents[method] = e = {};
20353                 e.originalFn = this[method];
20354                 e.methodName = method;
20355                 e.before = [];
20356                 e.after = [];
20357
20358                 var makeCall = function(fn, scope, args){
20359                     if((v = fn.apply(scope || obj, args)) !== undefined){
20360                         if (typeof v == 'object') {
20361                             if(v.returnValue !== undefined){
20362                                 returnValue = v.returnValue;
20363                             }else{
20364                                 returnValue = v;
20365                             }
20366                             cancel = !!v.cancel;
20367                         }
20368                         else
20369                             if (v === false) {
20370                                 cancel = true;
20371                             }
20372                             else {
20373                                 returnValue = v;
20374                             }
20375                     }
20376                 };
20377
20378                 this[method] = function(){
20379                     var args = Array.prototype.slice.call(arguments, 0),
20380                         b, i, len;
20381                     returnValue = v = undefined;
20382                     cancel = false;
20383
20384                     for(i = 0, len = e.before.length; i < len; i++){
20385                         b = e.before[i];
20386                         makeCall(b.fn, b.scope, args);
20387                         if (cancel) {
20388                             return returnValue;
20389                         }
20390                     }
20391
20392                     if((v = e.originalFn.apply(obj, args)) !== undefined){
20393                         returnValue = v;
20394                     }
20395
20396                     for(i = 0, len = e.after.length; i < len; i++){
20397                         b = e.after[i];
20398                         makeCall(b.fn, b.scope, args);
20399                         if (cancel) {
20400                             return returnValue;
20401                         }
20402                     }
20403                     return returnValue;
20404                 };
20405             }
20406             return e;
20407         }
20408
20409         return {
20410             // these are considered experimental
20411             // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
20412             // adds an 'interceptor' called before the original method
20413             beforeMethod : function(method, fn, scope){
20414                 getMethodEvent.call(this, method).before.push({
20415                     fn: fn,
20416                     scope: scope
20417                 });
20418             },
20419
20420             // adds a 'sequence' called after the original method
20421             afterMethod : function(method, fn, scope){
20422                 getMethodEvent.call(this, method).after.push({
20423                     fn: fn,
20424                     scope: scope
20425                 });
20426             },
20427
20428             removeMethodListener: function(method, fn, scope){
20429                 var e = this.getMethodEvent(method),
20430                     i, len;
20431                 for(i = 0, len = e.before.length; i < len; i++){
20432                     if(e.before[i].fn == fn && e.before[i].scope == scope){
20433                         e.before.splice(i, 1);
20434                         return;
20435                     }
20436                 }
20437                 for(i = 0, len = e.after.length; i < len; i++){
20438                     if(e.after[i].fn == fn && e.after[i].scope == scope){
20439                         e.after.splice(i, 1);
20440                         return;
20441                     }
20442                 }
20443             },
20444
20445             toggleEventLogging: function(toggle) {
20446                 Ext.util.Observable[toggle ? 'capture' : 'releaseCapture'](this, function(en) {
20447                     if (Ext.isDefined(Ext.global.console)) {
20448                         Ext.global.console.log(en, arguments);
20449                     }
20450                 });
20451             }
20452         };
20453     }());
20454 });
20455
20456 /**
20457  * @class Ext.util.Animate
20458  * This animation class is a mixin.
20459  * 
20460  * Ext.util.Animate provides an API for the creation of animated transitions of properties and styles.  
20461  * This class is used as a mixin and currently applied to {@link Ext.core.Element}, {@link Ext.CompositeElement}, 
20462  * {@link Ext.draw.Sprite}, {@link Ext.draw.CompositeSprite}, and {@link Ext.Component}.  Note that Components 
20463  * have a limited subset of what attributes can be animated such as top, left, x, y, height, width, and 
20464  * opacity (color, paddings, and margins can not be animated).
20465  * 
20466  * ## Animation Basics
20467  * 
20468  * All animations require three things - `easing`, `duration`, and `to` (the final end value for each property) 
20469  * you wish to animate. Easing and duration are defaulted values specified below.
20470  * Easing describes how the intermediate values used during a transition will be calculated. 
20471  * {@link Ext.fx.Anim#easing Easing} allows for a transition to change speed over its duration.
20472  * You may use the defaults for easing and duration, but you must always set a 
20473  * {@link Ext.fx.Anim#to to} property which is the end value for all animations.  
20474  * 
20475  * Popular element 'to' configurations are:
20476  * 
20477  *  - opacity
20478  *  - x
20479  *  - y
20480  *  - color
20481  *  - height
20482  *  - width 
20483  * 
20484  * Popular sprite 'to' configurations are:
20485  * 
20486  *  - translation
20487  *  - path
20488  *  - scale
20489  *  - stroke
20490  *  - rotation
20491  * 
20492  * The default duration for animations is 250 (which is a 1/4 of a second).  Duration is denoted in 
20493  * milliseconds.  Therefore 1 second is 1000, 1 minute would be 60000, and so on. The default easing curve 
20494  * used for all animations is 'ease'.  Popular easing functions are included and can be found in {@link Ext.fx.Anim#easing Easing}.
20495  * 
20496  * For example, a simple animation to fade out an element with a default easing and duration:
20497  * 
20498  *     var p1 = Ext.get('myElementId');
20499  * 
20500  *     p1.animate({
20501  *         to: {
20502  *             opacity: 0
20503  *         }
20504  *     });
20505  * 
20506  * To make this animation fade out in a tenth of a second:
20507  * 
20508  *     var p1 = Ext.get('myElementId');
20509  * 
20510  *     p1.animate({
20511  *        duration: 100,
20512  *         to: {
20513  *             opacity: 0
20514  *         }
20515  *     });
20516  * 
20517  * ## Animation Queues
20518  * 
20519  * By default all animations are added to a queue which allows for animation via a chain-style API.
20520  * For example, the following code will queue 4 animations which occur sequentially (one right after the other):
20521  * 
20522  *     p1.animate({
20523  *         to: {
20524  *             x: 500
20525  *         }
20526  *     }).animate({
20527  *         to: {
20528  *             y: 150
20529  *         }
20530  *     }).animate({
20531  *         to: {
20532  *             backgroundColor: '#f00'  //red
20533  *         }
20534  *     }).animate({
20535  *         to: {
20536  *             opacity: 0
20537  *         }
20538  *     });
20539  * 
20540  * You can change this behavior by calling the {@link Ext.util.Animate#syncFx syncFx} method and all 
20541  * subsequent animations for the specified target will be run concurrently (at the same time).
20542  * 
20543  *     p1.syncFx();  //this will make all animations run at the same time
20544  * 
20545  *     p1.animate({
20546  *         to: {
20547  *             x: 500
20548  *         }
20549  *     }).animate({
20550  *         to: {
20551  *             y: 150
20552  *         }
20553  *     }).animate({
20554  *         to: {
20555  *             backgroundColor: '#f00'  //red
20556  *         }
20557  *     }).animate({
20558  *         to: {
20559  *             opacity: 0
20560  *         }
20561  *     });
20562  * 
20563  * This works the same as:
20564  * 
20565  *     p1.animate({
20566  *         to: {
20567  *             x: 500,
20568  *             y: 150,
20569  *             backgroundColor: '#f00'  //red
20570  *             opacity: 0
20571  *         }
20572  *     });
20573  * 
20574  * The {@link Ext.util.Animate#stopAnimation stopAnimation} method can be used to stop any 
20575  * currently running animations and clear any queued animations. 
20576  * 
20577  * ## Animation Keyframes
20578  *
20579  * You can also set up complex animations with {@link Ext.fx.Anim#keyframe keyframe} which follows the 
20580  * CSS3 Animation configuration pattern. Note rotation, translation, and scaling can only be done for sprites. 
20581  * The previous example can be written with the following syntax:
20582  * 
20583  *     p1.animate({
20584  *         duration: 1000,  //one second total
20585  *         keyframes: {
20586  *             25: {     //from 0 to 250ms (25%)
20587  *                 x: 0
20588  *             },
20589  *             50: {   //from 250ms to 500ms (50%)
20590  *                 y: 0
20591  *             },
20592  *             75: {  //from 500ms to 750ms (75%)
20593  *                 backgroundColor: '#f00'  //red
20594  *             },
20595  *             100: {  //from 750ms to 1sec
20596  *                 opacity: 0
20597  *             }
20598  *         }
20599  *     });
20600  * 
20601  * ## Animation Events
20602  * 
20603  * Each animation you create has events for {@link Ext.fx.Anim#beforeanimation beforeanimation}, 
20604  * {@link Ext.fx.Anim#afteranimate afteranimate}, and {@link Ext.fx.Anim#lastframe lastframe}.  
20605  * Keyframed animations adds an additional {@link Ext.fx.Animator#keyframe keyframe} event which 
20606  * fires for each keyframe in your animation.
20607  * 
20608  * All animations support the {@link Ext.util.Observable#listeners listeners} configuration to attact functions to these events.
20609  *    
20610  *     startAnimate: function() {
20611  *         var p1 = Ext.get('myElementId');
20612  *         p1.animate({
20613  *            duration: 100,
20614  *             to: {
20615  *                 opacity: 0
20616  *             },
20617  *             listeners: {
20618  *                 beforeanimate:  function() {
20619  *                     // Execute my custom method before the animation
20620  *                     this.myBeforeAnimateFn();
20621  *                 },
20622  *                 afteranimate: function() {
20623  *                     // Execute my custom method after the animation
20624  *                     this.myAfterAnimateFn();
20625  *                 },
20626  *                 scope: this
20627  *         });
20628  *     },
20629  *     myBeforeAnimateFn: function() {
20630  *       // My custom logic
20631  *     },
20632  *     myAfterAnimateFn: function() {
20633  *       // My custom logic
20634  *     }
20635  * 
20636  * Due to the fact that animations run asynchronously, you can determine if an animation is currently 
20637  * running on any target by using the {@link Ext.util.Animate#getActiveAnimation getActiveAnimation} 
20638  * method.  This method will return false if there are no active animations or return the currently 
20639  * running {@link Ext.fx.Anim} instance.
20640  * 
20641  * In this example, we're going to wait for the current animation to finish, then stop any other 
20642  * queued animations before we fade our element's opacity to 0:
20643  * 
20644  *     var curAnim = p1.getActiveAnimation();
20645  *     if (curAnim) {
20646  *         curAnim.on('afteranimate', function() {
20647  *             p1.stopAnimation();
20648  *             p1.animate({
20649  *                 to: {
20650  *                     opacity: 0
20651  *                 }
20652  *             });
20653  *         });
20654  *     }
20655  * 
20656  * @docauthor Jamie Avins <jamie@sencha.com>
20657  */
20658 Ext.define('Ext.util.Animate', {
20659
20660     uses: ['Ext.fx.Manager', 'Ext.fx.Anim'],
20661
20662     /**
20663      * <p>Perform custom animation on this object.<p>
20664      * <p>This method is applicable to both the the {@link Ext.Component Component} class and the {@link Ext.core.Element Element} class.
20665      * It performs animated transitions of certain properties of this object over a specified timeline.</p>
20666      * <p>The sole parameter is an object which specifies start property values, end property values, and properties which
20667      * describe the timeline. Of the properties listed below, only <b><code>to</code></b> is mandatory.</p>
20668      * <p>Properties include<ul>
20669      * <li><code>from</code> <div class="sub-desc">An object which specifies start values for the properties being animated.
20670      * If not supplied, properties are animated from current settings. The actual properties which may be animated depend upon
20671      * ths object being animated. See the sections below on Element and Component animation.<div></li>
20672      * <li><code>to</code> <div class="sub-desc">An object which specifies end values for the properties being animated.</div></li>
20673      * <li><code>duration</code><div class="sub-desc">The duration <b>in milliseconds</b> for which the animation will run.</div></li>
20674      * <li><code>easing</code> <div class="sub-desc">A string value describing an easing type to modify the rate of change from the default linear to non-linear. Values may be one of:<code><ul>
20675      * <li>ease</li>
20676      * <li>easeIn</li>
20677      * <li>easeOut</li>
20678      * <li>easeInOut</li>
20679      * <li>backIn</li>
20680      * <li>backOut</li>
20681      * <li>elasticIn</li>
20682      * <li>elasticOut</li>
20683      * <li>bounceIn</li>
20684      * <li>bounceOut</li>
20685      * </ul></code></div></li>
20686      * <li><code>keyframes</code> <div class="sub-desc">This is an object which describes the state of animated properties at certain points along the timeline.
20687      * it is an object containing properties who's names are the percentage along the timeline being described and who's values specify the animation state at that point.</div></li>
20688      * <li><code>listeners</code> <div class="sub-desc">This is a standard {@link Ext.util.Observable#listeners listeners} configuration object which may be used
20689      * to inject behaviour at either the <code>beforeanimate</code> event or the <code>afteranimate</code> event.</div></li>
20690      * </ul></p>
20691      * <h3>Animating an {@link Ext.core.Element Element}</h3>
20692      * When animating an Element, the following properties may be specified in <code>from</code>, <code>to</code>, and <code>keyframe</code> objects:<ul>
20693      * <li><code>x</code> <div class="sub-desc">The page X position in pixels.</div></li>
20694      * <li><code>y</code> <div class="sub-desc">The page Y position in pixels</div></li>
20695      * <li><code>left</code> <div class="sub-desc">The element's CSS <code>left</code> value. Units must be supplied.</div></li>
20696      * <li><code>top</code> <div class="sub-desc">The element's CSS <code>top</code> value. Units must be supplied.</div></li>
20697      * <li><code>width</code> <div class="sub-desc">The element's CSS <code>width</code> value. Units must be supplied.</div></li>
20698      * <li><code>height</code> <div class="sub-desc">The element's CSS <code>height</code> value. Units must be supplied.</div></li>
20699      * <li><code>scrollLeft</code> <div class="sub-desc">The element's <code>scrollLeft</code> value.</div></li>
20700      * <li><code>scrollTop</code> <div class="sub-desc">The element's <code>scrollLeft</code> value.</div></li>
20701      * <li><code>opacity</code> <div class="sub-desc">The element's <code>opacity</code> value. This must be a value between <code>0</code> and <code>1</code>.</div></li>
20702      * </ul>
20703      * <p><b>Be aware than animating an Element which is being used by an Ext Component without in some way informing the Component about the changed element state
20704      * will result in incorrect Component behaviour. This is because the Component will be using the old state of the element. To avoid this problem, it is now possible to
20705      * directly animate certain properties of Components.</b></p>
20706      * <h3>Animating a {@link Ext.Component Component}</h3>
20707      * When animating an Element, the following properties may be specified in <code>from</code>, <code>to</code>, and <code>keyframe</code> objects:<ul>
20708      * <li><code>x</code> <div class="sub-desc">The Component's page X position in pixels.</div></li>
20709      * <li><code>y</code> <div class="sub-desc">The Component's page Y position in pixels</div></li>
20710      * <li><code>left</code> <div class="sub-desc">The Component's <code>left</code> value in pixels.</div></li>
20711      * <li><code>top</code> <div class="sub-desc">The Component's <code>top</code> value in pixels.</div></li>
20712      * <li><code>width</code> <div class="sub-desc">The Component's <code>width</code> value in pixels.</div></li>
20713      * <li><code>width</code> <div class="sub-desc">The Component's <code>width</code> value in pixels.</div></li>
20714      * <li><code>dynamic</code> <div class="sub-desc">Specify as true to update the Component's layout (if it is a Container) at every frame
20715      * of the animation. <i>Use sparingly as laying out on every intermediate size change is an expensive operation</i>.</div></li>
20716      * </ul>
20717      * <p>For example, to animate a Window to a new size, ensuring that its internal layout, and any shadow is correct:</p>
20718      * <pre><code>
20719 myWindow = Ext.create('Ext.window.Window', {
20720     title: 'Test Component animation',
20721     width: 500,
20722     height: 300,
20723     layout: {
20724         type: 'hbox',
20725         align: 'stretch'
20726     },
20727     items: [{
20728         title: 'Left: 33%',
20729         margins: '5 0 5 5',
20730         flex: 1
20731     }, {
20732         title: 'Left: 66%',
20733         margins: '5 5 5 5',
20734         flex: 2
20735     }]
20736 });
20737 myWindow.show();
20738 myWindow.header.el.on('click', function() {
20739     myWindow.animate({
20740         to: {
20741             width: (myWindow.getWidth() == 500) ? 700 : 500,
20742             height: (myWindow.getHeight() == 300) ? 400 : 300,
20743         }
20744     });
20745 });
20746 </code></pre>
20747      * <p>For performance reasons, by default, the internal layout is only updated when the Window reaches its final <code>"to"</code> size. If dynamic updating of the Window's child
20748      * Components is required, then configure the animation with <code>dynamic: true</code> and the two child items will maintain their proportions during the animation.</p>
20749      * @param {Object} config An object containing properties which describe the animation's start and end states, and the timeline of the animation.
20750      * @return {Object} this
20751      */
20752     animate: function(animObj) {
20753         var me = this;
20754         if (Ext.fx.Manager.hasFxBlock(me.id)) {
20755             return me;
20756         }
20757         Ext.fx.Manager.queueFx(Ext.create('Ext.fx.Anim', me.anim(animObj)));
20758         return this;
20759     },
20760
20761     // @private - process the passed fx configuration.
20762     anim: function(config) {
20763         if (!Ext.isObject(config)) {
20764             return (config) ? {} : false;
20765         }
20766
20767         var me = this;
20768
20769         if (config.stopAnimation) {
20770             me.stopAnimation();
20771         }
20772
20773         Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id));
20774
20775         return Ext.apply({
20776             target: me,
20777             paused: true
20778         }, config);
20779     },
20780
20781     /**
20782      * Stops any running effects and clears this object's internal effects queue if it contains
20783      * any additional effects that haven't started yet.
20784      * @return {Ext.core.Element} The Element
20785      */
20786     stopFx: Ext.Function.alias(Ext.util.Animate, 'stopAnimation'),
20787
20788     /**
20789      * @deprecated 4.0 Replaced by {@link #stopAnimation}
20790      * Stops any running effects and clears this object's internal effects queue if it contains
20791      * any additional effects that haven't started yet.
20792      * @return {Ext.core.Element} The Element
20793      */
20794     stopAnimation: function() {
20795         Ext.fx.Manager.stopAnimation(this.id);
20796     },
20797
20798     /**
20799      * Ensures that all effects queued after syncFx is called on this object are
20800      * run concurrently.  This is the opposite of {@link #sequenceFx}.
20801      * @return {Ext.core.Element} The Element
20802      */
20803     syncFx: function() {
20804         Ext.fx.Manager.setFxDefaults(this.id, {
20805             concurrent: true
20806         });
20807     },
20808
20809     /**
20810      * Ensures that all effects queued after sequenceFx is called on this object are
20811      * run in sequence.  This is the opposite of {@link #syncFx}.
20812      * @return {Ext.core.Element} The Element
20813      */
20814     sequenceFx: function() {
20815         Ext.fx.Manager.setFxDefaults(this.id, {
20816             concurrent: false
20817         });
20818     },
20819
20820     /**
20821      * @deprecated 4.0 Replaced by {@link #getActiveAnimation}
20822      * Returns thq current animation if this object has any effects actively running or queued, else returns false.
20823      * @return {Mixed} anim if element has active effects, else false
20824      */
20825     hasActiveFx: Ext.Function.alias(Ext.util.Animate, 'getActiveAnimation'),
20826
20827     /**
20828      * Returns thq current animation if this object has any effects actively running or queued, else returns false.
20829      * @return {Mixed} anim if element has active effects, else false
20830      */
20831     getActiveAnimation: function() {
20832         return Ext.fx.Manager.getActiveAnimation(this.id);
20833     }
20834 });
20835
20836 // Apply Animate mixin manually until Element is defined in the proper 4.x way
20837 Ext.applyIf(Ext.core.Element.prototype, Ext.util.Animate.prototype);
20838 /**
20839  * @class Ext.state.Provider
20840  * <p>Abstract base class for state provider implementations. The provider is responsible
20841  * for setting values  and extracting values to/from the underlying storage source. The 
20842  * storage source can vary and the details should be implemented in a subclass. For example
20843  * a provider could use a server side database or the browser localstorage where supported.</p>
20844  *
20845  * <p>This class provides methods for encoding and decoding <b>typed</b> variables including 
20846  * dates and defines the Provider interface. By default these methods put the value and the
20847  * type information into a delimited string that can be stored. These should be overridden in 
20848  * a subclass if you want to change the format of the encoded value and subsequent decoding.</p>
20849  */
20850 Ext.define('Ext.state.Provider', {
20851     mixins: {
20852         observable: 'Ext.util.Observable'
20853     },
20854     
20855     /**
20856      * @cfg {String} prefix A string to prefix to items stored in the underlying state store. 
20857      * Defaults to <tt>'ext-'</tt>
20858      */
20859     prefix: 'ext-',
20860     
20861     constructor : function(config){
20862         config = config || {};
20863         var me = this;
20864         Ext.apply(me, config);
20865         /**
20866          * @event statechange
20867          * Fires when a state change occurs.
20868          * @param {Provider} this This state provider
20869          * @param {String} key The state key which was changed
20870          * @param {String} value The encoded value for the state
20871          */
20872         me.addEvents("statechange");
20873         me.state = {};
20874         me.mixins.observable.constructor.call(me);
20875     },
20876     
20877     /**
20878      * Returns the current value for a key
20879      * @param {String} name The key name
20880      * @param {Mixed} defaultValue A default value to return if the key's value is not found
20881      * @return {Mixed} The state data
20882      */
20883     get : function(name, defaultValue){
20884         return typeof this.state[name] == "undefined" ?
20885             defaultValue : this.state[name];
20886     },
20887
20888     /**
20889      * Clears a value from the state
20890      * @param {String} name The key name
20891      */
20892     clear : function(name){
20893         var me = this;
20894         delete me.state[name];
20895         me.fireEvent("statechange", me, name, null);
20896     },
20897
20898     /**
20899      * Sets the value for a key
20900      * @param {String} name The key name
20901      * @param {Mixed} value The value to set
20902      */
20903     set : function(name, value){
20904         var me = this;
20905         me.state[name] = value;
20906         me.fireEvent("statechange", me, name, value);
20907     },
20908
20909     /**
20910      * Decodes a string previously encoded with {@link #encodeValue}.
20911      * @param {String} value The value to decode
20912      * @return {Mixed} The decoded value
20913      */
20914     decodeValue : function(value){
20915
20916         // a -> Array
20917         // n -> Number
20918         // d -> Date
20919         // b -> Boolean
20920         // s -> String
20921         // o -> Object
20922         // -> Empty (null)
20923
20924         var me = this,
20925             re = /^(a|n|d|b|s|o|e)\:(.*)$/,
20926             matches = re.exec(unescape(value)),
20927             all,
20928             type,
20929             value,
20930             keyValue;
20931             
20932         if(!matches || !matches[1]){
20933             return; // non state
20934         }
20935         
20936         type = matches[1];
20937         value = matches[2];
20938         switch (type) {
20939             case 'e':
20940                 return null;
20941             case 'n':
20942                 return parseFloat(value);
20943             case 'd':
20944                 return new Date(Date.parse(value));
20945             case 'b':
20946                 return (value == '1');
20947             case 'a':
20948                 all = [];
20949                 if(value != ''){
20950                     Ext.each(value.split('^'), function(val){
20951                         all.push(me.decodeValue(val));
20952                     }, me);
20953                 }
20954                 return all;
20955            case 'o':
20956                 all = {};
20957                 if(value != ''){
20958                     Ext.each(value.split('^'), function(val){
20959                         keyValue = val.split('=');
20960                         all[keyValue[0]] = me.decodeValue(keyValue[1]);
20961                     }, me);
20962                 }
20963                 return all;
20964            default:
20965                 return value;
20966         }
20967     },
20968
20969     /**
20970      * Encodes a value including type information.  Decode with {@link #decodeValue}.
20971      * @param {Mixed} value The value to encode
20972      * @return {String} The encoded value
20973      */
20974     encodeValue : function(value){
20975         var flat = '',
20976             i = 0,
20977             enc,
20978             len,
20979             key;
20980             
20981         if (value == null) {
20982             return 'e:1';    
20983         } else if(typeof value == 'number') {
20984             enc = 'n:' + value;
20985         } else if(typeof value == 'boolean') {
20986             enc = 'b:' + (value ? '1' : '0');
20987         } else if(Ext.isDate(value)) {
20988             enc = 'd:' + value.toGMTString();
20989         } else if(Ext.isArray(value)) {
20990             for (len = value.length; i < len; i++) {
20991                 flat += this.encodeValue(value[i]);
20992                 if (i != len - 1) {
20993                     flat += '^';
20994                 }
20995             }
20996             enc = 'a:' + flat;
20997         } else if (typeof value == 'object') {
20998             for (key in value) {
20999                 if (typeof value[key] != 'function' && value[key] !== undefined) {
21000                     flat += key + '=' + this.encodeValue(value[key]) + '^';
21001                 }
21002             }
21003             enc = 'o:' + flat.substring(0, flat.length-1);
21004         } else {
21005             enc = 's:' + value;
21006         }
21007         return escape(enc);
21008     }
21009 });
21010 /**
21011  * @class Ext.util.HashMap
21012  * <p>
21013  * Represents a collection of a set of key and value pairs. Each key in the HashMap
21014  * must be unique, the same key cannot exist twice. Access to items is provided via
21015  * the key only. Sample usage:
21016  * <pre><code>
21017 var map = new Ext.util.HashMap();
21018 map.add('key1', 1);
21019 map.add('key2', 2);
21020 map.add('key3', 3);
21021
21022 map.each(function(key, value, length){
21023     console.log(key, value, length);
21024 });
21025  * </code></pre>
21026  * </p>
21027  *
21028  * <p>The HashMap is an unordered class,
21029  * there is no guarantee when iterating over the items that they will be in any particular
21030  * order. If this is required, then use a {@link Ext.util.MixedCollection}.
21031  * </p>
21032  * @constructor
21033  * @param {Object} config The configuration options
21034  */
21035 Ext.define('Ext.util.HashMap', {
21036
21037     /**
21038      * @cfg {Function} keyFn A function that is used to retrieve a default key for a passed object.
21039      * A default is provided that returns the <b>id</b> property on the object. This function is only used
21040      * if the add method is called with a single argument.
21041      */
21042
21043     mixins: {
21044         observable: 'Ext.util.Observable'
21045     },
21046
21047     constructor: function(config) {
21048         var me = this;
21049
21050         me.addEvents(
21051             /**
21052              * @event add
21053              * Fires when a new item is added to the hash
21054              * @param {Ext.util.HashMap} this.
21055              * @param {String} key The key of the added item.
21056              * @param {Object} value The value of the added item.
21057              */
21058             'add',
21059             /**
21060              * @event clear
21061              * Fires when the hash is cleared.
21062              * @param {Ext.util.HashMap} this.
21063              */
21064             'clear',
21065             /**
21066              * @event remove
21067              * Fires when an item is removed from the hash.
21068              * @param {Ext.util.HashMap} this.
21069              * @param {String} key The key of the removed item.
21070              * @param {Object} value The value of the removed item.
21071              */
21072             'remove',
21073             /**
21074              * @event replace
21075              * Fires when an item is replaced in the hash.
21076              * @param {Ext.util.HashMap} this.
21077              * @param {String} key The key of the replaced item.
21078              * @param {Object} value The new value for the item.
21079              * @param {Object} old The old value for the item.
21080              */
21081             'replace'
21082         );
21083
21084         me.mixins.observable.constructor.call(me, config);
21085         me.clear(true);
21086     },
21087
21088     /**
21089      * Gets the number of items in the hash.
21090      * @return {Number} The number of items in the hash.
21091      */
21092     getCount: function() {
21093         return this.length;
21094     },
21095
21096     /**
21097      * Implementation for being able to extract the key from an object if only
21098      * a single argument is passed.
21099      * @private
21100      * @param {String} key The key
21101      * @param {Object} value The value
21102      * @return {Array} [key, value]
21103      */
21104     getData: function(key, value) {
21105         // if we have no value, it means we need to get the key from the object
21106         if (value === undefined) {
21107             value = key;
21108             key = this.getKey(value);
21109         }
21110
21111         return [key, value];
21112     },
21113
21114     /**
21115      * Extracts the key from an object. This is a default implementation, it may be overridden
21116      * @private
21117      * @param {Object} o The object to get the key from
21118      * @return {String} The key to use.
21119      */
21120     getKey: function(o) {
21121         return o.id;
21122     },
21123
21124     /**
21125      * Adds an item to the collection. Fires the {@link #add} event when complete.
21126      * @param {String} key <p>The key to associate with the item, or the new item.</p>
21127      * <p>If a {@link #getKey} implementation was specified for this HashMap,
21128      * or if the key of the stored items is in a property called <tt><b>id</b></tt>,
21129      * the HashMap will be able to <i>derive</i> the key for the new item.
21130      * In this case just pass the new item in this parameter.</p>
21131      * @param {Object} o The item to add.
21132      * @return {Object} The item added.
21133      */
21134     add: function(key, value) {
21135         var me = this,
21136             data;
21137
21138         if (arguments.length === 1) {
21139             value = key;
21140             key = me.getKey(value);
21141         }
21142
21143         if (me.containsKey(key)) {
21144             me.replace(key, value);
21145         }
21146
21147         data = me.getData(key, value);
21148         key = data[0];
21149         value = data[1];
21150         me.map[key] = value;
21151         ++me.length;
21152         me.fireEvent('add', me, key, value);
21153         return value;
21154     },
21155
21156     /**
21157      * Replaces an item in the hash. If the key doesn't exist, the
21158      * {@link #add} method will be used.
21159      * @param {String} key The key of the item.
21160      * @param {Object} value The new value for the item.
21161      * @return {Object} The new value of the item.
21162      */
21163     replace: function(key, value) {
21164         var me = this,
21165             map = me.map,
21166             old;
21167
21168         if (!me.containsKey(key)) {
21169             me.add(key, value);
21170         }
21171         old = map[key];
21172         map[key] = value;
21173         me.fireEvent('replace', me, key, value, old);
21174         return value;
21175     },
21176
21177     /**
21178      * Remove an item from the hash.
21179      * @param {Object} o The value of the item to remove.
21180      * @return {Boolean} True if the item was successfully removed.
21181      */
21182     remove: function(o) {
21183         var key = this.findKey(o);
21184         if (key !== undefined) {
21185             return this.removeAtKey(key);
21186         }
21187         return false;
21188     },
21189
21190     /**
21191      * Remove an item from the hash.
21192      * @param {String} key The key to remove.
21193      * @return {Boolean} True if the item was successfully removed.
21194      */
21195     removeAtKey: function(key) {
21196         var me = this,
21197             value;
21198
21199         if (me.containsKey(key)) {
21200             value = me.map[key];
21201             delete me.map[key];
21202             --me.length;
21203             me.fireEvent('remove', me, key, value);
21204             return true;
21205         }
21206         return false;
21207     },
21208
21209     /**
21210      * Retrieves an item with a particular key.
21211      * @param {String} key The key to lookup.
21212      * @return {Object} The value at that key. If it doesn't exist, <tt>undefined</tt> is returned.
21213      */
21214     get: function(key) {
21215         return this.map[key];
21216     },
21217
21218     /**
21219      * Removes all items from the hash.
21220      * @return {Ext.util.HashMap} this
21221      */
21222     clear: function(/* private */ initial) {
21223         var me = this;
21224         me.map = {};
21225         me.length = 0;
21226         if (initial !== true) {
21227             me.fireEvent('clear', me);
21228         }
21229         return me;
21230     },
21231
21232     /**
21233      * Checks whether a key exists in the hash.
21234      * @param {String} key The key to check for.
21235      * @return {Boolean} True if they key exists in the hash.
21236      */
21237     containsKey: function(key) {
21238         return this.map[key] !== undefined;
21239     },
21240
21241     /**
21242      * Checks whether a value exists in the hash.
21243      * @param {Object} value The value to check for.
21244      * @return {Boolean} True if the value exists in the dictionary.
21245      */
21246     contains: function(value) {
21247         return this.containsKey(this.findKey(value));
21248     },
21249
21250     /**
21251      * Return all of the keys in the hash.
21252      * @return {Array} An array of keys.
21253      */
21254     getKeys: function() {
21255         return this.getArray(true);
21256     },
21257
21258     /**
21259      * Return all of the values in the hash.
21260      * @return {Array} An array of values.
21261      */
21262     getValues: function() {
21263         return this.getArray(false);
21264     },
21265
21266     /**
21267      * Gets either the keys/values in an array from the hash.
21268      * @private
21269      * @param {Boolean} isKey True to extract the keys, otherwise, the value
21270      * @return {Array} An array of either keys/values from the hash.
21271      */
21272     getArray: function(isKey) {
21273         var arr = [],
21274             key,
21275             map = this.map;
21276         for (key in map) {
21277             if (map.hasOwnProperty(key)) {
21278                 arr.push(isKey ? key: map[key]);
21279             }
21280         }
21281         return arr;
21282     },
21283
21284     /**
21285      * Executes the specified function once for each item in the hash.
21286      * Returning false from the function will cease iteration.
21287      *
21288      * The paramaters passed to the function are:
21289      * <div class="mdetail-params"><ul>
21290      * <li><b>key</b> : String<p class="sub-desc">The key of the item</p></li>
21291      * <li><b>value</b> : Number<p class="sub-desc">The value of the item</p></li>
21292      * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the hash</p></li>
21293      * </ul></div>
21294      * @param {Function} fn The function to execute.
21295      * @param {Object} scope The scope to execute in. Defaults to <tt>this</tt>.
21296      * @return {Ext.util.HashMap} this
21297      */
21298     each: function(fn, scope) {
21299         // copy items so they may be removed during iteration.
21300         var items = Ext.apply({}, this.map),
21301             key,
21302             length = this.length;
21303
21304         scope = scope || this;
21305         for (key in items) {
21306             if (items.hasOwnProperty(key)) {
21307                 if (fn.call(scope, key, items[key], length) === false) {
21308                     break;
21309                 }
21310             }
21311         }
21312         return this;
21313     },
21314
21315     /**
21316      * Performs a shallow copy on this hash.
21317      * @return {Ext.util.HashMap} The new hash object.
21318      */
21319     clone: function() {
21320         var hash = new this.self(),
21321             map = this.map,
21322             key;
21323
21324         hash.suspendEvents();
21325         for (key in map) {
21326             if (map.hasOwnProperty(key)) {
21327                 hash.add(key, map[key]);
21328             }
21329         }
21330         hash.resumeEvents();
21331         return hash;
21332     },
21333
21334     /**
21335      * @private
21336      * Find the key for a value.
21337      * @param {Object} value The value to find.
21338      * @return {Object} The value of the item. Returns <tt>undefined</tt> if not found.
21339      */
21340     findKey: function(value) {
21341         var key,
21342             map = this.map;
21343
21344         for (key in map) {
21345             if (map.hasOwnProperty(key) && map[key] === value) {
21346                 return key;
21347             }
21348         }
21349         return undefined;
21350     }
21351 });
21352
21353 /**
21354  * @class Ext.Template
21355  * <p>Represents an HTML fragment template. Templates may be {@link #compile precompiled}
21356  * for greater performance.</p>
21357  * An instance of this class may be created by passing to the constructor either
21358  * a single argument, or multiple arguments:
21359  * <div class="mdetail-params"><ul>
21360  * <li><b>single argument</b> : String/Array
21361  * <div class="sub-desc">
21362  * The single argument may be either a String or an Array:<ul>
21363  * <li><tt>String</tt> : </li><pre><code>
21364 var t = new Ext.Template("&lt;div>Hello {0}.&lt;/div>");
21365 t.{@link #append}('some-element', ['foo']);
21366    </code></pre>
21367  * <li><tt>Array</tt> : </li>
21368  * An Array will be combined with <code>join('')</code>.
21369 <pre><code>
21370 var t = new Ext.Template([
21371     '&lt;div name="{id}"&gt;',
21372         '&lt;span class="{cls}"&gt;{name:trim} {value:ellipsis(10)}&lt;/span&gt;',
21373     '&lt;/div&gt;',
21374 ]);
21375 t.{@link #compile}();
21376 t.{@link #append}('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
21377    </code></pre>
21378  * </ul></div></li>
21379  * <li><b>multiple arguments</b> : String, Object, Array, ...
21380  * <div class="sub-desc">
21381  * Multiple arguments will be combined with <code>join('')</code>.
21382  * <pre><code>
21383 var t = new Ext.Template(
21384     '&lt;div name="{id}"&gt;',
21385         '&lt;span class="{cls}"&gt;{name} {value}&lt;/span&gt;',
21386     '&lt;/div&gt;',
21387     // a configuration object:
21388     {
21389         compiled: true,      // {@link #compile} immediately
21390     }
21391 );
21392    </code></pre>
21393  * <p><b>Notes</b>:</p>
21394  * <div class="mdetail-params"><ul>
21395  * <li>For a list of available format functions, see {@link Ext.util.Format}.</li>
21396  * <li><code>disableFormats</code> reduces <code>{@link #apply}</code> time
21397  * when no formatting is required.</li>
21398  * </ul></div>
21399  * </div></li>
21400  * </ul></div>
21401  * @param {Mixed} config
21402  */
21403
21404 Ext.define('Ext.Template', {
21405
21406     /* Begin Definitions */
21407
21408     requires: ['Ext.core.DomHelper', 'Ext.util.Format'],
21409
21410     statics: {
21411         /**
21412          * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
21413          * @param {String/HTMLElement} el A DOM element or its id
21414          * @param {Object} config A configuration object
21415          * @return {Ext.Template} The created template
21416          * @static
21417          */
21418         from: function(el, config) {
21419             el = Ext.getDom(el);
21420             return new this(el.value || el.innerHTML, config || '');
21421         }
21422     },
21423
21424     /* End Definitions */
21425
21426     constructor: function(html) {
21427         var me = this,
21428             args = arguments,
21429             buffer = [],
21430             i = 0,
21431             length = args.length,
21432             value;
21433
21434         me.initialConfig = {};
21435
21436         if (length > 1) {
21437             for (; i < length; i++) {
21438                 value = args[i];
21439                 if (typeof value == 'object') {
21440                     Ext.apply(me.initialConfig, value);
21441                     Ext.apply(me, value);
21442                 } else {
21443                     buffer.push(value);
21444                 }
21445             }
21446             html = buffer.join('');
21447         } else {
21448             if (Ext.isArray(html)) {
21449                 buffer.push(html.join(''));
21450             } else {
21451                 buffer.push(html);
21452             }
21453         }
21454
21455         // @private
21456         me.html = buffer.join('');
21457
21458         if (me.compiled) {
21459             me.compile();
21460         }
21461     },
21462     isTemplate: true,
21463     /**
21464      * @cfg {Boolean} disableFormats true to disable format functions in the template. If the template doesn't contain format functions, setting
21465      * disableFormats to true will reduce apply time (defaults to false)
21466      */
21467     disableFormats: false,
21468
21469     re: /\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
21470     /**
21471      * Returns an HTML fragment of this template with the specified values applied.
21472      * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
21473      * @return {String} The HTML fragment
21474      * @hide repeat doc
21475      */
21476     applyTemplate: function(values) {
21477         var me = this,
21478             useFormat = me.disableFormats !== true,
21479             fm = Ext.util.Format,
21480             tpl = me;
21481
21482         if (me.compiled) {
21483             return me.compiled(values);
21484         }
21485         function fn(m, name, format, args) {
21486             if (format && useFormat) {
21487                 if (args) {
21488                     args = [values[name]].concat(Ext.functionFactory('return ['+ args +'];')());
21489                 } else {
21490                     args = [values[name]];
21491                 }
21492                 if (format.substr(0, 5) == "this.") {
21493                     return tpl[format.substr(5)].apply(tpl, args);
21494                 }
21495                 else {
21496                     return fm[format].apply(fm, args);
21497                 }
21498             }
21499             else {
21500                 return values[name] !== undefined ? values[name] : "";
21501             }
21502         }
21503         return me.html.replace(me.re, fn);
21504     },
21505
21506     /**
21507      * Sets the HTML used as the template and optionally compiles it.
21508      * @param {String} html
21509      * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
21510      * @return {Ext.Template} this
21511      */
21512     set: function(html, compile) {
21513         var me = this;
21514         me.html = html;
21515         me.compiled = null;
21516         return compile ? me.compile() : me;
21517     },
21518
21519     compileARe: /\\/g,
21520     compileBRe: /(\r\n|\n)/g,
21521     compileCRe: /'/g,
21522     /**
21523      * Compiles the template into an internal function, eliminating the RegEx overhead.
21524      * @return {Ext.Template} this
21525      * @hide repeat doc
21526      */
21527     compile: function() {
21528         var me = this,
21529             fm = Ext.util.Format,
21530             useFormat = me.disableFormats !== true,
21531             body, bodyReturn;
21532
21533         function fn(m, name, format, args) {
21534             if (format && useFormat) {
21535                 args = args ? ',' + args: "";
21536                 if (format.substr(0, 5) != "this.") {
21537                     format = "fm." + format + '(';
21538                 }
21539                 else {
21540                     format = 'this.' + format.substr(5) + '(';
21541                 }
21542             }
21543             else {
21544                 args = '';
21545                 format = "(values['" + name + "'] == undefined ? '' : ";
21546             }
21547             return "'," + format + "values['" + name + "']" + args + ") ,'";
21548         }
21549
21550         bodyReturn = me.html.replace(me.compileARe, '\\\\').replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn);
21551         body = "this.compiled = function(values){ return ['" + bodyReturn + "'].join('');};";
21552         eval(body);
21553         return me;
21554     },
21555
21556     /**
21557      * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
21558      * @param {Mixed} el The context element
21559      * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
21560      * @param {Boolean} returnElement (optional) true to return a Ext.core.Element (defaults to undefined)
21561      * @return {HTMLElement/Ext.core.Element} The new node or Element
21562      */
21563     insertFirst: function(el, values, returnElement) {
21564         return this.doInsert('afterBegin', el, values, returnElement);
21565     },
21566
21567     /**
21568      * Applies the supplied values to the template and inserts the new node(s) before el.
21569      * @param {Mixed} el The context element
21570      * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
21571      * @param {Boolean} returnElement (optional) true to return a Ext.core.Element (defaults to undefined)
21572      * @return {HTMLElement/Ext.core.Element} The new node or Element
21573      */
21574     insertBefore: function(el, values, returnElement) {
21575         return this.doInsert('beforeBegin', el, values, returnElement);
21576     },
21577
21578     /**
21579      * Applies the supplied values to the template and inserts the new node(s) after el.
21580      * @param {Mixed} el The context element
21581      * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
21582      * @param {Boolean} returnElement (optional) true to return a Ext.core.Element (defaults to undefined)
21583      * @return {HTMLElement/Ext.core.Element} The new node or Element
21584      */
21585     insertAfter: function(el, values, returnElement) {
21586         return this.doInsert('afterEnd', el, values, returnElement);
21587     },
21588
21589     /**
21590      * Applies the supplied <code>values</code> to the template and appends
21591      * the new node(s) to the specified <code>el</code>.
21592      * <p>For example usage {@link #Template see the constructor}.</p>
21593      * @param {Mixed} el The context element
21594      * @param {Object/Array} values
21595      * The template values. Can be an array if the params are numeric (i.e. <code>{0}</code>)
21596      * or an object (i.e. <code>{foo: 'bar'}</code>).
21597      * @param {Boolean} returnElement (optional) true to return an Ext.core.Element (defaults to undefined)
21598      * @return {HTMLElement/Ext.core.Element} The new node or Element
21599      */
21600     append: function(el, values, returnElement) {
21601         return this.doInsert('beforeEnd', el, values, returnElement);
21602     },
21603
21604     doInsert: function(where, el, values, returnEl) {
21605         el = Ext.getDom(el);
21606         var newNode = Ext.core.DomHelper.insertHtml(where, el, this.applyTemplate(values));
21607         return returnEl ? Ext.get(newNode, true) : newNode;
21608     },
21609
21610     /**
21611      * Applies the supplied values to the template and overwrites the content of el with the new node(s).
21612      * @param {Mixed} el The context element
21613      * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
21614      * @param {Boolean} returnElement (optional) true to return a Ext.core.Element (defaults to undefined)
21615      * @return {HTMLElement/Ext.core.Element} The new node or Element
21616      */
21617     overwrite: function(el, values, returnElement) {
21618         el = Ext.getDom(el);
21619         el.innerHTML = this.applyTemplate(values);
21620         return returnElement ? Ext.get(el.firstChild, true) : el.firstChild;
21621     }
21622 }, function() {
21623
21624     /**
21625      * Alias for {@link #applyTemplate}
21626      * Returns an HTML fragment of this template with the specified <code>values</code> applied.
21627      * @param {Object/Array} values
21628      * The template values. Can be an array if the params are numeric (i.e. <code>{0}</code>)
21629      * or an object (i.e. <code>{foo: 'bar'}</code>).
21630      * @return {String} The HTML fragment
21631      * @member Ext.Template
21632      * @method apply
21633      */
21634     this.createAlias('apply', 'applyTemplate');
21635 });
21636
21637 /**
21638  * @class Ext.ComponentQuery
21639  * @extends Object
21640  *
21641  * Provides searching of Components within Ext.ComponentManager (globally) or a specific
21642  * Ext.container.Container on the document with a similar syntax to a CSS selector.
21643  *
21644  * Components can be retrieved by using their {@link Ext.Component xtype} with an optional . prefix
21645 <ul>
21646     <li>component or .component</li>
21647     <li>gridpanel or .gridpanel</li>
21648 </ul>
21649  *
21650  * An itemId or id must be prefixed with a #
21651 <ul>
21652     <li>#myContainer</li>
21653 </ul>
21654  *
21655  *
21656  * Attributes must be wrapped in brackets
21657 <ul>
21658     <li>component[autoScroll]</li>
21659     <li>panel[title="Test"]</li>
21660 </ul>
21661  *
21662  * Member expressions from candidate Components may be tested. If the expression returns a <i>truthy</i> value,
21663  * the candidate Component will be included in the query:<pre><code>
21664 var disabledFields = myFormPanel.query("{isDisabled()}");
21665 </code></pre>
21666  *
21667  * Pseudo classes may be used to filter results in the same way as in {@link Ext.DomQuery DomQuery}:<code><pre>
21668 // Function receives array and returns a filtered array.
21669 Ext.ComponentQuery.pseudos.invalid = function(items) {
21670     var i = 0, l = items.length, c, result = [];
21671     for (; i < l; i++) {
21672         if (!(c = items[i]).isValid()) {
21673             result.push(c);
21674         }
21675     }
21676     return result;
21677 };
21678
21679 var invalidFields = myFormPanel.query('field:invalid');
21680 if (invalidFields.length) {
21681     invalidFields[0].getEl().scrollIntoView(myFormPanel.body);
21682     for (var i = 0, l = invalidFields.length; i < l; i++) {
21683         invalidFields[i].getEl().frame("red");
21684     }
21685 }
21686 </pre></code>
21687  * <p>
21688  * Default pseudos include:<br />
21689  * - not
21690  * </p>
21691  *
21692  * Queries return an array of components.
21693  * Here are some example queries.
21694 <pre><code>
21695     // retrieve all Ext.Panels in the document by xtype
21696     var panelsArray = Ext.ComponentQuery.query('panel');
21697
21698     // retrieve all Ext.Panels within the container with an id myCt
21699     var panelsWithinmyCt = Ext.ComponentQuery.query('#myCt panel');
21700
21701     // retrieve all direct children which are Ext.Panels within myCt
21702     var directChildPanel = Ext.ComponentQuery.query('#myCt > panel');
21703
21704     // retrieve all gridpanels and listviews
21705     var gridsAndLists = Ext.ComponentQuery.query('gridpanel, listview');
21706 </code></pre>
21707
21708 For easy access to queries based from a particular Container see the {@link Ext.container.Container#query},
21709 {@link Ext.container.Container#down} and {@link Ext.container.Container#child} methods. Also see
21710 {@link Ext.Component#up}.
21711  * @singleton
21712  */
21713 Ext.define('Ext.ComponentQuery', {
21714     singleton: true,
21715     uses: ['Ext.ComponentManager']
21716 }, function() {
21717
21718     var cq = this,
21719
21720         // A function source code pattern with a placeholder which accepts an expression which yields a truth value when applied
21721         // as a member on each item in the passed array.
21722         filterFnPattern = [
21723             'var r = [],',
21724                 'i = 0,',
21725                 'it = items,',
21726                 'l = it.length,',
21727                 'c;',
21728             'for (; i < l; i++) {',
21729                 'c = it[i];',
21730                 'if (c.{0}) {',
21731                    'r.push(c);',
21732                 '}',
21733             '}',
21734             'return r;'
21735         ].join(''),
21736
21737         filterItems = function(items, operation) {
21738             // Argument list for the operation is [ itemsArray, operationArg1, operationArg2...]
21739             // The operation's method loops over each item in the candidate array and
21740             // returns an array of items which match its criteria
21741             return operation.method.apply(this, [ items ].concat(operation.args));
21742         },
21743
21744         getItems = function(items, mode) {
21745             var result = [],
21746                 i = 0,
21747                 length = items.length,
21748                 candidate,
21749                 deep = mode !== '>';
21750                 
21751             for (; i < length; i++) {
21752                 candidate = items[i];
21753                 if (candidate.getRefItems) {
21754                     result = result.concat(candidate.getRefItems(deep));
21755                 }
21756             }
21757             return result;
21758         },
21759
21760         getAncestors = function(items) {
21761             var result = [],
21762                 i = 0,
21763                 length = items.length,
21764                 candidate;
21765             for (; i < length; i++) {
21766                 candidate = items[i];
21767                 while (!!(candidate = (candidate.ownerCt || candidate.floatParent))) {
21768                     result.push(candidate);
21769                 }
21770             }
21771             return result;
21772         },
21773
21774         // Filters the passed candidate array and returns only items which match the passed xtype
21775         filterByXType = function(items, xtype, shallow) {
21776             if (xtype === '*') {
21777                 return items.slice();
21778             }
21779             else {
21780                 var result = [],
21781                     i = 0,
21782                     length = items.length,
21783                     candidate;
21784                 for (; i < length; i++) {
21785                     candidate = items[i];
21786                     if (candidate.isXType(xtype, shallow)) {
21787                         result.push(candidate);
21788                     }
21789                 }
21790                 return result;
21791             }
21792         },
21793
21794         // Filters the passed candidate array and returns only items which have the passed className
21795         filterByClassName = function(items, className) {
21796             var EA = Ext.Array,
21797                 result = [],
21798                 i = 0,
21799                 length = items.length,
21800                 candidate;
21801             for (; i < length; i++) {
21802                 candidate = items[i];
21803                 if (candidate.el ? candidate.el.hasCls(className) : EA.contains(candidate.initCls(), className)) {
21804                     result.push(candidate);
21805                 }
21806             }
21807             return result;
21808         },
21809
21810         // Filters the passed candidate array and returns only items which have the specified property match
21811         filterByAttribute = function(items, property, operator, value) {
21812             var result = [],
21813                 i = 0,
21814                 length = items.length,
21815                 candidate;
21816             for (; i < length; i++) {
21817                 candidate = items[i];
21818                 if (!value ? !!candidate[property] : (String(candidate[property]) === value)) {
21819                     result.push(candidate);
21820                 }
21821             }
21822             return result;
21823         },
21824
21825         // Filters the passed candidate array and returns only items which have the specified itemId or id
21826         filterById = function(items, id) {
21827             var result = [],
21828                 i = 0,
21829                 length = items.length,
21830                 candidate;
21831             for (; i < length; i++) {
21832                 candidate = items[i];
21833                 if (candidate.getItemId() === id) {
21834                     result.push(candidate);
21835                 }
21836             }
21837             return result;
21838         },
21839
21840         // Filters the passed candidate array and returns only items which the named pseudo class matcher filters in
21841         filterByPseudo = function(items, name, value) {
21842             return cq.pseudos[name](items, value);
21843         },
21844
21845         // Determines leading mode
21846         // > for direct child, and ^ to switch to ownerCt axis
21847         modeRe = /^(\s?([>\^])\s?|\s|$)/,
21848
21849         // Matches a token with possibly (true|false) appended for the "shallow" parameter
21850         tokenRe = /^(#)?([\w\-]+|\*)(?:\((true|false)\))?/,
21851
21852         matchers = [{
21853             // Checks for .xtype with possibly (true|false) appended for the "shallow" parameter
21854             re: /^\.([\w\-]+)(?:\((true|false)\))?/,
21855             method: filterByXType
21856         },{
21857             // checks for [attribute=value]
21858             re: /^(?:[\[](?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]])/,
21859             method: filterByAttribute
21860         }, {
21861             // checks for #cmpItemId
21862             re: /^#([\w\-]+)/,
21863             method: filterById
21864         }, {
21865             // checks for :<pseudo_class>(<selector>)
21866             re: /^\:([\w\-]+)(?:\(((?:\{[^\}]+\})|(?:(?!\{)[^\s>\/]*?(?!\})))\))?/,
21867             method: filterByPseudo
21868         }, {
21869             // checks for {<member_expression>}
21870             re: /^(?:\{([^\}]+)\})/,
21871             method: filterFnPattern
21872         }];
21873
21874     /**
21875      * @class Ext.ComponentQuery.Query
21876      * @extends Object
21877      * @private
21878      */
21879     cq.Query = Ext.extend(Object, {
21880         constructor: function(cfg) {
21881             cfg = cfg || {};
21882             Ext.apply(this, cfg);
21883         },
21884
21885         /**
21886          * @private
21887          * Executes this Query upon the selected root.
21888          * The root provides the initial source of candidate Component matches which are progressively
21889          * filtered by iterating through this Query's operations cache.
21890          * If no root is provided, all registered Components are searched via the ComponentManager.
21891          * root may be a Container who's descendant Components are filtered
21892          * root may be a Component with an implementation of getRefItems which provides some nested Components such as the
21893          * docked items within a Panel.
21894          * root may be an array of candidate Components to filter using this Query.
21895          */
21896         execute : function(root) {
21897             var operations = this.operations,
21898                 i = 0,
21899                 length = operations.length,
21900                 operation,
21901                 workingItems;
21902
21903             // no root, use all Components in the document
21904             if (!root) {
21905                 workingItems = Ext.ComponentManager.all.getArray();
21906             }
21907             // Root is a candidate Array
21908             else if (Ext.isArray(root)) {
21909                 workingItems = root;
21910             }
21911
21912             // We are going to loop over our operations and take care of them
21913             // one by one.
21914             for (; i < length; i++) {
21915                 operation = operations[i];
21916
21917                 // The mode operation requires some custom handling.
21918                 // All other operations essentially filter down our current
21919                 // working items, while mode replaces our current working
21920                 // items by getting children from each one of our current
21921                 // working items. The type of mode determines the type of
21922                 // children we get. (e.g. > only gets direct children)
21923                 if (operation.mode === '^') {
21924                     workingItems = getAncestors(workingItems || [root]);
21925                 }
21926                 else if (operation.mode) {
21927                     workingItems = getItems(workingItems || [root], operation.mode);
21928                 }
21929                 else {
21930                     workingItems = filterItems(workingItems || getItems([root]), operation);
21931                 }
21932
21933                 // If this is the last operation, it means our current working
21934                 // items are the final matched items. Thus return them!
21935                 if (i === length -1) {
21936                     return workingItems;
21937                 }
21938             }
21939             return [];
21940         },
21941
21942         is: function(component) {
21943             var operations = this.operations,
21944                 components = Ext.isArray(component) ? component : [component],
21945                 originalLength = components.length,
21946                 lastOperation = operations[operations.length-1],
21947                 ln, i;
21948
21949             components = filterItems(components, lastOperation);
21950             if (components.length === originalLength) {
21951                 if (operations.length > 1) {
21952                     for (i = 0, ln = components.length; i < ln; i++) {
21953                         if (Ext.Array.indexOf(this.execute(), components[i]) === -1) {
21954                             return false;
21955                         }
21956                     }
21957                 }
21958                 return true;
21959             }
21960             return false;
21961         }
21962     });
21963
21964     Ext.apply(this, {
21965
21966         // private cache of selectors and matching ComponentQuery.Query objects
21967         cache: {},
21968
21969         // private cache of pseudo class filter functions
21970         pseudos: {
21971             not: function(components, selector){
21972                 var CQ = Ext.ComponentQuery,
21973                     i = 0,
21974                     length = components.length,
21975                     results = [],
21976                     index = -1,
21977                     component;
21978                 
21979                 for(; i < length; ++i) {
21980                     component = components[i];
21981                     if (!CQ.is(component, selector)) {
21982                         results[++index] = component;
21983                     }
21984                 }
21985                 return results;
21986             }
21987         },
21988
21989         /**
21990          * <p>Returns an array of matched Components from within the passed root object.</p>
21991          * <p>This method filters returned Components in a similar way to how CSS selector based DOM
21992          * queries work using a textual selector string.</p>
21993          * <p>See class summary for details.</p>
21994          * @param selector The selector string to filter returned Components
21995          * @param root <p>The Container within which to perform the query. If omitted, all Components
21996          * within the document are included in the search.</p>
21997          * <p>This parameter may also be an array of Components to filter according to the selector.</p>
21998          * @returns {Array} The matched Components.
21999          * @member Ext.ComponentQuery
22000          * @method query
22001          */
22002         query: function(selector, root) {
22003             var selectors = selector.split(','),
22004                 length = selectors.length,
22005                 i = 0,
22006                 results = [],
22007                 noDupResults = [], 
22008                 dupMatcher = {}, 
22009                 query, resultsLn, cmp;
22010
22011             for (; i < length; i++) {
22012                 selector = Ext.String.trim(selectors[i]);
22013                 query = this.cache[selector];
22014                 if (!query) {
22015                     this.cache[selector] = query = this.parse(selector);
22016                 }
22017                 results = results.concat(query.execute(root));
22018             }
22019
22020             // multiple selectors, potential to find duplicates
22021             // lets filter them out.
22022             if (length > 1) {
22023                 resultsLn = results.length;
22024                 for (i = 0; i < resultsLn; i++) {
22025                     cmp = results[i];
22026                     if (!dupMatcher[cmp.id]) {
22027                         noDupResults.push(cmp);
22028                         dupMatcher[cmp.id] = true;
22029                     }
22030                 }
22031                 results = noDupResults;
22032             }
22033             return results;
22034         },
22035
22036         /**
22037          * Tests whether the passed Component matches the selector string.
22038          * @param component The Component to test
22039          * @param selector The selector string to test against.
22040          * @return {Boolean} True if the Component matches the selector.
22041          * @member Ext.ComponentQuery
22042          * @method query
22043          */
22044         is: function(component, selector) {
22045             if (!selector) {
22046                 return true;
22047             }
22048             var query = this.cache[selector];
22049             if (!query) {
22050                 this.cache[selector] = query = this.parse(selector);
22051             }
22052             return query.is(component);
22053         },
22054
22055         parse: function(selector) {
22056             var operations = [],
22057                 length = matchers.length,
22058                 lastSelector,
22059                 tokenMatch,
22060                 matchedChar,
22061                 modeMatch,
22062                 selectorMatch,
22063                 i, matcher, method;
22064
22065             // We are going to parse the beginning of the selector over and
22066             // over again, slicing off the selector any portions we converted into an
22067             // operation, until it is an empty string.
22068             while (selector && lastSelector !== selector) {
22069                 lastSelector = selector;
22070
22071                 // First we check if we are dealing with a token like #, * or an xtype
22072                 tokenMatch = selector.match(tokenRe);
22073
22074                 if (tokenMatch) {
22075                     matchedChar = tokenMatch[1];
22076
22077                     // If the token is prefixed with a # we push a filterById operation to our stack
22078                     if (matchedChar === '#') {
22079                         operations.push({
22080                             method: filterById,
22081                             args: [Ext.String.trim(tokenMatch[2])]
22082                         });
22083                     }
22084                     // If the token is prefixed with a . we push a filterByClassName operation to our stack
22085                     // FIXME: Not enabled yet. just needs \. adding to the tokenRe prefix
22086                     else if (matchedChar === '.') {
22087                         operations.push({
22088                             method: filterByClassName,
22089                             args: [Ext.String.trim(tokenMatch[2])]
22090                         });
22091                     }
22092                     // If the token is a * or an xtype string, we push a filterByXType
22093                     // operation to the stack.
22094                     else {
22095                         operations.push({
22096                             method: filterByXType,
22097                             args: [Ext.String.trim(tokenMatch[2]), Boolean(tokenMatch[3])]
22098                         });
22099                     }
22100
22101                     // Now we slice of the part we just converted into an operation
22102                     selector = selector.replace(tokenMatch[0], '');
22103                 }
22104
22105                 // If the next part of the query is not a space or > or ^, it means we
22106                 // are going to check for more things that our current selection
22107                 // has to comply to.
22108                 while (!(modeMatch = selector.match(modeRe))) {
22109                     // Lets loop over each type of matcher and execute it
22110                     // on our current selector.
22111                     for (i = 0; selector && i < length; i++) {
22112                         matcher = matchers[i];
22113                         selectorMatch = selector.match(matcher.re);
22114                         method = matcher.method;
22115
22116                         // If we have a match, add an operation with the method
22117                         // associated with this matcher, and pass the regular
22118                         // expression matches are arguments to the operation.
22119                         if (selectorMatch) {
22120                             operations.push({
22121                                 method: Ext.isString(matcher.method)
22122                                     // Turn a string method into a function by formatting the string with our selector matche expression
22123                                     // A new method is created for different match expressions, eg {id=='textfield-1024'}
22124                                     // Every expression may be different in different selectors.
22125                                     ? Ext.functionFactory('items', Ext.String.format.apply(Ext.String, [method].concat(selectorMatch.slice(1))))
22126                                     : matcher.method,
22127                                 args: selectorMatch.slice(1)
22128                             });
22129                             selector = selector.replace(selectorMatch[0], '');
22130                             break; // Break on match
22131                         }
22132                         // Exhausted all matches: It's an error
22133                         if (i === (length - 1)) {
22134                             Ext.Error.raise('Invalid ComponentQuery selector: "' + arguments[0] + '"');
22135                         }
22136                     }
22137                 }
22138
22139                 // Now we are going to check for a mode change. This means a space
22140                 // or a > to determine if we are going to select all the children
22141                 // of the currently matched items, or a ^ if we are going to use the
22142                 // ownerCt axis as the candidate source.
22143                 if (modeMatch[1]) { // Assignment, and test for truthiness!
22144                     operations.push({
22145                         mode: modeMatch[2]||modeMatch[1]
22146                     });
22147                     selector = selector.replace(modeMatch[0], '');
22148                 }
22149             }
22150
22151             //  Now that we have all our operations in an array, we are going
22152             // to create a new Query using these operations.
22153             return new cq.Query({
22154                 operations: operations
22155             });
22156         }
22157     });
22158 });
22159 /**
22160  * @class Ext.util.Filter
22161  * @extends Object
22162  * <p>Represents a filter that can be applied to a {@link Ext.util.MixedCollection MixedCollection}. Can either simply
22163  * filter on a property/value pair or pass in a filter function with custom logic. Filters are always used in the context
22164  * of MixedCollections, though {@link Ext.data.Store Store}s frequently create them when filtering and searching on their
22165  * records. Example usage:</p>
22166 <pre><code>
22167 //set up a fictional MixedCollection containing a few people to filter on
22168 var allNames = new Ext.util.MixedCollection();
22169 allNames.addAll([
22170     {id: 1, name: 'Ed',    age: 25},
22171     {id: 2, name: 'Jamie', age: 37},
22172     {id: 3, name: 'Abe',   age: 32},
22173     {id: 4, name: 'Aaron', age: 26},
22174     {id: 5, name: 'David', age: 32}
22175 ]);
22176
22177 var ageFilter = new Ext.util.Filter({
22178     property: 'age',
22179     value   : 32
22180 });
22181
22182 var longNameFilter = new Ext.util.Filter({
22183     filterFn: function(item) {
22184         return item.name.length > 4;
22185     }
22186 });
22187
22188 //a new MixedCollection with the 3 names longer than 4 characters
22189 var longNames = allNames.filter(longNameFilter);
22190
22191 //a new MixedCollection with the 2 people of age 24:
22192 var youngFolk = allNames.filter(ageFilter);
22193 </code></pre>
22194  * @constructor
22195  * @param {Object} config Config object
22196  */
22197 Ext.define('Ext.util.Filter', {
22198
22199     /* Begin Definitions */
22200
22201     /* End Definitions */
22202     /**
22203      * @cfg {String} property The property to filter on. Required unless a {@link #filter} is passed
22204      */
22205     
22206     /**
22207      * @cfg {Function} filterFn A custom filter function which is passed each item in the {@link Ext.util.MixedCollection} 
22208      * in turn. Should return true to accept each item or false to reject it
22209      */
22210     
22211     /**
22212      * @cfg {Boolean} anyMatch True to allow any match - no regex start/end line anchors will be added. Defaults to false
22213      */
22214     anyMatch: false,
22215     
22216     /**
22217      * @cfg {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
22218      * Ignored if anyMatch is true.
22219      */
22220     exactMatch: false,
22221     
22222     /**
22223      * @cfg {Boolean} caseSensitive True to make the regex case sensitive (adds 'i' switch to regex). Defaults to false.
22224      */
22225     caseSensitive: false,
22226     
22227     /**
22228      * @cfg {String} root Optional root property. This is mostly useful when filtering a Store, in which case we set the
22229      * root to 'data' to make the filter pull the {@link #property} out of the data object of each item
22230      */
22231     
22232     constructor: function(config) {
22233         Ext.apply(this, config);
22234         
22235         //we're aliasing filter to filterFn mostly for API cleanliness reasons, despite the fact it dirties the code here.
22236         //Ext.util.Sorter takes a sorterFn property but allows .sort to be called - we do the same here
22237         this.filter = this.filter || this.filterFn;
22238         
22239         if (this.filter == undefined) {
22240             if (this.property == undefined || this.value == undefined) {
22241                 // Commented this out temporarily because it stops us using string ids in models. TODO: Remove this once
22242                 // Model has been updated to allow string ids
22243                 
22244                 // Ext.Error.raise("A Filter requires either a property or a filterFn to be set");
22245             } else {
22246                 this.filter = this.createFilterFn();
22247             }
22248             
22249             this.filterFn = this.filter;
22250         }
22251     },
22252     
22253     /**
22254      * @private
22255      * Creates a filter function for the configured property/value/anyMatch/caseSensitive options for this Filter
22256      */
22257     createFilterFn: function() {
22258         var me       = this,
22259             matcher  = me.createValueMatcher(),
22260             property = me.property;
22261         
22262         return function(item) {
22263             return matcher.test(me.getRoot.call(me, item)[property]);
22264         };
22265     },
22266     
22267     /**
22268      * @private
22269      * Returns the root property of the given item, based on the configured {@link #root} property
22270      * @param {Object} item The item
22271      * @return {Object} The root property of the object
22272      */
22273     getRoot: function(item) {
22274         return this.root == undefined ? item : item[this.root];
22275     },
22276     
22277     /**
22278      * @private
22279      * Returns a regular expression based on the given value and matching options
22280      */
22281     createValueMatcher : function() {
22282         var me            = this,
22283             value         = me.value,
22284             anyMatch      = me.anyMatch,
22285             exactMatch    = me.exactMatch,
22286             caseSensitive = me.caseSensitive,
22287             escapeRe      = Ext.String.escapeRegex;
22288         
22289         if (!value.exec) { // not a regex
22290             value = String(value);
22291
22292             if (anyMatch === true) {
22293                 value = escapeRe(value);
22294             } else {
22295                 value = '^' + escapeRe(value);
22296                 if (exactMatch === true) {
22297                     value += '$';
22298                 }
22299             }
22300             value = new RegExp(value, caseSensitive ? '' : 'i');
22301          }
22302          
22303          return value;
22304     }
22305 });
22306 /**
22307  * @class Ext.util.Sorter
22308  * @extends Object
22309  * Represents a single sorter that can be applied to a Store
22310  */
22311 Ext.define('Ext.util.Sorter', {
22312
22313     /**
22314      * @cfg {String} property The property to sort by. Required unless {@link #sorter} is provided
22315      */
22316     
22317     /**
22318      * @cfg {Function} sorterFn A specific sorter function to execute. Can be passed instead of {@link #property}
22319      */
22320     
22321     /**
22322      * @cfg {String} root Optional root property. This is mostly useful when sorting a Store, in which case we set the
22323      * root to 'data' to make the filter pull the {@link #property} out of the data object of each item
22324      */
22325     
22326     /**
22327      * @cfg {Function} transform A function that will be run on each value before
22328      * it is compared in the sorter. The function will receive a single argument,
22329      * the value.
22330      */
22331     
22332     /**
22333      * @cfg {String} direction The direction to sort by. Defaults to ASC
22334      */
22335     direction: "ASC",
22336     
22337     constructor: function(config) {
22338         var me = this;
22339         
22340         Ext.apply(me, config);
22341         
22342         if (me.property == undefined && me.sorterFn == undefined) {
22343             Ext.Error.raise("A Sorter requires either a property or a sorter function");
22344         }
22345         
22346         me.updateSortFunction();
22347     },
22348     
22349     /**
22350      * @private
22351      * Creates and returns a function which sorts an array by the given property and direction
22352      * @return {Function} A function which sorts by the property/direction combination provided
22353      */
22354     createSortFunction: function(sorterFn) {
22355         var me        = this,
22356             property  = me.property,
22357             direction = me.direction || "ASC",
22358             modifier  = direction.toUpperCase() == "DESC" ? -1 : 1;
22359         
22360         //create a comparison function. Takes 2 objects, returns 1 if object 1 is greater,
22361         //-1 if object 2 is greater or 0 if they are equal
22362         return function(o1, o2) {
22363             return modifier * sorterFn.call(me, o1, o2);
22364         };
22365     },
22366     
22367     /**
22368      * @private
22369      * Basic default sorter function that just compares the defined property of each object
22370      */
22371     defaultSorterFn: function(o1, o2) {
22372         var me = this,
22373             transform = me.transform,
22374             v1 = me.getRoot(o1)[me.property],
22375             v2 = me.getRoot(o2)[me.property];
22376             
22377         if (transform) {
22378             v1 = transform(v1);
22379             v2 = transform(v2);
22380         }
22381
22382         return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
22383     },
22384     
22385     /**
22386      * @private
22387      * Returns the root property of the given item, based on the configured {@link #root} property
22388      * @param {Object} item The item
22389      * @return {Object} The root property of the object
22390      */
22391     getRoot: function(item) {
22392         return this.root == undefined ? item : item[this.root];
22393     },
22394     
22395     // @TODO: Add docs for these three methods
22396     setDirection: function(direction) {
22397         var me = this;
22398         me.direction = direction;
22399         me.updateSortFunction();
22400     },
22401     
22402     toggle: function() {
22403         var me = this;
22404         me.direction = Ext.String.toggle(me.direction, "ASC", "DESC");
22405         me.updateSortFunction();
22406     },
22407     
22408     updateSortFunction: function() {
22409         var me = this;
22410         me.sort = me.createSortFunction(me.sorterFn || me.defaultSorterFn);
22411     }
22412 });
22413 /**
22414  * @class Ext.ElementLoader
22415  * A class used to load remote content to an Element. Sample usage:
22416  * <pre><code>
22417 Ext.get('el').load({
22418     url: 'myPage.php',
22419     scripts: true,
22420     params: {
22421         id: 1
22422     }
22423 });
22424  * </code></pre>
22425  * <p>
22426  * In general this class will not be instanced directly, rather the {@link Ext.core.Element#load} method
22427  * will be used.
22428  * </p>
22429  */
22430 Ext.define('Ext.ElementLoader', {
22431
22432     /* Begin Definitions */
22433
22434     mixins: {
22435         observable: 'Ext.util.Observable'
22436     },
22437
22438     uses: [
22439         'Ext.data.Connection',
22440         'Ext.Ajax'
22441     ],
22442     
22443     statics: {
22444         Renderer: {
22445             Html: function(loader, response, active){
22446                 loader.getTarget().update(response.responseText, active.scripts === true);
22447                 return true;
22448             }
22449         }     
22450     },
22451
22452     /* End Definitions */
22453
22454     /**
22455      * @cfg {String} url The url to retrieve the content from. Defaults to <tt>null</tt>.
22456      */
22457     url: null,
22458
22459     /**
22460      * @cfg {Object} params Any params to be attached to the Ajax request. These parameters will
22461      * be overridden by any params in the load options. Defaults to <tt>null</tt>.
22462      */
22463     params: null,
22464
22465     /**
22466      * @cfg {Object} baseParams Params that will be attached to every request. These parameters
22467      * will not be overridden by any params in the load options. Defaults to <tt>null</tt>.
22468      */
22469     baseParams: null,
22470
22471     /**
22472      * @cfg {Boolean/Object} autoLoad True to have the loader make a request as soon as it is created. Defaults to <tt>false</tt>.
22473      * This argument can also be a set of options that will be passed to {@link #load} is called.
22474      */
22475     autoLoad: false,
22476
22477     /**
22478      * @cfg {Mixed} target The target element for the loader. It can be the DOM element, the id or an Ext.Element.
22479      */
22480     target: null,
22481
22482     /**
22483      * @cfg {Mixed} loadMask True or a string to show when the element is loading.
22484      */
22485     loadMask: false,
22486
22487     /**
22488      * @cfg {Object} ajaxOptions Any additional options to be passed to the request, for example timeout or headers. Defaults to <tt>null</tt>.
22489      */
22490     ajaxOptions: null,
22491     
22492     /**
22493      * @cfg {Boolean} scripts True to parse any inline script tags in the response.
22494      */
22495     scripts: false,
22496
22497     /**
22498      * @cfg {Function} success A function to be called when a load request is successful.
22499      */
22500
22501     /**
22502      * @cfg {Function} failure A function to be called when a load request fails.
22503      */
22504
22505     /**
22506      * @cfg {Object} scope The scope to execute the {@link #success} and {@link #failure} functions in.
22507      */
22508     
22509     /**
22510      * @cfg {Function} renderer A custom function to render the content to the element. The passed parameters
22511      * are
22512      * <ul>
22513      * <li>The loader</li>
22514      * <li>The response</li>
22515      * <li>The active request</li>
22516      * </ul>
22517      */
22518
22519     isLoader: true,
22520
22521     constructor: function(config) {
22522         var me = this,
22523             autoLoad;
22524         
22525         config = config || {};
22526         Ext.apply(me, config);
22527         me.setTarget(me.target);
22528         me.addEvents(
22529             /**
22530              * @event beforeload
22531              * Fires before a load request is made to the server.
22532              * Returning false from an event listener can prevent the load
22533              * from occurring.
22534              * @param {Ext.ElementLoader} this
22535              * @param {Object} options The options passed to the request
22536              */
22537             'beforeload',
22538
22539             /**
22540              * @event exception
22541              * Fires after an unsuccessful load.
22542              * @param {Ext.ElementLoader} this
22543              * @param {Object} response The response from the server
22544              * @param {Object} options The options passed to the request
22545              */
22546             'exception',
22547
22548             /**
22549              * @event exception
22550              * Fires after a successful load.
22551              * @param {Ext.ElementLoader} this
22552              * @param {Object} response The response from the server
22553              * @param {Object} options The options passed to the request
22554              */
22555             'load'
22556         );
22557
22558         // don't pass config because we have already applied it.
22559         me.mixins.observable.constructor.call(me);
22560
22561         if (me.autoLoad) {
22562             autoLoad = me.autoLoad;
22563             if (autoLoad === true) {
22564                 autoLoad = {};
22565             }
22566             me.load(autoLoad);
22567         }
22568     },
22569
22570     /**
22571      * Set an {Ext.Element} as the target of this loader. Note that if the target is changed,
22572      * any active requests will be aborted.
22573      * @param {Mixed} target The element
22574      */
22575     setTarget: function(target){
22576         var me = this;
22577         target = Ext.get(target);
22578         if (me.target && me.target != target) {
22579             me.abort();
22580         }
22581         me.target = target;
22582     },
22583
22584     /**
22585      * Get the target of this loader.
22586      * @return {Ext.Component} target The target, null if none exists.
22587      */
22588     getTarget: function(){
22589         return this.target || null;
22590     },
22591
22592     /**
22593      * Aborts the active load request
22594      */
22595     abort: function(){
22596         var active = this.active;
22597         if (active !== undefined) {
22598             Ext.Ajax.abort(active.request);
22599             if (active.mask) {
22600                 this.removeMask();
22601             }
22602             delete this.active;
22603         }
22604     },
22605     
22606     /**
22607      * Remove the mask on the target
22608      * @private
22609      */
22610     removeMask: function(){
22611         this.target.unmask();
22612     },
22613     
22614     /**
22615      * Add the mask on the target
22616      * @private
22617      * @param {Mixed} mask The mask configuration
22618      */
22619     addMask: function(mask){
22620         this.target.mask(mask === true ? null : mask);
22621     },
22622
22623     /**
22624      * Load new data from the server.
22625      * @param {Object} options The options for the request. They can be any configuration option that can be specified for
22626      * the class, with the exception of the target option. Note that any options passed to the method will override any
22627      * class defaults.
22628      */
22629     load: function(options) {
22630         if (!this.target) {
22631             Ext.Error.raise('A valid target is required when loading content');
22632         }
22633
22634         options = Ext.apply({}, options);
22635
22636         var me = this,
22637             target = me.target,
22638             mask = Ext.isDefined(options.loadMask) ? options.loadMask : me.loadMask,
22639             params = Ext.apply({}, options.params),
22640             ajaxOptions = Ext.apply({}, options.ajaxOptions),
22641             callback = options.callback || me.callback,
22642             scope = options.scope || me.scope || me,
22643             request;
22644
22645         Ext.applyIf(ajaxOptions, me.ajaxOptions);
22646         Ext.applyIf(options, ajaxOptions);
22647
22648         Ext.applyIf(params, me.params);
22649         Ext.apply(params, me.baseParams);
22650
22651         Ext.applyIf(options, {
22652             url: me.url
22653         });
22654
22655         if (!options.url) {
22656             Ext.Error.raise('You must specify the URL from which content should be loaded');
22657         }
22658
22659         Ext.apply(options, {
22660             scope: me,
22661             params: params,
22662             callback: me.onComplete
22663         });
22664
22665         if (me.fireEvent('beforeload', me, options) === false) {
22666             return;
22667         }
22668
22669         if (mask) {
22670             me.addMask(mask);
22671         }
22672
22673         request = Ext.Ajax.request(options);
22674         me.active = {
22675             request: request,
22676             options: options,
22677             mask: mask,
22678             scope: scope,
22679             callback: callback,
22680             success: options.success || me.success,
22681             failure: options.failure || me.failure,
22682             renderer: options.renderer || me.renderer,
22683             scripts: Ext.isDefined(options.scripts) ? options.scripts : me.scripts
22684         };
22685         me.setOptions(me.active, options);
22686     },
22687     
22688     /**
22689      * Set any additional options on the active request
22690      * @private
22691      * @param {Object} active The active request
22692      * @param {Object} options The initial options
22693      */
22694     setOptions: Ext.emptyFn,
22695
22696     /**
22697      * Parse the response after the request completes
22698      * @private
22699      * @param {Object} options Ajax options
22700      * @param {Boolean} success Success status of the request
22701      * @param {Object} response The response object
22702      */
22703     onComplete: function(options, success, response) {
22704         var me = this,
22705             active = me.active,
22706             scope = active.scope,
22707             renderer = me.getRenderer(active.renderer);
22708
22709
22710         if (success) {
22711             success = renderer.call(me, me, response, active);
22712         }
22713
22714         if (success) {
22715             Ext.callback(active.success, scope, [me, response, options]);
22716             me.fireEvent('load', me, response, options);
22717         } else {
22718             Ext.callback(active.failure, scope, [me, response, options]);
22719             me.fireEvent('exception', me, response, options);
22720         }
22721         Ext.callback(active.callback, scope, [me, success, response, options]);
22722
22723         if (active.mask) {
22724             me.removeMask();
22725         }
22726
22727         delete me.active;
22728     },
22729
22730     /**
22731      * Gets the renderer to use
22732      * @private
22733      * @param {String/Function} renderer The renderer to use
22734      * @return {Function} A rendering function to use.
22735      */
22736     getRenderer: function(renderer){
22737         if (Ext.isFunction(renderer)) {
22738             return renderer;
22739         }
22740         return this.statics().Renderer.Html;
22741     },
22742     
22743     /**
22744      * Automatically refreshes the content over a specified period.
22745      * @param {Number} interval The interval to refresh in ms.
22746      * @param {Object} options (optional) The options to pass to the load method. See {@link #load}
22747      */
22748     startAutoRefresh: function(interval, options){
22749         var me = this;
22750         me.stopAutoRefresh();
22751         me.autoRefresh = setInterval(function(){
22752             me.load(options);
22753         }, interval);
22754     },
22755     
22756     /**
22757      * Clears any auto refresh. See {@link #startAutoRefresh}.
22758      */
22759     stopAutoRefresh: function(){
22760         clearInterval(this.autoRefresh);
22761         delete this.autoRefresh;
22762     },
22763     
22764     /**
22765      * Checks whether the loader is automatically refreshing. See {@link #startAutoRefresh}.
22766      * @return {Boolean} True if the loader is automatically refreshing
22767      */
22768     isAutoRefreshing: function(){
22769         return Ext.isDefined(this.autoRefresh);
22770     },
22771
22772     /**
22773      * Destroys the loader. Any active requests will be aborted.
22774      */
22775     destroy: function(){
22776         var me = this;
22777         me.stopAutoRefresh();
22778         delete me.target;
22779         me.abort();
22780         me.clearListeners();
22781     }
22782 });
22783
22784 /**
22785  * @class Ext.layout.Layout
22786  * @extends Object
22787  * @private
22788  * Base Layout class - extended by ComponentLayout and ContainerLayout
22789  */
22790
22791 Ext.define('Ext.layout.Layout', {
22792
22793     /* Begin Definitions */
22794
22795     /* End Definitions */
22796
22797     isLayout: true,
22798     initialized: false,
22799
22800     statics: {
22801         create: function(layout, defaultType) {
22802             var type;
22803             if (layout instanceof Ext.layout.Layout) {
22804                 return Ext.createByAlias('layout.' + layout);
22805             } else {
22806                 if (Ext.isObject(layout)) {
22807                     type = layout.type;
22808                 }
22809                 else {
22810                     type = layout || defaultType;
22811                     layout = {};
22812                 }
22813                 return Ext.createByAlias('layout.' + type, layout || {});
22814             }
22815         }
22816     },
22817
22818     constructor : function(config) {
22819         this.id = Ext.id(null, this.type + '-');
22820         Ext.apply(this, config);
22821     },
22822
22823     /**
22824      * @private
22825      */
22826     layout : function() {
22827         var me = this;
22828         me.layoutBusy = true;
22829         me.initLayout();
22830
22831         if (me.beforeLayout.apply(me, arguments) !== false) {
22832             me.layoutCancelled = false;
22833             me.onLayout.apply(me, arguments);
22834             me.childrenChanged = false;
22835             me.owner.needsLayout = false;
22836             me.layoutBusy = false;
22837             me.afterLayout.apply(me, arguments);
22838         }
22839         else {
22840             me.layoutCancelled = true;
22841         }
22842         me.layoutBusy = false;
22843         me.doOwnerCtLayouts();
22844     },
22845
22846     beforeLayout : function() {
22847         this.renderItems(this.getLayoutItems(), this.getRenderTarget());
22848         return true;
22849     },
22850
22851     /**
22852      * @private
22853      * Iterates over all passed items, ensuring they are rendered.  If the items are already rendered,
22854      * also determines if the items are in the proper place dom.
22855      */
22856     renderItems : function(items, target) {
22857         var ln = items.length,
22858             i = 0,
22859             item;
22860
22861         for (; i < ln; i++) {
22862             item = items[i];
22863             if (item && !item.rendered) {
22864                 this.renderItem(item, target, i);
22865             }
22866             else if (!this.isValidParent(item, target, i)) {
22867                 this.moveItem(item, target, i);
22868             }
22869         }
22870     },
22871
22872     // @private - Validates item is in the proper place in the dom.
22873     isValidParent : function(item, target, position) {
22874         var dom = item.el ? item.el.dom : Ext.getDom(item);
22875         if (dom && target && target.dom) {
22876             if (Ext.isNumber(position) && dom !== target.dom.childNodes[position]) {
22877                 return false;
22878             }
22879             return (dom.parentNode == (target.dom || target));
22880         }
22881         return false;
22882     },
22883
22884     /**
22885      * @private
22886      * Renders the given Component into the target Element.
22887      * @param {Ext.Component} item The Component to render
22888      * @param {Ext.core.Element} target The target Element
22889      * @param {Number} position The position within the target to render the item to
22890      */
22891     renderItem : function(item, target, position) {
22892         if (!item.rendered) {
22893             item.render(target, position);
22894             this.configureItem(item);
22895             this.childrenChanged = true;
22896         }
22897     },
22898
22899     /**
22900      * @private
22901      * Moved Component to the provided target instead.
22902      */
22903     moveItem : function(item, target, position) {
22904         // Make sure target is a dom element
22905         target = target.dom || target;
22906         if (typeof position == 'number') {
22907             position = target.childNodes[position];
22908         }
22909         target.insertBefore(item.el.dom, position || null);
22910         item.container = Ext.get(target);
22911         this.configureItem(item);
22912         this.childrenChanged = true;
22913     },
22914
22915     /**
22916      * @private
22917      * Adds the layout's targetCls if necessary and sets
22918      * initialized flag when complete.
22919      */
22920     initLayout : function() {
22921         if (!this.initialized && !Ext.isEmpty(this.targetCls)) {
22922             this.getTarget().addCls(this.targetCls);
22923         }
22924         this.initialized = true;
22925     },
22926
22927     // @private Sets the layout owner
22928     setOwner : function(owner) {
22929         this.owner = owner;
22930     },
22931
22932     // @private - Returns empty array
22933     getLayoutItems : function() {
22934         return [];
22935     },
22936
22937     /**
22938      * @private
22939      * Applies itemCls
22940      */
22941     configureItem: function(item) {
22942         var me = this,
22943             el = item.el,
22944             owner = me.owner;
22945             
22946         if (me.itemCls) {
22947             el.addCls(me.itemCls);
22948         }
22949         if (owner.itemCls) {
22950             el.addCls(owner.itemCls);
22951         }
22952     },
22953     
22954     // Placeholder empty functions for subclasses to extend
22955     onLayout : Ext.emptyFn,
22956     afterLayout : Ext.emptyFn,
22957     onRemove : Ext.emptyFn,
22958     onDestroy : Ext.emptyFn,
22959     doOwnerCtLayouts : Ext.emptyFn,
22960
22961     /**
22962      * @private
22963      * Removes itemCls
22964      */
22965     afterRemove : function(item) {
22966         var me = this,
22967             el = item.el,
22968             owner = me.owner;
22969             
22970         if (item.rendered) {
22971             if (me.itemCls) {
22972                 el.removeCls(me.itemCls);
22973             }
22974             if (owner.itemCls) {
22975                 el.removeCls(owner.itemCls);
22976             }
22977         }
22978     },
22979
22980     /*
22981      * Destroys this layout. This is a template method that is empty by default, but should be implemented
22982      * by subclasses that require explicit destruction to purge event handlers or remove DOM nodes.
22983      * @protected
22984      */
22985     destroy : function() {
22986         if (!Ext.isEmpty(this.targetCls)) {
22987             var target = this.getTarget();
22988             if (target) {
22989                 target.removeCls(this.targetCls);
22990             }
22991         }
22992         this.onDestroy();
22993     }
22994 });
22995 /**
22996  * @class Ext.layout.component.Component
22997  * @extends Ext.layout.Layout
22998  * @private
22999  * <p>This class is intended to be extended or created via the <tt><b>{@link Ext.Component#componentLayout layout}</b></tt>
23000  * configuration property.  See <tt><b>{@link Ext.Component#componentLayout}</b></tt> for additional details.</p>
23001  */
23002
23003 Ext.define('Ext.layout.component.Component', {
23004
23005     /* Begin Definitions */
23006
23007     extend: 'Ext.layout.Layout',
23008
23009     /* End Definitions */
23010
23011     type: 'component',
23012
23013     monitorChildren: true,
23014
23015     initLayout : function() {
23016         var me = this,
23017             owner = me.owner,
23018             ownerEl = owner.el;
23019
23020         if (!me.initialized) {
23021             if (owner.frameSize) {
23022                 me.frameSize = owner.frameSize;
23023             }
23024             else {
23025                 owner.frameSize = me.frameSize = {
23026                     top: 0,
23027                     left: 0,
23028                     bottom: 0,
23029                     right: 0
23030                 }; 
23031             }
23032         }
23033         me.callParent(arguments);
23034     },
23035
23036     beforeLayout : function(width, height, isSetSize, layoutOwner) {
23037         this.callParent(arguments);
23038
23039         var me = this,
23040             owner = me.owner,
23041             ownerCt = owner.ownerCt,
23042             layout = owner.layout,
23043             isVisible = owner.isVisible(true),
23044             ownerElChild = owner.el.child,
23045             layoutCollection;
23046
23047         /**
23048         * Do not layout calculatedSized components for fixedLayouts unless the ownerCt == layoutOwner
23049         * fixedLayouts means layouts which are never auto/auto in the sizing that comes from their ownerCt.
23050         * Currently 3 layouts MAY be auto/auto (Auto, Border, and Box)
23051         * The reason for not allowing component layouts is to stop component layouts from things such as Updater and
23052         * form Validation.
23053         */
23054         if (!isSetSize && !(Ext.isNumber(width) && Ext.isNumber(height)) && ownerCt && ownerCt.layout && ownerCt.layout.fixedLayout && ownerCt != layoutOwner) {
23055             me.doContainerLayout();
23056             return false;
23057         }
23058
23059         // If an ownerCt is hidden, add my reference onto the layoutOnShow stack.  Set the needsLayout flag.
23060         // If the owner itself is a directly hidden floater, set the needsLayout object on that for when it is shown.
23061         if (!isVisible && (owner.hiddenAncestor || owner.floating)) {
23062             if (owner.hiddenAncestor) {
23063                 layoutCollection = owner.hiddenAncestor.layoutOnShow;
23064                 layoutCollection.remove(owner);
23065                 layoutCollection.add(owner);
23066             }
23067             owner.needsLayout = {
23068                 width: width,
23069                 height: height,
23070                 isSetSize: false
23071             };
23072         }
23073
23074         if (isVisible && this.needsLayout(width, height)) {
23075             me.rawWidth = width;
23076             me.rawHeight = height;
23077             return owner.beforeComponentLayout(width, height, isSetSize, layoutOwner);
23078         }
23079         else {
23080             return false;
23081         }
23082     },
23083
23084     /**
23085     * Check if the new size is different from the current size and only
23086     * trigger a layout if it is necessary.
23087     * @param {Mixed} width The new width to set.
23088     * @param {Mixed} height The new height to set.
23089     */
23090     needsLayout : function(width, height) {
23091         this.lastComponentSize = this.lastComponentSize || {
23092             width: -Infinity,
23093             height: -Infinity
23094         };
23095         return (this.childrenChanged || this.lastComponentSize.width !== width || this.lastComponentSize.height !== height);
23096     },
23097
23098     /**
23099     * Set the size of any element supporting undefined, null, and values.
23100     * @param {Mixed} width The new width to set.
23101     * @param {Mixed} height The new height to set.
23102     */
23103     setElementSize: function(el, width, height) {
23104         if (width !== undefined && height !== undefined) {
23105             el.setSize(width, height);
23106         }
23107         else if (height !== undefined) {
23108             el.setHeight(height);
23109         }
23110         else if (width !== undefined) {
23111             el.setWidth(width);
23112         }
23113     },
23114
23115     /**
23116      * Returns the owner component's resize element.
23117      * @return {Ext.core.Element}
23118      */
23119      getTarget : function() {
23120          return this.owner.el;
23121      },
23122
23123     /**
23124      * <p>Returns the element into which rendering must take place. Defaults to the owner Component's encapsulating element.</p>
23125      * May be overridden in Component layout managers which implement an inner element.
23126      * @return {Ext.core.Element}
23127      */
23128     getRenderTarget : function() {
23129         return this.owner.el;
23130     },
23131
23132     /**
23133     * Set the size of the target element.
23134     * @param {Mixed} width The new width to set.
23135     * @param {Mixed} height The new height to set.
23136     */
23137     setTargetSize : function(width, height) {
23138         var me = this;
23139         me.setElementSize(me.owner.el, width, height);
23140
23141         if (me.owner.frameBody) {
23142             var targetInfo = me.getTargetInfo(),
23143                 padding = targetInfo.padding,
23144                 border = targetInfo.border,
23145                 frameSize = me.frameSize;
23146
23147             me.setElementSize(me.owner.frameBody,
23148                 Ext.isNumber(width) ? (width - frameSize.left - frameSize.right - padding.left - padding.right - border.left - border.right) : width,
23149                 Ext.isNumber(height) ? (height - frameSize.top - frameSize.bottom - padding.top - padding.bottom - border.top - border.bottom) : height
23150             );
23151         }
23152
23153         me.autoSized = {
23154             width: !Ext.isNumber(width),
23155             height: !Ext.isNumber(height)
23156         };
23157
23158         me.lastComponentSize = {
23159             width: width,
23160             height: height
23161         };
23162     },
23163
23164     getTargetInfo : function() {
23165         if (!this.targetInfo) {
23166             var target = this.getTarget(),
23167                 body = this.owner.getTargetEl();
23168
23169             this.targetInfo = {
23170                 padding: {
23171                     top: target.getPadding('t'),
23172                     right: target.getPadding('r'),
23173                     bottom: target.getPadding('b'),
23174                     left: target.getPadding('l')
23175                 },
23176                 border: {
23177                     top: target.getBorderWidth('t'),
23178                     right: target.getBorderWidth('r'),
23179                     bottom: target.getBorderWidth('b'),
23180                     left: target.getBorderWidth('l')
23181                 },
23182                 bodyMargin: {
23183                     top: body.getMargin('t'),
23184                     right: body.getMargin('r'),
23185                     bottom: body.getMargin('b'),
23186                     left: body.getMargin('l')
23187                 } 
23188             };
23189         }
23190         return this.targetInfo;
23191     },
23192
23193     // Start laying out UP the ownerCt's layout when flagged to do so.
23194     doOwnerCtLayouts: function() {
23195         var owner = this.owner,
23196             ownerCt = owner.ownerCt,
23197             ownerCtComponentLayout, ownerCtContainerLayout;
23198
23199         if (!ownerCt) {
23200             return;
23201         }
23202
23203         ownerCtComponentLayout = ownerCt.componentLayout;
23204         ownerCtContainerLayout = ownerCt.layout;
23205
23206         if (!owner.floating && ownerCtComponentLayout && ownerCtComponentLayout.monitorChildren && !ownerCtComponentLayout.layoutBusy) {
23207             if (!ownerCt.suspendLayout && ownerCtContainerLayout && !ownerCtContainerLayout.layoutBusy) {
23208                 // AutoContainer Layout and Dock with auto in some dimension
23209                 if (ownerCtContainerLayout.bindToOwnerCtComponent === true) {
23210                     ownerCt.doComponentLayout();
23211                 }
23212                 // Box Layouts
23213                 else if (ownerCtContainerLayout.bindToOwnerCtContainer === true) {
23214                     ownerCtContainerLayout.layout();
23215                 }
23216             }
23217         }
23218     },
23219
23220     doContainerLayout: function() {
23221         var me = this,
23222             owner = me.owner,
23223             ownerCt = owner.ownerCt,
23224             layout = owner.layout,
23225             ownerCtComponentLayout;
23226
23227         // Run the container layout if it exists (layout for child items)
23228         // **Unless automatic laying out is suspended, or the layout is currently running**
23229         if (!owner.suspendLayout && layout && layout.isLayout && !layout.layoutBusy) {
23230             layout.layout();
23231         }
23232
23233         // Tell the ownerCt that it's child has changed and can be re-layed by ignoring the lastComponentSize cache.
23234         if (ownerCt && ownerCt.componentLayout) {
23235             ownerCtComponentLayout = ownerCt.componentLayout;
23236             if (!owner.floating && ownerCtComponentLayout.monitorChildren && !ownerCtComponentLayout.layoutBusy) {
23237                 ownerCtComponentLayout.childrenChanged = true;
23238             }
23239         }
23240     },
23241
23242     afterLayout : function(width, height, isSetSize, layoutOwner) {
23243         this.doContainerLayout();
23244         this.owner.afterComponentLayout(width, height, isSetSize, layoutOwner);
23245     }
23246 });
23247
23248 /**
23249  * @class Ext.state.Manager
23250  * This is the global state manager. By default all components that are "state aware" check this class
23251  * for state information if you don't pass them a custom state provider. In order for this class
23252  * to be useful, it must be initialized with a provider when your application initializes. Example usage:
23253  <pre><code>
23254 // in your initialization function
23255 init : function(){
23256    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
23257    var win = new Window(...);
23258    win.restoreState();
23259 }
23260  </code></pre>
23261  * This class passes on calls from components to the underlying {@link Ext.state.Provider} so that
23262  * there is a common interface that can be used without needing to refer to a specific provider instance
23263  * in every component.
23264  * @singleton
23265  * @docauthor Evan Trimboli <evan@sencha.com>
23266  */
23267 Ext.define('Ext.state.Manager', {
23268     singleton: true,
23269     requires: ['Ext.state.Provider'],
23270     constructor: function() {
23271         this.provider = Ext.create('Ext.state.Provider');
23272     },
23273     
23274     
23275     /**
23276      * Configures the default state provider for your application
23277      * @param {Provider} stateProvider The state provider to set
23278      */
23279     setProvider : function(stateProvider){
23280         this.provider = stateProvider;
23281     },
23282
23283     /**
23284      * Returns the current value for a key
23285      * @param {String} name The key name
23286      * @param {Mixed} defaultValue The default value to return if the key lookup does not match
23287      * @return {Mixed} The state data
23288      */
23289     get : function(key, defaultValue){
23290         return this.provider.get(key, defaultValue);
23291     },
23292
23293     /**
23294      * Sets the value for a key
23295      * @param {String} name The key name
23296      * @param {Mixed} value The state data
23297      */
23298      set : function(key, value){
23299         this.provider.set(key, value);
23300     },
23301
23302     /**
23303      * Clears a value from the state
23304      * @param {String} name The key name
23305      */
23306     clear : function(key){
23307         this.provider.clear(key);
23308     },
23309
23310     /**
23311      * Gets the currently configured state provider
23312      * @return {Provider} The state provider
23313      */
23314     getProvider : function(){
23315         return this.provider;
23316     }
23317 });
23318 /**
23319  * @class Ext.state.Stateful
23320  * A mixin for being able to save the state of an object to an underlying 
23321  * {@link Ext.state.Provider}.
23322  */
23323 Ext.define('Ext.state.Stateful', {
23324     
23325     /* Begin Definitions */
23326    
23327    mixins: {
23328         observable: 'Ext.util.Observable'
23329     },
23330     
23331     requires: ['Ext.state.Manager'],
23332     
23333     /* End Definitions */
23334     
23335     /**
23336      * @cfg {Boolean} stateful
23337      * <p>A flag which causes the object to attempt to restore the state of
23338      * internal properties from a saved state on startup. The object must have
23339      * a <code>{@link #stateId}</code> for state to be managed. 
23340      * Auto-generated ids are not guaranteed to be stable across page loads and 
23341      * cannot be relied upon to save and restore the same state for a object.<p>
23342      * <p>For state saving to work, the state manager's provider must have been
23343      * set to an implementation of {@link Ext.state.Provider} which overrides the
23344      * {@link Ext.state.Provider#set set} and {@link Ext.state.Provider#get get}
23345      * methods to save and recall name/value pairs. A built-in implementation,
23346      * {@link Ext.state.CookieProvider} is available.</p>
23347      * <p>To set the state provider for the current page:</p>
23348      * <pre><code>
23349 Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
23350     expires: new Date(new Date().getTime()+(1000*60*60*24*7)), //7 days from now
23351 }));
23352      * </code></pre>
23353      * <p>A stateful object attempts to save state when one of the events
23354      * listed in the <code>{@link #stateEvents}</code> configuration fires.</p>
23355      * <p>To save state, a stateful object first serializes its state by
23356      * calling <b><code>{@link #getState}</code></b>. By default, this function does
23357      * nothing. The developer must provide an implementation which returns an
23358      * object hash which represents the restorable state of the object.</p>
23359      * <p>The value yielded by getState is passed to {@link Ext.state.Manager#set}
23360      * which uses the configured {@link Ext.state.Provider} to save the object
23361      * keyed by the <code>{@link stateId}</code></p>.
23362      * <p>During construction, a stateful object attempts to <i>restore</i>
23363      * its state by calling {@link Ext.state.Manager#get} passing the
23364      * <code>{@link #stateId}</code></p>
23365      * <p>The resulting object is passed to <b><code>{@link #applyState}</code></b>.
23366      * The default implementation of <code>{@link #applyState}</code> simply copies
23367      * properties into the object, but a developer may override this to support
23368      * more behaviour.</p>
23369      * <p>You can perform extra processing on state save and restore by attaching
23370      * handlers to the {@link #beforestaterestore}, {@link #staterestore},
23371      * {@link #beforestatesave} and {@link #statesave} events.</p>
23372      */
23373     stateful: true,
23374     
23375     /**
23376      * @cfg {String} stateId
23377      * The unique id for this object to use for state management purposes.
23378      * <p>See {@link #stateful} for an explanation of saving and restoring state.</p>
23379      */
23380     
23381     /**
23382      * @cfg {Array} stateEvents
23383      * <p>An array of events that, when fired, should trigger this object to
23384      * save its state (defaults to none). <code>stateEvents</code> may be any type
23385      * of event supported by this object, including browser or custom events
23386      * (e.g., <tt>['click', 'customerchange']</tt>).</p>
23387      * <p>See <code>{@link #stateful}</code> for an explanation of saving and
23388      * restoring object state.</p>
23389      */
23390     
23391     /**
23392      * @cfg {Number} saveBuffer A buffer to be applied if many state events are fired within
23393      * a short period. Defaults to 100.
23394      */
23395     saveDelay: 100,
23396     
23397     autoGenIdRe: /^((\w+-)|(ext-comp-))\d{4,}$/i,
23398     
23399     constructor: function(config) {
23400         var me = this;
23401         
23402         config = config || {};
23403         if (Ext.isDefined(config.stateful)) {
23404             me.stateful = config.stateful;
23405         }
23406         if (Ext.isDefined(config.saveDelay)) {
23407             me.saveDelay = config.saveDelay;
23408         }
23409         me.stateId = config.stateId;
23410         
23411         if (!me.stateEvents) {
23412             me.stateEvents = [];
23413         }
23414         if (config.stateEvents) {
23415             me.stateEvents.concat(config.stateEvents);
23416         }
23417         this.addEvents(
23418             /**
23419              * @event beforestaterestore
23420              * Fires before the state of the object is restored. Return false from an event handler to stop the restore.
23421              * @param {Ext.state.Stateful} this
23422              * @param {Object} state The hash of state values returned from the StateProvider. If this
23423              * event is not vetoed, then the state object is passed to <b><tt>applyState</tt></b>. By default,
23424              * that simply copies property values into this object. The method maybe overriden to
23425              * provide custom state restoration.
23426              */
23427             'beforestaterestore',
23428             
23429             /**
23430              * @event staterestore
23431              * Fires after the state of the object is restored.
23432              * @param {Ext.state.Stateful} this
23433              * @param {Object} state The hash of state values returned from the StateProvider. This is passed
23434              * to <b><tt>applyState</tt></b>. By default, that simply copies property values into this
23435              * object. The method maybe overriden to provide custom state restoration.
23436              */
23437             'staterestore',
23438             
23439             /**
23440              * @event beforestatesave
23441              * Fires before the state of the object is saved to the configured state provider. Return false to stop the save.
23442              * @param {Ext.state.Stateful} this
23443              * @param {Object} state The hash of state values. This is determined by calling
23444              * <b><tt>getState()</tt></b> on the object. This method must be provided by the
23445              * developer to return whetever representation of state is required, by default, Ext.state.Stateful
23446              * has a null implementation.
23447              */
23448             'beforestatesave',
23449             
23450             /**
23451              * @event statesave
23452              * Fires after the state of the object is saved to the configured state provider.
23453              * @param {Ext.state.Stateful} this
23454              * @param {Object} state The hash of state values. This is determined by calling
23455              * <b><tt>getState()</tt></b> on the object. This method must be provided by the
23456              * developer to return whetever representation of state is required, by default, Ext.state.Stateful
23457              * has a null implementation.
23458              */
23459             'statesave'
23460         );
23461         me.mixins.observable.constructor.call(me);
23462         if (me.stateful !== false) {
23463             me.initStateEvents();
23464             me.initState();
23465         }
23466     },
23467     
23468     /**
23469      * Initializes any state events for this object.
23470      * @private
23471      */
23472     initStateEvents: function() {
23473         this.addStateEvents(this.stateEvents);
23474     },
23475     
23476     /**
23477      * Add events that will trigger the state to be saved.
23478      * @param {String/Array} events The event name or an array of event names.
23479      */
23480     addStateEvents: function(events){
23481         if (!Ext.isArray(events)) {
23482             events = [events];
23483         }
23484         
23485         var me = this,
23486             i = 0,
23487             len = events.length;
23488             
23489         for (; i < len; ++i) {
23490             me.on(events[i], me.onStateChange, me);
23491         }
23492     },
23493     
23494     /**
23495      * This method is called when any of the {@link #stateEvents} are fired.
23496      * @private
23497      */
23498     onStateChange: function(){
23499         var me = this,
23500             delay = me.saveDelay;
23501         
23502         if (delay > 0) {
23503             if (!me.stateTask) {
23504                 me.stateTask = Ext.create('Ext.util.DelayedTask', me.saveState, me);
23505             }
23506             me.stateTask.delay(me.saveDelay);
23507         } else {
23508             me.saveState();
23509         }
23510     },
23511     
23512     /**
23513      * Saves the state of the object to the persistence store.
23514      * @private
23515      */
23516     saveState: function() {
23517         var me = this,
23518             id,
23519             state;
23520         
23521         if (me.stateful !== false) {
23522             id = me.getStateId();
23523             if (id) {
23524                 state = me.getState();
23525                 if (me.fireEvent('beforestatesave', me, state) !== false) {
23526                     Ext.state.Manager.set(id, state);
23527                     me.fireEvent('statesave', me, state);
23528                 }
23529             }
23530         }
23531     },
23532     
23533     /**
23534      * Gets the current state of the object. By default this function returns null,
23535      * it should be overridden in subclasses to implement methods for getting the state.
23536      * @return {Object} The current state
23537      */
23538     getState: function(){
23539         return null;    
23540     },
23541     
23542     /**
23543      * Applies the state to the object. This should be overridden in subclasses to do
23544      * more complex state operations. By default it applies the state properties onto
23545      * the current object.
23546      * @param {Object} state The state
23547      */
23548     applyState: function(state) {
23549         if (state) {
23550             Ext.apply(this, state);
23551         }
23552     },
23553     
23554     /**
23555      * Gets the state id for this object.
23556      * @return {String} The state id, null if not found.
23557      */
23558     getStateId: function() {
23559         var me = this,
23560             id = me.stateId;
23561         
23562         if (!id) {
23563             id = me.autoGenIdRe.test(String(me.id)) ? null : me.id;
23564         }
23565         return id;
23566     },
23567     
23568     /**
23569      * Initializes the state of the object upon construction.
23570      * @private
23571      */
23572     initState: function(){
23573         var me = this,
23574             id = me.getStateId(),
23575             state;
23576             
23577         if (me.stateful !== false) {
23578             if (id) {
23579                 state = Ext.state.Manager.get(id);
23580                 if (state) {
23581                     state = Ext.apply({}, state);
23582                     if (me.fireEvent('beforestaterestore', me, state) !== false) {
23583                         me.applyState(state);
23584                         me.fireEvent('staterestore', me, state);
23585                     }
23586                 }
23587             }
23588         }
23589     },
23590     
23591     /**
23592      * Destroys this stateful object.
23593      */
23594     destroy: function(){
23595         var task = this.stateTask;
23596         if (task) {
23597             task.cancel();
23598         }
23599         this.clearListeners();
23600         
23601     }
23602     
23603 });
23604
23605 /**
23606  * @class Ext.AbstractManager
23607  * @extends Object
23608  * @ignore
23609  * Base Manager class
23610  */
23611
23612 Ext.define('Ext.AbstractManager', {
23613
23614     /* Begin Definitions */
23615
23616     requires: ['Ext.util.HashMap'],
23617
23618     /* End Definitions */
23619
23620     typeName: 'type',
23621
23622     constructor: function(config) {
23623         Ext.apply(this, config || {});
23624
23625         /**
23626          * Contains all of the items currently managed
23627          * @property all
23628          * @type Ext.util.MixedCollection
23629          */
23630         this.all = Ext.create('Ext.util.HashMap');
23631
23632         this.types = {};
23633     },
23634
23635     /**
23636      * Returns an item by id.
23637      * For additional details see {@link Ext.util.HashMap#get}.
23638      * @param {String} id The id of the item
23639      * @return {Mixed} The item, <code>undefined</code> if not found.
23640      */
23641     get : function(id) {
23642         return this.all.get(id);
23643     },
23644
23645     /**
23646      * Registers an item to be managed
23647      * @param {Mixed} item The item to register
23648      */
23649     register: function(item) {
23650         this.all.add(item);
23651     },
23652
23653     /**
23654      * Unregisters an item by removing it from this manager
23655      * @param {Mixed} item The item to unregister
23656      */
23657     unregister: function(item) {
23658         this.all.remove(item);
23659     },
23660
23661     /**
23662      * <p>Registers a new item constructor, keyed by a type key.
23663      * @param {String} type The mnemonic string by which the class may be looked up.
23664      * @param {Constructor} cls The new instance class.
23665      */
23666     registerType : function(type, cls) {
23667         this.types[type] = cls;
23668         cls[this.typeName] = type;
23669     },
23670
23671     /**
23672      * Checks if an item type is registered.
23673      * @param {String} type The mnemonic string by which the class may be looked up
23674      * @return {Boolean} Whether the type is registered.
23675      */
23676     isRegistered : function(type){
23677         return this.types[type] !== undefined;
23678     },
23679
23680     /**
23681      * Creates and returns an instance of whatever this manager manages, based on the supplied type and config object
23682      * @param {Object} config The config object
23683      * @param {String} defaultType If no type is discovered in the config object, we fall back to this type
23684      * @return {Mixed} The instance of whatever this manager is managing
23685      */
23686     create: function(config, defaultType) {
23687         var type        = config[this.typeName] || config.type || defaultType,
23688             Constructor = this.types[type];
23689
23690         if (Constructor == undefined) {
23691             Ext.Error.raise("The '" + type + "' type has not been registered with this manager");
23692         }
23693
23694         return new Constructor(config);
23695     },
23696
23697     /**
23698      * Registers a function that will be called when an item with the specified id is added to the manager. This will happen on instantiation.
23699      * @param {String} id The item id
23700      * @param {Function} fn The callback function. Called with a single parameter, the item.
23701      * @param {Object} scope The scope (<code>this</code> reference) in which the callback is executed. Defaults to the item.
23702      */
23703     onAvailable : function(id, fn, scope){
23704         var all = this.all,
23705             item;
23706         
23707         if (all.containsKey(id)) {
23708             item = all.get(id);
23709             fn.call(scope || item, item);
23710         } else {
23711             all.on('add', function(map, key, item){
23712                 if (key == id) {
23713                     fn.call(scope || item, item);
23714                     all.un('add', fn, scope);
23715                 }
23716             });
23717         }
23718     },
23719     
23720     /**
23721      * Executes the specified function once for each item in the collection.
23722      * Returning false from the function will cease iteration.
23723      * 
23724      * The paramaters passed to the function are:
23725      * <div class="mdetail-params"><ul>
23726      * <li><b>key</b> : String<p class="sub-desc">The key of the item</p></li>
23727      * <li><b>value</b> : Number<p class="sub-desc">The value of the item</p></li>
23728      * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the collection</p></li>
23729      * </ul></div>
23730      * @param {Object} fn The function to execute.
23731      * @param {Object} scope The scope to execute in. Defaults to <tt>this</tt>.
23732      */
23733     each: function(fn, scope){
23734         this.all.each(fn, scope || this);    
23735     },
23736     
23737     /**
23738      * Gets the number of items in the collection.
23739      * @return {Number} The number of items in the collection.
23740      */
23741     getCount: function(){
23742         return this.all.getCount();
23743     }
23744 });
23745
23746 /**
23747  * @class Ext.PluginManager
23748  * @extends Ext.AbstractManager
23749  * <p>Provides a registry of available Plugin <i>classes</i> indexed by a mnemonic code known as the Plugin's ptype.
23750  * The <code>{@link Ext.Component#xtype xtype}</code> provides a way to avoid instantiating child Components
23751  * when creating a full, nested config object for a complete Ext page.</p>
23752  * <p>A child Component may be specified simply as a <i>config object</i>
23753  * as long as the correct <code>{@link Ext.Component#xtype xtype}</code> is specified so that if and when the Component
23754  * needs rendering, the correct type can be looked up for lazy instantiation.</p>
23755  * <p>For a list of all available <code>{@link Ext.Component#xtype xtypes}</code>, see {@link Ext.Component}.</p>
23756  * @singleton
23757  */
23758 Ext.define('Ext.PluginManager', {
23759     extend: 'Ext.AbstractManager',
23760     alternateClassName: 'Ext.PluginMgr',
23761     singleton: true,
23762     typeName: 'ptype',
23763
23764     /**
23765      * Creates a new Plugin from the specified config object using the
23766      * config object's ptype to determine the class to instantiate.
23767      * @param {Object} config A configuration object for the Plugin you wish to create.
23768      * @param {Constructor} defaultType The constructor to provide the default Plugin type if
23769      * the config object does not contain a <code>ptype</code>. (Optional if the config contains a <code>ptype</code>).
23770      * @return {Ext.Component} The newly instantiated Plugin.
23771      */
23772     //create: function(plugin, defaultType) {
23773     //    if (plugin instanceof this) {
23774     //        return plugin;
23775     //    } else {
23776     //        var type, config = {};
23777     //
23778     //        if (Ext.isString(plugin)) {
23779     //            type = plugin;
23780     //        }
23781     //        else {
23782     //            type = plugin[this.typeName] || defaultType;
23783     //            config = plugin;
23784     //        }
23785     //
23786     //        return Ext.createByAlias('plugin.' + type, config);
23787     //    }
23788     //},
23789
23790     create : function(config, defaultType){
23791         if (config.init) {
23792             return config;
23793         } else {
23794             return Ext.createByAlias('plugin.' + (config.ptype || defaultType), config);
23795         }
23796         
23797         // Prior system supported Singleton plugins.
23798         //var PluginCls = this.types[config.ptype || defaultType];
23799         //if (PluginCls.init) {
23800         //    return PluginCls;
23801         //} else {
23802         //    return new PluginCls(config);
23803         //}
23804     },
23805
23806     /**
23807      * Returns all plugins registered with the given type. Here, 'type' refers to the type of plugin, not its ptype.
23808      * @param {String} type The type to search for
23809      * @param {Boolean} defaultsOnly True to only return plugins of this type where the plugin's isDefault property is truthy
23810      * @return {Array} All matching plugins
23811      */
23812     findByType: function(type, defaultsOnly) {
23813         var matches = [],
23814             types   = this.types;
23815
23816         for (var name in types) {
23817             if (!types.hasOwnProperty(name)) {
23818                 continue;
23819             }
23820             var item = types[name];
23821
23822             if (item.type == type && (!defaultsOnly || (defaultsOnly === true && item.isDefault))) {
23823                 matches.push(item);
23824             }
23825         }
23826
23827         return matches;
23828     }
23829 }, function() {    
23830     /**
23831      * Shorthand for {@link Ext.PluginManager#registerType}
23832      * @param {String} ptype The ptype mnemonic string by which the Plugin class
23833      * may be looked up.
23834      * @param {Constructor} cls The new Plugin class.
23835      * @member Ext
23836      * @method preg
23837      */
23838     Ext.preg = function() {
23839         return Ext.PluginManager.registerType.apply(Ext.PluginManager, arguments);
23840     };
23841 });
23842
23843 /**
23844  * @class Ext.ComponentManager
23845  * @extends Ext.AbstractManager
23846  * <p>Provides a registry of all Components (instances of {@link Ext.Component} or any subclass
23847  * thereof) on a page so that they can be easily accessed by {@link Ext.Component component}
23848  * {@link Ext.Component#id id} (see {@link #get}, or the convenience method {@link Ext#getCmp Ext.getCmp}).</p>
23849  * <p>This object also provides a registry of available Component <i>classes</i>
23850  * indexed by a mnemonic code known as the Component's {@link Ext.Component#xtype xtype}.
23851  * The <code>xtype</code> provides a way to avoid instantiating child Components
23852  * when creating a full, nested config object for a complete Ext page.</p>
23853  * <p>A child Component may be specified simply as a <i>config object</i>
23854  * as long as the correct <code>{@link Ext.Component#xtype xtype}</code> is specified so that if and when the Component
23855  * needs rendering, the correct type can be looked up for lazy instantiation.</p>
23856  * <p>For a list of all available <code>{@link Ext.Component#xtype xtypes}</code>, see {@link Ext.Component}.</p>
23857  * @singleton
23858  */
23859 Ext.define('Ext.ComponentManager', {
23860     extend: 'Ext.AbstractManager',
23861     alternateClassName: 'Ext.ComponentMgr',
23862     
23863     singleton: true,
23864     
23865     typeName: 'xtype',
23866     
23867     /**
23868      * Creates a new Component from the specified config object using the
23869      * config object's xtype to determine the class to instantiate.
23870      * @param {Object} config A configuration object for the Component you wish to create.
23871      * @param {Constructor} defaultType The constructor to provide the default Component type if
23872      * the config object does not contain a <code>xtype</code>. (Optional if the config contains a <code>xtype</code>).
23873      * @return {Ext.Component} The newly instantiated Component.
23874      */
23875     create: function(component, defaultType){
23876         if (component instanceof Ext.AbstractComponent) {
23877             return component;
23878         }
23879         else if (Ext.isString(component)) {
23880             return Ext.createByAlias('widget.' + component);
23881         }
23882         else {
23883             var type = component.xtype || defaultType,
23884                 config = component;
23885             
23886             return Ext.createByAlias('widget.' + type, config);
23887         }
23888     },
23889
23890     registerType: function(type, cls) {
23891         this.types[type] = cls;
23892         cls[this.typeName] = type;
23893         cls.prototype[this.typeName] = type;
23894     }
23895 });
23896 /**
23897  * @class Ext.XTemplate
23898  * @extends Ext.Template
23899  * <p>A template class that supports advanced functionality like:<div class="mdetail-params"><ul>
23900  * <li>Autofilling arrays using templates and sub-templates</li>
23901  * <li>Conditional processing with basic comparison operators</li>
23902  * <li>Basic math function support</li>
23903  * <li>Execute arbitrary inline code with special built-in template variables</li>
23904  * <li>Custom member functions</li>
23905  * <li>Many special tags and built-in operators that aren't defined as part of
23906  * the API, but are supported in the templates that can be created</li>
23907  * </ul></div></p>
23908  * <p>XTemplate provides the templating mechanism built into:<div class="mdetail-params"><ul>
23909  * <li>{@link Ext.view.View}</li>
23910  * </ul></div></p>
23911  *
23912  * The {@link Ext.Template} describes
23913  * the acceptable parameters to pass to the constructor. The following
23914  * examples demonstrate all of the supported features.</p>
23915  *
23916  * <div class="mdetail-params"><ul>
23917  *
23918  * <li><b><u>Sample Data</u></b>
23919  * <div class="sub-desc">
23920  * <p>This is the data object used for reference in each code example:</p>
23921  * <pre><code>
23922 var data = {
23923 name: 'Tommy Maintz',
23924 title: 'Lead Developer',
23925 company: 'Sencha Inc.',
23926 email: 'tommy@sencha.com',
23927 address: '5 Cups Drive',
23928 city: 'Palo Alto',
23929 state: 'CA',
23930 zip: '44102',
23931 drinks: ['Coffee', 'Soda', 'Water'],
23932 kids: [{
23933         name: 'Joshua',
23934         age:3
23935     },{
23936         name: 'Matthew',
23937         age:2
23938     },{
23939         name: 'Solomon',
23940         age:0
23941 }]
23942 };
23943  </code></pre>
23944  * </div>
23945  * </li>
23946  *
23947  *
23948  * <li><b><u>Auto filling of arrays</u></b>
23949  * <div class="sub-desc">
23950  * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>for</tt></b> operator are used
23951  * to process the provided data object:
23952  * <ul>
23953  * <li>If the value specified in <tt>for</tt> is an array, it will auto-fill,
23954  * repeating the template block inside the <tt>tpl</tt> tag for each item in the
23955  * array.</li>
23956  * <li>If <tt>for="."</tt> is specified, the data object provided is examined.</li>
23957  * <li>While processing an array, the special variable <tt>{#}</tt>
23958  * will provide the current array index + 1 (starts at 1, not 0).</li>
23959  * </ul>
23960  * </p>
23961  * <pre><code>
23962 &lt;tpl <b>for</b>=".">...&lt;/tpl>       // loop through array at root node
23963 &lt;tpl <b>for</b>="foo">...&lt;/tpl>     // loop through array at foo node
23964 &lt;tpl <b>for</b>="foo.bar">...&lt;/tpl> // loop through array at foo.bar node
23965  </code></pre>
23966  * Using the sample data above:
23967  * <pre><code>
23968 var tpl = new Ext.XTemplate(
23969     '&lt;p>Kids: ',
23970     '&lt;tpl <b>for</b>=".">',       // process the data.kids node
23971         '&lt;p>{#}. {name}&lt;/p>',  // use current array index to autonumber
23972     '&lt;/tpl>&lt;/p>'
23973 );
23974 tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
23975  </code></pre>
23976  * <p>An example illustrating how the <b><tt>for</tt></b> property can be leveraged
23977  * to access specified members of the provided data object to populate the template:</p>
23978  * <pre><code>
23979 var tpl = new Ext.XTemplate(
23980     '&lt;p>Name: {name}&lt;/p>',
23981     '&lt;p>Title: {title}&lt;/p>',
23982     '&lt;p>Company: {company}&lt;/p>',
23983     '&lt;p>Kids: ',
23984     '&lt;tpl <b>for="kids"</b>>',     // interrogate the kids property within the data
23985         '&lt;p>{name}&lt;/p>',
23986     '&lt;/tpl>&lt;/p>'
23987 );
23988 tpl.overwrite(panel.body, data);  // pass the root node of the data object
23989  </code></pre>
23990  * <p>Flat arrays that contain values (and not objects) can be auto-rendered
23991  * using the special <b><tt>{.}</tt></b> variable inside a loop.  This variable
23992  * will represent the value of the array at the current index:</p>
23993  * <pre><code>
23994 var tpl = new Ext.XTemplate(
23995     '&lt;p>{name}\&#39;s favorite beverages:&lt;/p>',
23996     '&lt;tpl for="drinks">',
23997         '&lt;div> - {.}&lt;/div>',
23998     '&lt;/tpl>'
23999 );
24000 tpl.overwrite(panel.body, data);
24001  </code></pre>
24002  * <p>When processing a sub-template, for example while looping through a child array,
24003  * you can access the parent object's members via the <b><tt>parent</tt></b> object:</p>
24004  * <pre><code>
24005 var tpl = new Ext.XTemplate(
24006     '&lt;p>Name: {name}&lt;/p>',
24007     '&lt;p>Kids: ',
24008     '&lt;tpl for="kids">',
24009         '&lt;tpl if="age &amp;gt; 1">',
24010             '&lt;p>{name}&lt;/p>',
24011             '&lt;p>Dad: {<b>parent</b>.name}&lt;/p>',
24012         '&lt;/tpl>',
24013     '&lt;/tpl>&lt;/p>'
24014 );
24015 tpl.overwrite(panel.body, data);
24016  </code></pre>
24017  * </div>
24018  * </li>
24019  *
24020  *
24021  * <li><b><u>Conditional processing with basic comparison operators</u></b>
24022  * <div class="sub-desc">
24023  * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>if</tt></b> operator are used
24024  * to provide conditional checks for deciding whether or not to render specific
24025  * parts of the template. Notes:<div class="sub-desc"><ul>
24026  * <li>Double quotes must be encoded if used within the conditional</li>
24027  * <li>There is no <tt>else</tt> operator &mdash; if needed, two opposite
24028  * <tt>if</tt> statements should be used.</li>
24029  * </ul></div>
24030  * <pre><code>
24031 &lt;tpl if="age &gt; 1 &amp;&amp; age &lt; 10">Child&lt;/tpl>
24032 &lt;tpl if="age >= 10 && age < 18">Teenager&lt;/tpl>
24033 &lt;tpl <b>if</b>="this.isGirl(name)">...&lt;/tpl>
24034 &lt;tpl <b>if</b>="id==\'download\'">...&lt;/tpl>
24035 &lt;tpl <b>if</b>="needsIcon">&lt;img src="{icon}" class="{iconCls}"/>&lt;/tpl>
24036 // no good:
24037 &lt;tpl if="name == "Tommy"">Hello&lt;/tpl>
24038 // encode &#34; if it is part of the condition, e.g.
24039 &lt;tpl if="name == &#38;quot;Tommy&#38;quot;">Hello&lt;/tpl>
24040  * </code></pre>
24041  * Using the sample data above:
24042  * <pre><code>
24043 var tpl = new Ext.XTemplate(
24044     '&lt;p>Name: {name}&lt;/p>',
24045     '&lt;p>Kids: ',
24046     '&lt;tpl for="kids">',
24047         '&lt;tpl if="age &amp;gt; 1">',
24048             '&lt;p>{name}&lt;/p>',
24049         '&lt;/tpl>',
24050     '&lt;/tpl>&lt;/p>'
24051 );
24052 tpl.overwrite(panel.body, data);
24053  </code></pre>
24054  * </div>
24055  * </li>
24056  *
24057  *
24058  * <li><b><u>Basic math support</u></b>
24059  * <div class="sub-desc">
24060  * <p>The following basic math operators may be applied directly on numeric
24061  * data values:</p><pre>
24062  * + - * /
24063  * </pre>
24064  * For example:
24065  * <pre><code>
24066 var tpl = new Ext.XTemplate(
24067     '&lt;p>Name: {name}&lt;/p>',
24068     '&lt;p>Kids: ',
24069     '&lt;tpl for="kids">',
24070         '&lt;tpl if="age &amp;gt; 1">',  // <-- Note that the &gt; is encoded
24071             '&lt;p>{#}: {name}&lt;/p>',  // <-- Auto-number each item
24072             '&lt;p>In 5 Years: {age+5}&lt;/p>',  // <-- Basic math
24073             '&lt;p>Dad: {parent.name}&lt;/p>',
24074         '&lt;/tpl>',
24075     '&lt;/tpl>&lt;/p>'
24076 );
24077 tpl.overwrite(panel.body, data);
24078  </code></pre>
24079  * </div>
24080  * </li>
24081  *
24082  *
24083  * <li><b><u>Execute arbitrary inline code with special built-in template variables</u></b>
24084  * <div class="sub-desc">
24085  * <p>Anything between <code>{[ ... ]}</code> is considered code to be executed
24086  * in the scope of the template. There are some special variables available in that code:
24087  * <ul>
24088  * <li><b><tt>values</tt></b>: The values in the current scope. If you are using
24089  * scope changing sub-templates, you can change what <tt>values</tt> is.</li>
24090  * <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li>
24091  * <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the
24092  * loop you are in (1-based).</li>
24093  * <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length
24094  * of the array you are looping.</li>
24095  * </ul>
24096  * This example demonstrates basic row striping using an inline code block and the
24097  * <tt>xindex</tt> variable:</p>
24098  * <pre><code>
24099 var tpl = new Ext.XTemplate(
24100     '&lt;p>Name: {name}&lt;/p>',
24101     '&lt;p>Company: {[values.company.toUpperCase() + ", " + values.title]}&lt;/p>',
24102     '&lt;p>Kids: ',
24103     '&lt;tpl for="kids">',
24104         '&lt;div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
24105         '{name}',
24106         '&lt;/div>',
24107     '&lt;/tpl>&lt;/p>'
24108  );
24109 tpl.overwrite(panel.body, data);
24110  </code></pre>
24111  * </div>
24112  * </li>
24113  *
24114  * <li><b><u>Template member functions</u></b>
24115  * <div class="sub-desc">
24116  * <p>One or more member functions can be specified in a configuration
24117  * object passed into the XTemplate constructor for more complex processing:</p>
24118  * <pre><code>
24119 var tpl = new Ext.XTemplate(
24120     '&lt;p>Name: {name}&lt;/p>',
24121     '&lt;p>Kids: ',
24122     '&lt;tpl for="kids">',
24123         '&lt;tpl if="this.isGirl(name)">',
24124             '&lt;p>Girl: {name} - {age}&lt;/p>',
24125         '&lt;/tpl>',
24126          // use opposite if statement to simulate 'else' processing:
24127         '&lt;tpl if="this.isGirl(name) == false">',
24128             '&lt;p>Boy: {name} - {age}&lt;/p>',
24129         '&lt;/tpl>',
24130         '&lt;tpl if="this.isBaby(age)">',
24131             '&lt;p>{name} is a baby!&lt;/p>',
24132         '&lt;/tpl>',
24133     '&lt;/tpl>&lt;/p>',
24134     {
24135         // XTemplate configuration:
24136         compiled: true,
24137         // member functions:
24138         isGirl: function(name){
24139            return name == 'Sara Grace';
24140         },
24141         isBaby: function(age){
24142            return age < 1;
24143         }
24144     }
24145 );
24146 tpl.overwrite(panel.body, data);
24147  </code></pre>
24148  * </div>
24149  * </li>
24150  *
24151  * </ul></div>
24152  *
24153  * @param {Mixed} config
24154  */
24155
24156 Ext.define('Ext.XTemplate', {
24157
24158     /* Begin Definitions */
24159
24160     extend: 'Ext.Template',
24161
24162     statics: {
24163         /**
24164          * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
24165          * @param {String/HTMLElement} el A DOM element or its id
24166          * @return {Ext.Template} The created template
24167          * @static
24168          */
24169         from: function(el, config) {
24170             el = Ext.getDom(el);
24171             return new this(el.value || el.innerHTML, config || {});
24172         }
24173     },
24174
24175     /* End Definitions */
24176
24177     argsRe: /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
24178     nameRe: /^<tpl\b[^>]*?for="(.*?)"/,
24179     ifRe: /^<tpl\b[^>]*?if="(.*?)"/,
24180     execRe: /^<tpl\b[^>]*?exec="(.*?)"/,
24181     constructor: function() {
24182         this.callParent(arguments);
24183
24184         var me = this,
24185             html = me.html,
24186             argsRe = me.argsRe,
24187             nameRe = me.nameRe,
24188             ifRe = me.ifRe,
24189             execRe = me.execRe,
24190             id = 0,
24191             tpls = [],
24192             VALUES = 'values',
24193             PARENT = 'parent',
24194             XINDEX = 'xindex',
24195             XCOUNT = 'xcount',
24196             RETURN = 'return ',
24197             WITHVALUES = 'with(values){ ',
24198             m, matchName, matchIf, matchExec, exp, fn, exec, name, i;
24199
24200         html = ['<tpl>', html, '</tpl>'].join('');
24201
24202         while ((m = html.match(argsRe))) {
24203             exp = null;
24204             fn = null;
24205             exec = null;
24206             matchName = m[0].match(nameRe);
24207             matchIf = m[0].match(ifRe);
24208             matchExec = m[0].match(execRe);
24209
24210             exp = matchIf ? matchIf[1] : null;
24211             if (exp) {
24212                 fn = Ext.functionFactory(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + 'try{' + RETURN + Ext.String.htmlDecode(exp) + ';}catch(e){return;}}');
24213             }
24214
24215             exp = matchExec ? matchExec[1] : null;
24216             if (exp) {
24217                 exec = Ext.functionFactory(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + Ext.String.htmlDecode(exp) + ';}');
24218             }
24219
24220             name = matchName ? matchName[1] : null;
24221             if (name) {
24222                 if (name === '.') {
24223                     name = VALUES;
24224                 } else if (name === '..') {
24225                     name = PARENT;
24226                 }
24227                 name = Ext.functionFactory(VALUES, PARENT, 'try{' + WITHVALUES + RETURN + name + ';}}catch(e){return;}');
24228             }
24229
24230             tpls.push({
24231                 id: id,
24232                 target: name,
24233                 exec: exec,
24234                 test: fn,
24235                 body: m[1] || ''
24236             });
24237
24238             html = html.replace(m[0], '{xtpl' + id + '}');
24239             id = id + 1;
24240         }
24241
24242         for (i = tpls.length - 1; i >= 0; --i) {
24243             me.compileTpl(tpls[i]);
24244         }
24245         me.master = tpls[tpls.length - 1];
24246         me.tpls = tpls;
24247     },
24248
24249     // @private
24250     applySubTemplate: function(id, values, parent, xindex, xcount) {
24251         var me = this, t = me.tpls[id];
24252         return t.compiled.call(me, values, parent, xindex, xcount);
24253     },
24254     /**
24255      * @cfg {RegExp} codeRe The regular expression used to match code variables (default: matches <tt>{[expression]}</tt>).
24256      */
24257     codeRe: /\{\[((?:\\\]|.|\n)*?)\]\}/g,
24258
24259     re: /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\/]\s?[\d\.\+\-\*\/\(\)]+)?\}/g,
24260
24261     // @private
24262     compileTpl: function(tpl) {
24263         var fm = Ext.util.Format,
24264             me = this,
24265             useFormat = me.disableFormats !== true,
24266             body, bodyReturn, evaluatedFn;
24267
24268         function fn(m, name, format, args, math) {
24269             var v;
24270             // name is what is inside the {}
24271             // Name begins with xtpl, use a Sub Template
24272             if (name.substr(0, 4) == 'xtpl') {
24273                 return "',this.applySubTemplate(" + name.substr(4) + ", values, parent, xindex, xcount),'";
24274             }
24275             // name = "." - Just use the values object.
24276             if (name == '.') {
24277                 // filter to not include arrays/objects/nulls
24278                 v = 'Ext.Array.indexOf(["string", "number", "boolean"], typeof values) > -1 || Ext.isDate(values) ? values : ""';
24279             }
24280
24281             // name = "#" - Use the xindex
24282             else if (name == '#') {
24283                 v = 'xindex';
24284             }
24285             else if (name.substr(0, 7) == "parent.") {
24286                 v = name;
24287             }
24288             // name has a . in it - Use object literal notation, starting from values
24289             else if (name.indexOf('.') != -1) {
24290                 v = "values." + name;
24291             }
24292
24293             // name is a property of values
24294             else {
24295                 v = "values['" + name + "']";
24296             }
24297             if (math) {
24298                 v = '(' + v + math + ')';
24299             }
24300             if (format && useFormat) {
24301                 args = args ? ',' + args : "";
24302                 if (format.substr(0, 5) != "this.") {
24303                     format = "fm." + format + '(';
24304                 }
24305                 else {
24306                     format = 'this.' + format.substr(5) + '(';
24307                 }
24308             }
24309             else {
24310                 args = '';
24311                 format = "(" + v + " === undefined ? '' : ";
24312             }
24313             return "'," + format + v + args + "),'";
24314         }
24315
24316         function codeFn(m, code) {
24317             // Single quotes get escaped when the template is compiled, however we want to undo this when running code.
24318             return "',(" + code.replace(me.compileARe, "'") + "),'";
24319         }
24320
24321         bodyReturn = tpl.body.replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn).replace(me.codeRe, codeFn);
24322         body = "evaluatedFn = function(values, parent, xindex, xcount){return ['" + bodyReturn + "'].join('');};";
24323         eval(body);
24324
24325         tpl.compiled = function(values, parent, xindex, xcount) {
24326             var vs,
24327                 length,
24328                 buffer,
24329                 i;
24330
24331             if (tpl.test && !tpl.test.call(me, values, parent, xindex, xcount)) {
24332                 return '';
24333             }
24334
24335             vs = tpl.target ? tpl.target.call(me, values, parent) : values;
24336             if (!vs) {
24337                return '';
24338             }
24339
24340             parent = tpl.target ? values : parent;
24341             if (tpl.target && Ext.isArray(vs)) {
24342                 buffer = [];
24343                 length = vs.length;
24344                 if (tpl.exec) {
24345                     for (i = 0; i < length; i++) {
24346                         buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length);
24347                         tpl.exec.call(me, vs[i], parent, i + 1, length);
24348                     }
24349                 } else {
24350                     for (i = 0; i < length; i++) {
24351                         buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length);
24352                     }
24353                 }
24354                 return buffer.join('');
24355             }
24356
24357             if (tpl.exec) {
24358                 tpl.exec.call(me, vs, parent, xindex, xcount);
24359             }
24360             return evaluatedFn.call(me, vs, parent, xindex, xcount);
24361         };
24362
24363         return this;
24364     },
24365
24366     /**
24367      * Returns an HTML fragment of this template with the specified values applied.
24368      * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
24369      * @return {String} The HTML fragment
24370      */
24371     applyTemplate: function(values) {
24372         return this.master.compiled.call(this, values, {}, 1, 1);
24373     },
24374
24375     /**
24376      * Compile the template to a function for optimized performance.  Recommended if the template will be used frequently.
24377      * @return {Function} The compiled function
24378      */
24379     compile: function() {
24380         return this;
24381     }
24382 }, function() {
24383     /**
24384      * Alias for {@link #applyTemplate}
24385      * Returns an HTML fragment of this template with the specified values applied.
24386      * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
24387      * @return {String} The HTML fragment
24388      * @member Ext.XTemplate
24389      * @method apply
24390      */
24391     this.createAlias('apply', 'applyTemplate');
24392 });
24393
24394 /**
24395  * @class Ext.util.AbstractMixedCollection
24396  */
24397 Ext.define('Ext.util.AbstractMixedCollection', {
24398     requires: ['Ext.util.Filter'],
24399     
24400     mixins: {
24401         observable: 'Ext.util.Observable'
24402     },
24403
24404     constructor: function(allowFunctions, keyFn) {
24405         var me = this;
24406
24407         me.items = [];
24408         me.map = {};
24409         me.keys = [];
24410         me.length = 0;
24411
24412         me.addEvents(
24413             /**
24414              * @event clear
24415              * Fires when the collection is cleared.
24416              */
24417             'clear',
24418
24419             /**
24420              * @event add
24421              * Fires when an item is added to the collection.
24422              * @param {Number} index The index at which the item was added.
24423              * @param {Object} o The item added.
24424              * @param {String} key The key associated with the added item.
24425              */
24426             'add',
24427
24428             /**
24429              * @event replace
24430              * Fires when an item is replaced in the collection.
24431              * @param {String} key he key associated with the new added.
24432              * @param {Object} old The item being replaced.
24433              * @param {Object} new The new item.
24434              */
24435             'replace',
24436
24437             /**
24438              * @event remove
24439              * Fires when an item is removed from the collection.
24440              * @param {Object} o The item being removed.
24441              * @param {String} key (optional) The key associated with the removed item.
24442              */
24443             'remove'
24444         );
24445
24446         me.allowFunctions = allowFunctions === true;
24447
24448         if (keyFn) {
24449             me.getKey = keyFn;
24450         }
24451
24452         me.mixins.observable.constructor.call(me);
24453     },
24454     
24455     /**
24456      * @cfg {Boolean} allowFunctions Specify <tt>true</tt> if the {@link #addAll}
24457      * function should add function references to the collection. Defaults to
24458      * <tt>false</tt>.
24459      */
24460     allowFunctions : false,
24461
24462     /**
24463      * Adds an item to the collection. Fires the {@link #add} event when complete.
24464      * @param {String} key <p>The key to associate with the item, or the new item.</p>
24465      * <p>If a {@link #getKey} implementation was specified for this MixedCollection,
24466      * or if the key of the stored items is in a property called <tt><b>id</b></tt>,
24467      * the MixedCollection will be able to <i>derive</i> the key for the new item.
24468      * In this case just pass the new item in this parameter.</p>
24469      * @param {Object} o The item to add.
24470      * @return {Object} The item added.
24471      */
24472     add : function(key, obj){
24473         var me = this,
24474             myObj = obj,
24475             myKey = key,
24476             old;
24477
24478         if (arguments.length == 1) {
24479             myObj = myKey;
24480             myKey = me.getKey(myObj);
24481         }
24482         if (typeof myKey != 'undefined' && myKey !== null) {
24483             old = me.map[myKey];
24484             if (typeof old != 'undefined') {
24485                 return me.replace(myKey, myObj);
24486             }
24487             me.map[myKey] = myObj;
24488         }
24489         me.length++;
24490         me.items.push(myObj);
24491         me.keys.push(myKey);
24492         me.fireEvent('add', me.length - 1, myObj, myKey);
24493         return myObj;
24494     },
24495
24496     /**
24497       * MixedCollection has a generic way to fetch keys if you implement getKey.  The default implementation
24498       * simply returns <b><code>item.id</code></b> but you can provide your own implementation
24499       * to return a different value as in the following examples:<pre><code>
24500 // normal way
24501 var mc = new Ext.util.MixedCollection();
24502 mc.add(someEl.dom.id, someEl);
24503 mc.add(otherEl.dom.id, otherEl);
24504 //and so on
24505
24506 // using getKey
24507 var mc = new Ext.util.MixedCollection();
24508 mc.getKey = function(el){
24509    return el.dom.id;
24510 };
24511 mc.add(someEl);
24512 mc.add(otherEl);
24513
24514 // or via the constructor
24515 var mc = new Ext.util.MixedCollection(false, function(el){
24516    return el.dom.id;
24517 });
24518 mc.add(someEl);
24519 mc.add(otherEl);
24520      * </code></pre>
24521      * @param {Object} item The item for which to find the key.
24522      * @return {Object} The key for the passed item.
24523      */
24524     getKey : function(o){
24525          return o.id;
24526     },
24527
24528     /**
24529      * Replaces an item in the collection. Fires the {@link #replace} event when complete.
24530      * @param {String} key <p>The key associated with the item to replace, or the replacement item.</p>
24531      * <p>If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key
24532      * of your stored items is in a property called <tt><b>id</b></tt>, then the MixedCollection
24533      * will be able to <i>derive</i> the key of the replacement item. If you want to replace an item
24534      * with one having the same key value, then just pass the replacement item in this parameter.</p>
24535      * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate
24536      * with that key.
24537      * @return {Object}  The new item.
24538      */
24539     replace : function(key, o){
24540         var me = this,
24541             old,
24542             index;
24543
24544         if (arguments.length == 1) {
24545             o = arguments[0];
24546             key = me.getKey(o);
24547         }
24548         old = me.map[key];
24549         if (typeof key == 'undefined' || key === null || typeof old == 'undefined') {
24550              return me.add(key, o);
24551         }
24552         index = me.indexOfKey(key);
24553         me.items[index] = o;
24554         me.map[key] = o;
24555         me.fireEvent('replace', key, old, o);
24556         return o;
24557     },
24558
24559     /**
24560      * Adds all elements of an Array or an Object to the collection.
24561      * @param {Object/Array} objs An Object containing properties which will be added
24562      * to the collection, or an Array of values, each of which are added to the collection.
24563      * Functions references will be added to the collection if <code>{@link #allowFunctions}</code>
24564      * has been set to <tt>true</tt>.
24565      */
24566     addAll : function(objs){
24567         var me = this,
24568             i = 0,
24569             args,
24570             len,
24571             key;
24572
24573         if (arguments.length > 1 || Ext.isArray(objs)) {
24574             args = arguments.length > 1 ? arguments : objs;
24575             for (len = args.length; i < len; i++) {
24576                 me.add(args[i]);
24577             }
24578         } else {
24579             for (key in objs) {
24580                 if (objs.hasOwnProperty(key)) {
24581                     if (me.allowFunctions || typeof objs[key] != 'function') {
24582                         me.add(key, objs[key]);
24583                     }
24584                 }
24585             }
24586         }
24587     },
24588
24589     /**
24590      * Executes the specified function once for every item in the collection, passing the following arguments:
24591      * <div class="mdetail-params"><ul>
24592      * <li><b>item</b> : Mixed<p class="sub-desc">The collection item</p></li>
24593      * <li><b>index</b> : Number<p class="sub-desc">The item's index</p></li>
24594      * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the collection</p></li>
24595      * </ul></div>
24596      * The function should return a boolean value. Returning false from the function will stop the iteration.
24597      * @param {Function} fn The function to execute for each item.
24598      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current item in the iteration.
24599      */
24600     each : function(fn, scope){
24601         var items = [].concat(this.items), // each safe for removal
24602             i = 0,
24603             len = items.length,
24604             item;
24605
24606         for (; i < len; i++) {
24607             item = items[i];
24608             if (fn.call(scope || item, item, i, len) === false) {
24609                 break;
24610             }
24611         }
24612     },
24613
24614     /**
24615      * Executes the specified function once for every key in the collection, passing each
24616      * key, and its associated item as the first two parameters.
24617      * @param {Function} fn The function to execute for each item.
24618      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.
24619      */
24620     eachKey : function(fn, scope){
24621         var keys = this.keys,
24622             items = this.items,
24623             i = 0,
24624             len = keys.length;
24625
24626         for (; i < len; i++) {
24627             fn.call(scope || window, keys[i], items[i], i, len);
24628         }
24629     },
24630
24631     /**
24632      * Returns the first item in the collection which elicits a true return value from the
24633      * passed selection function.
24634      * @param {Function} fn The selection function to execute for each item.
24635      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.
24636      * @return {Object} The first item in the collection which returned true from the selection function.
24637      */
24638     findBy : function(fn, scope) {
24639         var keys = this.keys,
24640             items = this.items,
24641             i = 0,
24642             len = items.length;
24643
24644         for (; i < len; i++) {
24645             if (fn.call(scope || window, items[i], keys[i])) {
24646                 return items[i];
24647             }
24648         }
24649         return null;
24650     },
24651
24652     find : function() {
24653         if (Ext.isDefined(Ext.global.console)) {
24654             Ext.global.console.warn('Ext.util.MixedCollection: find has been deprecated. Use findBy instead.');
24655         }
24656         return this.findBy.apply(this, arguments);
24657     },
24658
24659     /**
24660      * Inserts an item at the specified index in the collection. Fires the {@link #add} event when complete.
24661      * @param {Number} index The index to insert the item at.
24662      * @param {String} key The key to associate with the new item, or the item itself.
24663      * @param {Object} o (optional) If the second parameter was a key, the new item.
24664      * @return {Object} The item inserted.
24665      */
24666     insert : function(index, key, obj){
24667         var me = this,
24668             myKey = key,
24669             myObj = obj;
24670
24671         if (arguments.length == 2) {
24672             myObj = myKey;
24673             myKey = me.getKey(myObj);
24674         }
24675         if (me.containsKey(myKey)) {
24676             me.suspendEvents();
24677             me.removeAtKey(myKey);
24678             me.resumeEvents();
24679         }
24680         if (index >= me.length) {
24681             return me.add(myKey, myObj);
24682         }
24683         me.length++;
24684         me.items.splice(index, 0, myObj);
24685         if (typeof myKey != 'undefined' && myKey !== null) {
24686             me.map[myKey] = myObj;
24687         }
24688         me.keys.splice(index, 0, myKey);
24689         me.fireEvent('add', index, myObj, myKey);
24690         return myObj;
24691     },
24692
24693     /**
24694      * Remove an item from the collection.
24695      * @param {Object} o The item to remove.
24696      * @return {Object} The item removed or false if no item was removed.
24697      */
24698     remove : function(o){
24699         return this.removeAt(this.indexOf(o));
24700     },
24701
24702     /**
24703      * Remove all items in the passed array from the collection.
24704      * @param {Array} items An array of items to be removed.
24705      * @return {Ext.util.MixedCollection} this object
24706      */
24707     removeAll : function(items){
24708         Ext.each(items || [], function(item) {
24709             this.remove(item);
24710         }, this);
24711
24712         return this;
24713     },
24714
24715     /**
24716      * Remove an item from a specified index in the collection. Fires the {@link #remove} event when complete.
24717      * @param {Number} index The index within the collection of the item to remove.
24718      * @return {Object} The item removed or false if no item was removed.
24719      */
24720     removeAt : function(index){
24721         var me = this,
24722             o,
24723             key;
24724
24725         if (index < me.length && index >= 0) {
24726             me.length--;
24727             o = me.items[index];
24728             me.items.splice(index, 1);
24729             key = me.keys[index];
24730             if (typeof key != 'undefined') {
24731                 delete me.map[key];
24732             }
24733             me.keys.splice(index, 1);
24734             me.fireEvent('remove', o, key);
24735             return o;
24736         }
24737         return false;
24738     },
24739
24740     /**
24741      * Removed an item associated with the passed key fom the collection.
24742      * @param {String} key The key of the item to remove.
24743      * @return {Object} The item removed or false if no item was removed.
24744      */
24745     removeAtKey : function(key){
24746         return this.removeAt(this.indexOfKey(key));
24747     },
24748
24749     /**
24750      * Returns the number of items in the collection.
24751      * @return {Number} the number of items in the collection.
24752      */
24753     getCount : function(){
24754         return this.length;
24755     },
24756
24757     /**
24758      * Returns index within the collection of the passed Object.
24759      * @param {Object} o The item to find the index of.
24760      * @return {Number} index of the item. Returns -1 if not found.
24761      */
24762     indexOf : function(o){
24763         return Ext.Array.indexOf(this.items, o);
24764     },
24765
24766     /**
24767      * Returns index within the collection of the passed key.
24768      * @param {String} key The key to find the index of.
24769      * @return {Number} index of the key.
24770      */
24771     indexOfKey : function(key){
24772         return Ext.Array.indexOf(this.keys, key);
24773     },
24774
24775     /**
24776      * Returns the item associated with the passed key OR index.
24777      * Key has priority over index.  This is the equivalent
24778      * of calling {@link #key} first, then if nothing matched calling {@link #getAt}.
24779      * @param {String/Number} key The key or index of the item.
24780      * @return {Object} If the item is found, returns the item.  If the item was not found, returns <tt>undefined</tt>.
24781      * If an item was found, but is a Class, returns <tt>null</tt>.
24782      */
24783     get : function(key) {
24784         var me = this,
24785             mk = me.map[key],
24786             item = mk !== undefined ? mk : (typeof key == 'number') ? me.items[key] : undefined;
24787         return typeof item != 'function' || me.allowFunctions ? item : null; // for prototype!
24788     },
24789
24790     /**
24791      * Returns the item at the specified index.
24792      * @param {Number} index The index of the item.
24793      * @return {Object} The item at the specified index.
24794      */
24795     getAt : function(index) {
24796         return this.items[index];
24797     },
24798
24799     /**
24800      * Returns the item associated with the passed key.
24801      * @param {String/Number} key The key of the item.
24802      * @return {Object} The item associated with the passed key.
24803      */
24804     getByKey : function(key) {
24805         return this.map[key];
24806     },
24807
24808     /**
24809      * Returns true if the collection contains the passed Object as an item.
24810      * @param {Object} o  The Object to look for in the collection.
24811      * @return {Boolean} True if the collection contains the Object as an item.
24812      */
24813     contains : function(o){
24814         return Ext.Array.contains(this.items, o);
24815     },
24816
24817     /**
24818      * Returns true if the collection contains the passed Object as a key.
24819      * @param {String} key The key to look for in the collection.
24820      * @return {Boolean} True if the collection contains the Object as a key.
24821      */
24822     containsKey : function(key){
24823         return typeof this.map[key] != 'undefined';
24824     },
24825
24826     /**
24827      * Removes all items from the collection.  Fires the {@link #clear} event when complete.
24828      */
24829     clear : function(){
24830         var me = this;
24831
24832         me.length = 0;
24833         me.items = [];
24834         me.keys = [];
24835         me.map = {};
24836         me.fireEvent('clear');
24837     },
24838
24839     /**
24840      * Returns the first item in the collection.
24841      * @return {Object} the first item in the collection..
24842      */
24843     first : function() {
24844         return this.items[0];
24845     },
24846
24847     /**
24848      * Returns the last item in the collection.
24849      * @return {Object} the last item in the collection..
24850      */
24851     last : function() {
24852         return this.items[this.length - 1];
24853     },
24854
24855     /**
24856      * Collects all of the values of the given property and returns their sum
24857      * @param {String} property The property to sum by
24858      * @param {String} root Optional 'root' property to extract the first argument from. This is used mainly when
24859      * summing fields in records, where the fields are all stored inside the 'data' object
24860      * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
24861      * @param {Number} end (optional) The record index to end at (defaults to <tt>-1</tt>)
24862      * @return {Number} The total
24863      */
24864     sum: function(property, root, start, end) {
24865         var values = this.extractValues(property, root),
24866             length = values.length,
24867             sum    = 0,
24868             i;
24869
24870         start = start || 0;
24871         end   = (end || end === 0) ? end : length - 1;
24872
24873         for (i = start; i <= end; i++) {
24874             sum += values[i];
24875         }
24876
24877         return sum;
24878     },
24879
24880     /**
24881      * Collects unique values of a particular property in this MixedCollection
24882      * @param {String} property The property to collect on
24883      * @param {String} root Optional 'root' property to extract the first argument from. This is used mainly when
24884      * summing fields in records, where the fields are all stored inside the 'data' object
24885      * @param {Boolean} allowBlank (optional) Pass true to allow null, undefined or empty string values
24886      * @return {Array} The unique values
24887      */
24888     collect: function(property, root, allowNull) {
24889         var values = this.extractValues(property, root),
24890             length = values.length,
24891             hits   = {},
24892             unique = [],
24893             value, strValue, i;
24894
24895         for (i = 0; i < length; i++) {
24896             value = values[i];
24897             strValue = String(value);
24898
24899             if ((allowNull || !Ext.isEmpty(value)) && !hits[strValue]) {
24900                 hits[strValue] = true;
24901                 unique.push(value);
24902             }
24903         }
24904
24905         return unique;
24906     },
24907
24908     /**
24909      * @private
24910      * Extracts all of the given property values from the items in the MC. Mainly used as a supporting method for
24911      * functions like sum and collect.
24912      * @param {String} property The property to extract
24913      * @param {String} root Optional 'root' property to extract the first argument from. This is used mainly when
24914      * extracting field data from Model instances, where the fields are stored inside the 'data' object
24915      * @return {Array} The extracted values
24916      */
24917     extractValues: function(property, root) {
24918         var values = this.items;
24919
24920         if (root) {
24921             values = Ext.Array.pluck(values, root);
24922         }
24923
24924         return Ext.Array.pluck(values, property);
24925     },
24926
24927     /**
24928      * Returns a range of items in this collection
24929      * @param {Number} startIndex (optional) The starting index. Defaults to 0.
24930      * @param {Number} endIndex (optional) The ending index. Defaults to the last item.
24931      * @return {Array} An array of items
24932      */
24933     getRange : function(start, end){
24934         var me = this,
24935             items = me.items,
24936             range = [],
24937             i;
24938
24939         if (items.length < 1) {
24940             return range;
24941         }
24942
24943         start = start || 0;
24944         end = Math.min(typeof end == 'undefined' ? me.length - 1 : end, me.length - 1);
24945         if (start <= end) {
24946             for (i = start; i <= end; i++) {
24947                 range[range.length] = items[i];
24948             }
24949         } else {
24950             for (i = start; i >= end; i--) {
24951                 range[range.length] = items[i];
24952             }
24953         }
24954         return range;
24955     },
24956
24957     /**
24958      * <p>Filters the objects in this collection by a set of {@link Ext.util.Filter Filter}s, or by a single
24959      * property/value pair with optional parameters for substring matching and case sensitivity. See
24960      * {@link Ext.util.Filter Filter} for an example of using Filter objects (preferred). Alternatively,
24961      * MixedCollection can be easily filtered by property like this:</p>
24962 <pre><code>
24963 //create a simple store with a few people defined
24964 var people = new Ext.util.MixedCollection();
24965 people.addAll([
24966     {id: 1, age: 25, name: 'Ed'},
24967     {id: 2, age: 24, name: 'Tommy'},
24968     {id: 3, age: 24, name: 'Arne'},
24969     {id: 4, age: 26, name: 'Aaron'}
24970 ]);
24971
24972 //a new MixedCollection containing only the items where age == 24
24973 var middleAged = people.filter('age', 24);
24974 </code></pre>
24975      *
24976      *
24977      * @param {Array/String} property A property on your objects, or an array of {@link Ext.util.Filter Filter} objects
24978      * @param {String/RegExp} value Either string that the property values
24979      * should start with or a RegExp to test against the property
24980      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
24981      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison (defaults to False).
24982      * @return {MixedCollection} The new filtered collection
24983      */
24984     filter : function(property, value, anyMatch, caseSensitive) {
24985         var filters = [],
24986             filterFn;
24987
24988         //support for the simple case of filtering by property/value
24989         if (Ext.isString(property)) {
24990             filters.push(Ext.create('Ext.util.Filter', {
24991                 property     : property,
24992                 value        : value,
24993                 anyMatch     : anyMatch,
24994                 caseSensitive: caseSensitive
24995             }));
24996         } else if (Ext.isArray(property) || property instanceof Ext.util.Filter) {
24997             filters = filters.concat(property);
24998         }
24999
25000         //at this point we have an array of zero or more Ext.util.Filter objects to filter with,
25001         //so here we construct a function that combines these filters by ANDing them together
25002         filterFn = function(record) {
25003             var isMatch = true,
25004                 length = filters.length,
25005                 i;
25006
25007             for (i = 0; i < length; i++) {
25008                 var filter = filters[i],
25009                     fn     = filter.filterFn,
25010                     scope  = filter.scope;
25011
25012                 isMatch = isMatch && fn.call(scope, record);
25013             }
25014
25015             return isMatch;
25016         };
25017
25018         return this.filterBy(filterFn);
25019     },
25020
25021     /**
25022      * Filter by a function. Returns a <i>new</i> collection that has been filtered.
25023      * The passed function will be called with each object in the collection.
25024      * If the function returns true, the value is included otherwise it is filtered.
25025      * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
25026      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this MixedCollection.
25027      * @return {MixedCollection} The new filtered collection
25028      */
25029     filterBy : function(fn, scope) {
25030         var me = this,
25031             newMC  = new this.self(),
25032             keys   = me.keys,
25033             items  = me.items,
25034             length = items.length,
25035             i;
25036
25037         newMC.getKey = me.getKey;
25038
25039         for (i = 0; i < length; i++) {
25040             if (fn.call(scope || me, items[i], keys[i])) {
25041                 newMC.add(keys[i], items[i]);
25042             }
25043         }
25044
25045         return newMC;
25046     },
25047
25048     /**
25049      * Finds the index of the first matching object in this collection by a specific property/value.
25050      * @param {String} property The name of a property on your objects.
25051      * @param {String/RegExp} value A string that the property values
25052      * should start with or a RegExp to test against the property.
25053      * @param {Number} start (optional) The index to start searching at (defaults to 0).
25054      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning.
25055      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison.
25056      * @return {Number} The matched index or -1
25057      */
25058     findIndex : function(property, value, start, anyMatch, caseSensitive){
25059         if(Ext.isEmpty(value, false)){
25060             return -1;
25061         }
25062         value = this.createValueMatcher(value, anyMatch, caseSensitive);
25063         return this.findIndexBy(function(o){
25064             return o && value.test(o[property]);
25065         }, null, start);
25066     },
25067
25068     /**
25069      * Find the index of the first matching object in this collection by a function.
25070      * If the function returns <i>true</i> it is considered a match.
25071      * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key).
25072      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this MixedCollection.
25073      * @param {Number} start (optional) The index to start searching at (defaults to 0).
25074      * @return {Number} The matched index or -1
25075      */
25076     findIndexBy : function(fn, scope, start){
25077         var me = this,
25078             keys = me.keys,
25079             items = me.items,
25080             i = start || 0,
25081             len = items.length;
25082
25083         for (; i < len; i++) {
25084             if (fn.call(scope || me, items[i], keys[i])) {
25085                 return i;
25086             }
25087         }
25088         return -1;
25089     },
25090
25091     /**
25092      * Returns a regular expression based on the given value and matching options. This is used internally for finding and filtering,
25093      * and by Ext.data.Store#filter
25094      * @private
25095      * @param {String} value The value to create the regex for. This is escaped using Ext.escapeRe
25096      * @param {Boolean} anyMatch True to allow any match - no regex start/end line anchors will be added. Defaults to false
25097      * @param {Boolean} caseSensitive True to make the regex case sensitive (adds 'i' switch to regex). Defaults to false.
25098      * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
25099      */
25100     createValueMatcher : function(value, anyMatch, caseSensitive, exactMatch) {
25101         if (!value.exec) { // not a regex
25102             var er = Ext.String.escapeRegex;
25103             value = String(value);
25104
25105             if (anyMatch === true) {
25106                 value = er(value);
25107             } else {
25108                 value = '^' + er(value);
25109                 if (exactMatch === true) {
25110                     value += '$';
25111                 }
25112             }
25113             value = new RegExp(value, caseSensitive ? '' : 'i');
25114         }
25115         return value;
25116     },
25117
25118     /**
25119      * Creates a shallow copy of this collection
25120      * @return {MixedCollection}
25121      */
25122     clone : function() {
25123         var me = this,
25124             copy = new this.self(),
25125             keys = me.keys,
25126             items = me.items,
25127             i = 0,
25128             len = items.length;
25129
25130         for(; i < len; i++){
25131             copy.add(keys[i], items[i]);
25132         }
25133         copy.getKey = me.getKey;
25134         return copy;
25135     }
25136 });
25137
25138 /**
25139  * @class Ext.util.Sortable
25140
25141 A mixin which allows a data component to be sorted. This is used by e.g. {@link Ext.data.Store} and {@link Ext.data.TreeStore}.
25142
25143 **NOTE**: This mixin is mainly for internal library use and most users should not need to use it directly. It
25144 is more likely you will want to use one of the component classes that import this mixin, such as
25145 {@link Ext.data.Store} or {@link Ext.data.TreeStore}.
25146  * @markdown
25147  * @docauthor Tommy Maintz <tommy@sencha.com>
25148  */
25149 Ext.define("Ext.util.Sortable", {
25150     /**
25151      * @property isSortable
25152      * @type Boolean
25153      * Flag denoting that this object is sortable. Always true.
25154      */
25155     isSortable: true,
25156     
25157     /**
25158      * The default sort direction to use if one is not specified (defaults to "ASC")
25159      * @property defaultSortDirection
25160      * @type String
25161      */
25162     defaultSortDirection: "ASC",
25163     
25164     requires: [
25165         'Ext.util.Sorter'
25166     ],
25167
25168     /**
25169      * The property in each item that contains the data to sort. (defaults to null)
25170      * @type String
25171      */    
25172     sortRoot: null,
25173     
25174     /**
25175      * Performs initialization of this mixin. Component classes using this mixin should call this method
25176      * during their own initialization.
25177      */
25178     initSortable: function() {
25179         var me = this,
25180             sorters = me.sorters;
25181         
25182         /**
25183          * The collection of {@link Ext.util.Sorter Sorters} currently applied to this Store
25184          * @property sorters
25185          * @type Ext.util.MixedCollection
25186          */
25187         me.sorters = Ext.create('Ext.util.AbstractMixedCollection', false, function(item) {
25188             return item.id || item.property;
25189         });
25190         
25191         if (sorters) {
25192             me.sorters.addAll(me.decodeSorters(sorters));
25193         }
25194     },
25195
25196     /**
25197      * <p>Sorts the data in the Store by one or more of its properties. Example usage:</p>
25198 <pre><code>
25199 //sort by a single field
25200 myStore.sort('myField', 'DESC');
25201
25202 //sorting by multiple fields
25203 myStore.sort([
25204     {
25205         property : 'age',
25206         direction: 'ASC'
25207     },
25208     {
25209         property : 'name',
25210         direction: 'DESC'
25211     }
25212 ]);
25213 </code></pre>
25214      * <p>Internally, Store converts the passed arguments into an array of {@link Ext.util.Sorter} instances, and delegates the actual
25215      * sorting to its internal {@link Ext.util.MixedCollection}.</p>
25216      * <p>When passing a single string argument to sort, Store maintains a ASC/DESC toggler per field, so this code:</p>
25217 <pre><code>
25218 store.sort('myField');
25219 store.sort('myField');
25220      </code></pre>
25221      * <p>Is equivalent to this code, because Store handles the toggling automatically:</p>
25222 <pre><code>
25223 store.sort('myField', 'ASC');
25224 store.sort('myField', 'DESC');
25225 </code></pre>
25226      * @param {String|Array} sorters Either a string name of one of the fields in this Store's configured {@link Ext.data.Model Model},
25227      * or an Array of sorter configurations.
25228      * @param {String} direction The overall direction to sort the data by. Defaults to "ASC".
25229      */
25230     sort: function(sorters, direction, where, doSort) {
25231         var me = this,
25232             sorter, sorterFn,
25233             newSorters;
25234         
25235         if (Ext.isArray(sorters)) {
25236             doSort = where;
25237             where = direction;
25238             newSorters = sorters;
25239         }
25240         else if (Ext.isObject(sorters)) {
25241             doSort = where;
25242             where = direction;
25243             newSorters = [sorters];
25244         }
25245         else if (Ext.isString(sorters)) {
25246             sorter = me.sorters.get(sorters);
25247
25248             if (!sorter) {
25249                 sorter = {
25250                     property : sorters,
25251                     direction: direction
25252                 };
25253                 newSorters = [sorter];
25254             }
25255             else if (direction === undefined) {
25256                 sorter.toggle();
25257             }
25258             else {
25259                 sorter.setDirection(direction);
25260             }
25261         }
25262         
25263         if (newSorters && newSorters.length) {
25264             newSorters = me.decodeSorters(newSorters);
25265             if (Ext.isString(where)) {
25266                 if (where === 'prepend') {
25267                     sorters = me.sorters.clone().items;
25268                     
25269                     me.sorters.clear();
25270                     me.sorters.addAll(newSorters);
25271                     me.sorters.addAll(sorters);
25272                 }
25273                 else {
25274                     me.sorters.addAll(newSorters);
25275                 }
25276             }
25277             else {
25278                 me.sorters.clear();
25279                 me.sorters.addAll(newSorters);
25280             }
25281             
25282             if (doSort !== false) {
25283                 me.onBeforeSort(newSorters);
25284             }
25285         }
25286         
25287         if (doSort !== false) {
25288             sorters = me.sorters.items;
25289             if (sorters.length) {
25290                 //construct an amalgamated sorter function which combines all of the Sorters passed
25291                 sorterFn = function(r1, r2) {
25292                     var result = sorters[0].sort(r1, r2),
25293                         length = sorters.length,
25294                         i;
25295
25296                         //if we have more than one sorter, OR any additional sorter functions together
25297                         for (i = 1; i < length; i++) {
25298                             result = result || sorters[i].sort.call(this, r1, r2);
25299                         }
25300
25301                     return result;
25302                 };
25303
25304                 me.doSort(sorterFn);                
25305             }
25306         }
25307         
25308         return sorters;
25309     },
25310     
25311     onBeforeSort: Ext.emptyFn,
25312         
25313     /**
25314      * @private
25315      * Normalizes an array of sorter objects, ensuring that they are all Ext.util.Sorter instances
25316      * @param {Array} sorters The sorters array
25317      * @return {Array} Array of Ext.util.Sorter objects
25318      */
25319     decodeSorters: function(sorters) {
25320         if (!Ext.isArray(sorters)) {
25321             if (sorters === undefined) {
25322                 sorters = [];
25323             } else {
25324                 sorters = [sorters];
25325             }
25326         }
25327
25328         var length = sorters.length,
25329             Sorter = Ext.util.Sorter,
25330             fields = this.model ? this.model.prototype.fields : null,
25331             field,
25332             config, i;
25333
25334         for (i = 0; i < length; i++) {
25335             config = sorters[i];
25336
25337             if (!(config instanceof Sorter)) {
25338                 if (Ext.isString(config)) {
25339                     config = {
25340                         property: config
25341                     };
25342                 }
25343                 
25344                 Ext.applyIf(config, {
25345                     root     : this.sortRoot,
25346                     direction: "ASC"
25347                 });
25348
25349                 //support for 3.x style sorters where a function can be defined as 'fn'
25350                 if (config.fn) {
25351                     config.sorterFn = config.fn;
25352                 }
25353
25354                 //support a function to be passed as a sorter definition
25355                 if (typeof config == 'function') {
25356                     config = {
25357                         sorterFn: config
25358                     };
25359                 }
25360
25361                 // ensure sortType gets pushed on if necessary
25362                 if (fields && !config.transform) {
25363                     field = fields.get(config.property);
25364                     config.transform = field ? field.sortType : undefined;
25365                 }
25366                 sorters[i] = Ext.create('Ext.util.Sorter', config);
25367             }
25368         }
25369
25370         return sorters;
25371     },
25372     
25373     getSorters: function() {
25374         return this.sorters.items;
25375     },
25376     
25377     /**
25378      * Returns an object describing the current sort state of this Store.
25379      * @return {Object} The sort state of the Store. An object with two properties:<ul>
25380      * <li><b>field</b> : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
25381      * <li><b>direction</b> : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
25382      * </ul>
25383      * See <tt>{@link #sortInfo}</tt> for additional details.
25384      */
25385     getSortState : function() {
25386         return this.sortInfo;
25387     }
25388 });
25389 /**
25390  * @class Ext.util.MixedCollection
25391  * <p>
25392  * Represents a collection of a set of key and value pairs. Each key in the MixedCollection
25393  * must be unique, the same key cannot exist twice. This collection is ordered, items in the
25394  * collection can be accessed by index  or via the key. Newly added items are added to
25395  * the end of the collection. This class is similar to {@link Ext.util.HashMap} however it
25396  * is heavier and provides more functionality. Sample usage:
25397  * <pre><code>
25398 var coll = new Ext.util.MixedCollection();
25399 coll.add('key1', 'val1');
25400 coll.add('key2', 'val2');
25401 coll.add('key3', 'val3');
25402
25403 console.log(coll.get('key1')); // prints 'val1'
25404 console.log(coll.indexOfKey('key3')); // prints 2
25405  * </code></pre>
25406  *
25407  * <p>
25408  * The MixedCollection also has support for sorting and filtering of the values in the collection.
25409  * <pre><code>
25410 var coll = new Ext.util.MixedCollection();
25411 coll.add('key1', 100);
25412 coll.add('key2', -100);
25413 coll.add('key3', 17);
25414 coll.add('key4', 0);
25415 var biggerThanZero = coll.filterBy(function(value){
25416     return value > 0;
25417 });
25418 console.log(biggerThanZero.getCount()); // prints 2
25419  * </code></pre>
25420  * </p>
25421  *
25422  * @constructor
25423  * @param {Boolean} allowFunctions Specify <tt>true</tt> if the {@link #addAll}
25424  * function should add function references to the collection. Defaults to
25425  * <tt>false</tt>.
25426  * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
25427  * and return the key value for that item.  This is used when available to look up the key on items that
25428  * were passed without an explicit key parameter to a MixedCollection method.  Passing this parameter is
25429  * equivalent to providing an implementation for the {@link #getKey} method.
25430  */
25431 Ext.define('Ext.util.MixedCollection', {
25432     extend: 'Ext.util.AbstractMixedCollection',
25433     mixins: {
25434         sortable: 'Ext.util.Sortable'
25435     },
25436
25437     constructor: function() {
25438         var me = this;
25439         me.callParent(arguments);
25440         me.addEvents('sort');
25441         me.mixins.sortable.initSortable.call(me);
25442     },
25443
25444     doSort: function(sorterFn) {
25445         this.sortBy(sorterFn);
25446     },
25447
25448     /**
25449      * @private
25450      * Performs the actual sorting based on a direction and a sorting function. Internally,
25451      * this creates a temporary array of all items in the MixedCollection, sorts it and then writes
25452      * the sorted array data back into this.items and this.keys
25453      * @param {String} property Property to sort by ('key', 'value', or 'index')
25454      * @param {String} dir (optional) Direction to sort 'ASC' or 'DESC'. Defaults to 'ASC'.
25455      * @param {Function} fn (optional) Comparison function that defines the sort order.
25456      * Defaults to sorting by numeric value.
25457      */
25458     _sort : function(property, dir, fn){
25459         var me = this,
25460             i, len,
25461             dsc   = String(dir).toUpperCase() == 'DESC' ? -1 : 1,
25462
25463             //this is a temporary array used to apply the sorting function
25464             c     = [],
25465             keys  = me.keys,
25466             items = me.items;
25467
25468         //default to a simple sorter function if one is not provided
25469         fn = fn || function(a, b) {
25470             return a - b;
25471         };
25472
25473         //copy all the items into a temporary array, which we will sort
25474         for(i = 0, len = items.length; i < len; i++){
25475             c[c.length] = {
25476                 key  : keys[i],
25477                 value: items[i],
25478                 index: i
25479             };
25480         }
25481
25482         //sort the temporary array
25483         Ext.Array.sort(c, function(a, b){
25484             var v = fn(a[property], b[property]) * dsc;
25485             if(v === 0){
25486                 v = (a.index < b.index ? -1 : 1);
25487             }
25488             return v;
25489         });
25490
25491         //copy the temporary array back into the main this.items and this.keys objects
25492         for(i = 0, len = c.length; i < len; i++){
25493             items[i] = c[i].value;
25494             keys[i]  = c[i].key;
25495         }
25496
25497         me.fireEvent('sort', me);
25498     },
25499
25500     /**
25501      * Sorts the collection by a single sorter function
25502      * @param {Function} sorterFn The function to sort by
25503      */
25504     sortBy: function(sorterFn) {
25505         var me     = this,
25506             items  = me.items,
25507             keys   = me.keys,
25508             length = items.length,
25509             temp   = [],
25510             i;
25511
25512         //first we create a copy of the items array so that we can sort it
25513         for (i = 0; i < length; i++) {
25514             temp[i] = {
25515                 key  : keys[i],
25516                 value: items[i],
25517                 index: i
25518             };
25519         }
25520
25521         Ext.Array.sort(temp, function(a, b) {
25522             var v = sorterFn(a.value, b.value);
25523             if (v === 0) {
25524                 v = (a.index < b.index ? -1 : 1);
25525             }
25526
25527             return v;
25528         });
25529
25530         //copy the temporary array back into the main this.items and this.keys objects
25531         for (i = 0; i < length; i++) {
25532             items[i] = temp[i].value;
25533             keys[i]  = temp[i].key;
25534         }
25535         
25536         me.fireEvent('sort', me, items, keys);
25537     },
25538
25539     /**
25540      * Reorders each of the items based on a mapping from old index to new index. Internally this
25541      * just translates into a sort. The 'sort' event is fired whenever reordering has occured.
25542      * @param {Object} mapping Mapping from old item index to new item index
25543      */
25544     reorder: function(mapping) {
25545         var me = this,
25546             items = me.items,
25547             index = 0,
25548             length = items.length,
25549             order = [],
25550             remaining = [],
25551             oldIndex;
25552
25553         me.suspendEvents();
25554
25555         //object of {oldPosition: newPosition} reversed to {newPosition: oldPosition}
25556         for (oldIndex in mapping) {
25557             order[mapping[oldIndex]] = items[oldIndex];
25558         }
25559
25560         for (index = 0; index < length; index++) {
25561             if (mapping[index] == undefined) {
25562                 remaining.push(items[index]);
25563             }
25564         }
25565
25566         for (index = 0; index < length; index++) {
25567             if (order[index] == undefined) {
25568                 order[index] = remaining.shift();
25569             }
25570         }
25571
25572         me.clear();
25573         me.addAll(order);
25574
25575         me.resumeEvents();
25576         me.fireEvent('sort', me);
25577     },
25578
25579     /**
25580      * Sorts this collection by <b>key</b>s.
25581      * @param {String} direction (optional) 'ASC' or 'DESC'. Defaults to 'ASC'.
25582      * @param {Function} fn (optional) Comparison function that defines the sort order.
25583      * Defaults to sorting by case insensitive string.
25584      */
25585     sortByKey : function(dir, fn){
25586         this._sort('key', dir, fn || function(a, b){
25587             var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase();
25588             return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
25589         });
25590     }
25591 });
25592
25593 /**
25594  * @class Ext.data.StoreManager
25595  * @extends Ext.util.MixedCollection
25596  * <p>Contains a collection of all stores that are created that have an identifier.
25597  * An identifier can be assigned by setting the {@link Ext.data.AbstractStore#storeId storeId} 
25598  * property. When a store is in the StoreManager, it can be referred to via it's identifier:
25599  * <pre><code>
25600 Ext.create('Ext.data.Store', {
25601     model: 'SomeModel',
25602     storeId: 'myStore'
25603 });
25604
25605 var store = Ext.data.StoreManager.lookup('myStore');
25606  * </code></pre>
25607  * Also note that the {@link #lookup} method is aliased to {@link Ext#getStore} for convenience.</p>
25608  * <p>
25609  * If a store is registered with the StoreManager, you can also refer to the store by it's identifier when
25610  * registering it with any Component that consumes data from a store:
25611  * <pre><code>
25612 Ext.create('Ext.data.Store', {
25613     model: 'SomeModel',
25614     storeId: 'myStore'
25615 });
25616
25617 Ext.create('Ext.view.View', {
25618     store: 'myStore',
25619     // other configuration here
25620 });
25621  * </code></pre>
25622  * </p>
25623  * @singleton
25624  * @docauthor Evan Trimboli <evan@sencha.com>
25625  * TODO: Make this an AbstractMgr
25626  */
25627 Ext.define('Ext.data.StoreManager', {
25628     extend: 'Ext.util.MixedCollection',
25629     alternateClassName: ['Ext.StoreMgr', 'Ext.data.StoreMgr', 'Ext.StoreManager'],
25630     singleton: true,
25631     uses: ['Ext.data.ArrayStore'],
25632     
25633     /**
25634      * @cfg {Object} listeners @hide
25635      */
25636
25637     /**
25638      * Registers one or more Stores with the StoreManager. You do not normally need to register stores
25639      * manually.  Any store initialized with a {@link Ext.data.Store#storeId} will be auto-registered. 
25640      * @param {Ext.data.Store} store1 A Store instance
25641      * @param {Ext.data.Store} store2 (optional)
25642      * @param {Ext.data.Store} etc... (optional)
25643      */
25644     register : function() {
25645         for (var i = 0, s; (s = arguments[i]); i++) {
25646             this.add(s);
25647         }
25648     },
25649
25650     /**
25651      * Unregisters one or more Stores with the StoreManager
25652      * @param {String/Object} id1 The id of the Store, or a Store instance
25653      * @param {String/Object} id2 (optional)
25654      * @param {String/Object} etc... (optional)
25655      */
25656     unregister : function() {
25657         for (var i = 0, s; (s = arguments[i]); i++) {
25658             this.remove(this.lookup(s));
25659         }
25660     },
25661
25662     /**
25663      * Gets a registered Store by id
25664      * @param {String/Object} id The id of the Store, or a Store instance, or a store configuration
25665      * @return {Ext.data.Store}
25666      */
25667     lookup : function(store) {
25668         // handle the case when we are given an array or an array of arrays.
25669         if (Ext.isArray(store)) {
25670             var fields = ['field1'], 
25671                 expand = !Ext.isArray(store[0]),
25672                 data = store,
25673                 i,
25674                 len;
25675                 
25676             if(expand){
25677                 data = [];
25678                 for (i = 0, len = store.length; i < len; ++i) {
25679                     data.push([store[i]]);
25680                 }
25681             } else {
25682                 for(i = 2, len = store[0].length; i <= len; ++i){
25683                     fields.push('field' + i);
25684                 }
25685             }
25686             return Ext.create('Ext.data.ArrayStore', {
25687                 data  : data,
25688                 fields: fields,
25689                 autoDestroy: true,
25690                 autoCreated: true,
25691                 expanded: expand
25692             });
25693         }
25694         
25695         if (Ext.isString(store)) {
25696             // store id
25697             return this.get(store);
25698         } else {
25699             // store instance or store config
25700             return Ext.data.AbstractStore.create(store);
25701         }
25702     },
25703
25704     // getKey implementation for MixedCollection
25705     getKey : function(o) {
25706          return o.storeId;
25707     }
25708 }, function() {    
25709     /**
25710      * <p>Creates a new store for the given id and config, then registers it with the {@link Ext.data.StoreManager Store Mananger}. 
25711      * Sample usage:</p>
25712     <pre><code>
25713     Ext.regStore('AllUsers', {
25714         model: 'User'
25715     });
25716
25717     //the store can now easily be used throughout the application
25718     new Ext.List({
25719         store: 'AllUsers',
25720         ... other config
25721     });
25722     </code></pre>
25723      * @param {String} id The id to set on the new store
25724      * @param {Object} config The store config
25725      * @param {Constructor} cls The new Component class.
25726      * @member Ext
25727      * @method regStore
25728      */
25729     Ext.regStore = function(name, config) {
25730         var store;
25731
25732         if (Ext.isObject(name)) {
25733             config = name;
25734         } else {
25735             config.storeId = name;
25736         }
25737
25738         if (config instanceof Ext.data.Store) {
25739             store = config;
25740         } else {
25741             store = Ext.create('Ext.data.Store', config);
25742         }
25743
25744         return Ext.data.StoreManager.register(store);
25745     };
25746
25747     /**
25748      * Gets a registered Store by id (shortcut to {@link #lookup})
25749      * @param {String/Object} id The id of the Store, or a Store instance
25750      * @return {Ext.data.Store}
25751      * @member Ext
25752      * @method getStore
25753      */
25754     Ext.getStore = function(name) {
25755         return Ext.data.StoreManager.lookup(name);
25756     };
25757 });
25758
25759 /**
25760  * @class Ext.LoadMask
25761  * A simple utility class for generically masking elements while loading data.  If the {@link #store}
25762  * config option is specified, the masking will be automatically synchronized with the store's loading
25763  * process and the mask element will be cached for reuse.
25764  * <p>Example usage:</p>
25765  * <pre><code>
25766 // Basic mask:
25767 var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
25768 myMask.show();
25769 </code></pre>
25770
25771  * @constructor
25772  * Create a new LoadMask
25773  * @param {Mixed} el The element, element ID, or DOM node you wish to mask. Also, may be a Component who's element you wish to mask.
25774  * @param {Object} config The config object
25775  */
25776
25777 Ext.define('Ext.LoadMask', {
25778
25779     /* Begin Definitions */
25780
25781     mixins: {
25782         observable: 'Ext.util.Observable'
25783     },
25784
25785     requires: ['Ext.data.StoreManager'],
25786
25787     /* End Definitions */
25788
25789     /**
25790      * @cfg {Ext.data.Store} store
25791      * Optional Store to which the mask is bound. The mask is displayed when a load request is issued, and
25792      * hidden on either load success, or load fail.
25793      */
25794
25795     /**
25796      * @cfg {String} msg
25797      * The text to display in a centered loading message box (defaults to 'Loading...')
25798      */
25799     msg : 'Loading...',
25800     /**
25801      * @cfg {String} msgCls
25802      * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
25803      */
25804     msgCls : Ext.baseCSSPrefix + 'mask-loading',
25805     
25806     /**
25807      * @cfg {Boolean} useMsg
25808      * Whether or not to use a loading message class or simply mask the bound element.
25809      */
25810     useMsg: true,
25811
25812     /**
25813      * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
25814      * @type Boolean
25815      */
25816     disabled: false,
25817
25818     constructor : function(el, config) {
25819         var me = this;
25820
25821         if (el.isComponent) {
25822             me.bindComponent(el);
25823         } else {
25824             me.el = Ext.get(el);
25825         }
25826         Ext.apply(me, config);
25827
25828         me.addEvents('beforeshow', 'show', 'hide');
25829         if (me.store) {
25830             me.bindStore(me.store, true);
25831         }
25832         me.mixins.observable.constructor.call(me, config);
25833     },
25834
25835     bindComponent: function(comp) {
25836         var me = this,
25837             listeners = {
25838                 resize: me.onComponentResize,
25839                 scope: me
25840             };
25841
25842         if (comp.el) {
25843             me.onComponentRender(comp);
25844         } else {
25845             listeners.render = {
25846                 fn: me.onComponentRender,
25847                 scope: me,
25848                 single: true
25849             };
25850         }
25851         me.mon(comp, listeners);
25852     },
25853
25854     /**
25855      * @private
25856      * Called if we were configured with a Component, and that Component was not yet rendered. Collects the element to mask.
25857      */
25858     onComponentRender: function(comp) {
25859         this.el = comp.getContentTarget();
25860     },
25861
25862     /**
25863      * @private
25864      * Called when this LoadMask's Component is resized. The isMasked method also re-centers any displayed message.
25865      */
25866     onComponentResize: function(comp, w, h) {
25867         this.el.isMasked();
25868     },
25869
25870     /**
25871      * Changes the data store bound to this LoadMask.
25872      * @param {Store} store The store to bind to this LoadMask
25873      */
25874     bindStore : function(store, initial) {
25875         var me = this;
25876
25877         if (!initial && me.store) {
25878             me.mun(me.store, {
25879                 scope: me,
25880                 beforeload: me.onBeforeLoad,
25881                 load: me.onLoad,
25882                 exception: me.onLoad
25883             });
25884             if(!store) {
25885                 me.store = null;
25886             }
25887         }
25888         if (store) {
25889             store = Ext.data.StoreManager.lookup(store);
25890             me.mon(store, {
25891                 scope: me,
25892                 beforeload: me.onBeforeLoad,
25893                 load: me.onLoad,
25894                 exception: me.onLoad
25895             });
25896
25897         }
25898         me.store = store;
25899         if (store && store.isLoading()) {
25900             me.onBeforeLoad();
25901         }
25902     },
25903
25904     /**
25905      * Disables the mask to prevent it from being displayed
25906      */
25907     disable : function() {
25908         var me = this;
25909
25910        me.disabled = true;
25911        if (me.loading) {
25912            me.onLoad();
25913        }
25914     },
25915
25916     /**
25917      * Enables the mask so that it can be displayed
25918      */
25919     enable : function() {
25920         this.disabled = false;
25921     },
25922
25923     /**
25924      * Method to determine whether this LoadMask is currently disabled.
25925      * @return {Boolean} the disabled state of this LoadMask.
25926      */
25927     isDisabled : function() {
25928         return this.disabled;
25929     },
25930
25931     // private
25932     onLoad : function() {
25933         var me = this;
25934
25935         me.loading = false;
25936         me.el.unmask();
25937         me.fireEvent('hide', me, me.el, me.store);
25938     },
25939
25940     // private
25941     onBeforeLoad : function() {
25942         var me = this;
25943
25944         if (!me.disabled && !me.loading && me.fireEvent('beforeshow', me, me.el, me.store) !== false) {
25945             if (me.useMsg) {
25946                 me.el.mask(me.msg, me.msgCls, false);
25947             } else {
25948                 me.el.mask();
25949             }
25950             
25951             me.fireEvent('show', me, me.el, me.store);
25952             me.loading = true;
25953         }
25954     },
25955
25956     /**
25957      * Show this LoadMask over the configured Element.
25958      */
25959     show: function() {
25960         this.onBeforeLoad();
25961     },
25962
25963     /**
25964      * Hide this LoadMask.
25965      */
25966     hide: function() {
25967         this.onLoad();
25968     },
25969
25970     // private
25971     destroy : function() {
25972         this.hide();
25973         this.clearListeners();
25974     }
25975 });
25976
25977 /**
25978  * @class Ext.ComponentLoader
25979  * @extends Ext.ElementLoader
25980  * 
25981  * This class is used to load content via Ajax into a {@link Ext.Component}. In general 
25982  * this class will not be instanced directly, rather a loader configuration will be passed to the
25983  * constructor of the {@link Ext.Component}.
25984  * 
25985  * ## HTML Renderer
25986  * By default, the content loaded will be processed as raw html. The response text
25987  * from the request is taken and added to the component. This can be used in
25988  * conjunction with the {@link #scripts} option to execute any inline scripts in
25989  * the resulting content. Using this renderer has the same effect as passing the
25990  * {@link Ext.Component#html} configuration option.
25991  * 
25992  * ## Data Renderer
25993  * This renderer allows content to be added by using JSON data and a {@link Ext.XTemplate}.
25994  * The content received from the response is passed to the {@link Ext.Component#update} method.
25995  * This content is run through the attached {@link Ext.Component#tpl} and the data is added to
25996  * the Component. Using this renderer has the same effect as using the {@link Ext.Component#data}
25997  * configuration in conjunction with a {@link Ext.Component#tpl}.
25998  * 
25999  * ## Component Renderer
26000  * This renderer can only be used with a {@link Ext.Container} and subclasses. It allows for
26001  * Components to be loaded remotely into a Container. The response is expected to be a single/series of
26002  * {@link Ext.Component} configuration objects. When the response is received, the data is decoded
26003  * and then passed to {@link Ext.Container#add}. Using this renderer has the same effect as specifying
26004  * the {@link Ext.Container#items} configuration on a Container. 
26005  * 
26006  * ## Custom Renderer
26007  * A custom function can be passed to handle any other special case, see the {@link #renderer} option.
26008  * 
26009  * ## Example Usage
26010  *     new Ext.Component({
26011  *         tpl: '{firstName} - {lastName}',
26012  *         loader: {
26013  *             url: 'myPage.php',
26014  *             renderer: 'data',
26015  *             params: {
26016  *                 userId: 1
26017  *             }
26018  *         }
26019  *     });
26020  */
26021 Ext.define('Ext.ComponentLoader', {
26022
26023     /* Begin Definitions */
26024     
26025     extend: 'Ext.ElementLoader',
26026
26027     statics: {
26028         Renderer: {
26029             Data: function(loader, response, active){
26030                 var success = true;
26031                 try {
26032                     loader.getTarget().update(Ext.decode(response.responseText));
26033                 } catch (e) {
26034                     success = false;
26035                 }
26036                 return success;
26037             },
26038
26039             Component: function(loader, response, active){
26040                 var success = true,
26041                     target = loader.getTarget(),
26042                     items = [];
26043
26044                 if (!target.isContainer) {
26045                     Ext.Error.raise({
26046                         target: target,
26047                         msg: 'Components can only be loaded into a container'
26048                     });
26049                 }
26050
26051                 try {
26052                     items = Ext.decode(response.responseText);
26053                 } catch (e) {
26054                     success = false;
26055                 }
26056
26057                 if (success) {
26058                     if (active.removeAll) {
26059                         target.removeAll();
26060                     }
26061                     target.add(items);
26062                 }
26063                 return success;
26064             }
26065         }
26066     },
26067
26068     /* End Definitions */
26069
26070     /**
26071      * @cfg {Ext.Component/String} target The target {@link Ext.Component} for the loader. Defaults to <tt>null</tt>.
26072      * If a string is passed it will be looked up via the id.
26073      */
26074     target: null,
26075
26076     /**
26077      * @cfg {Mixed} loadMask True or a {@link Ext.LoadMask} configuration to enable masking during loading. Defaults to <tt>false</tt>.
26078      */
26079     loadMask: false,
26080     
26081     /**
26082      * @cfg {Boolean} scripts True to parse any inline script tags in the response. This only used when using the html
26083      * {@link #renderer}.
26084      */
26085
26086     /**
26087      * @cfg {String/Function} renderer
26088
26089 The type of content that is to be loaded into, which can be one of 3 types:
26090
26091 + **html** : Loads raw html content, see {@link Ext.Component#html}
26092 + **data** : Loads raw html content, see {@link Ext.Component#data}
26093 + **component** : Loads child {Ext.Component} instances. This option is only valid when used with a Container.
26094
26095 Defaults to `html`.
26096
26097 Alternatively, you can pass a function which is called with the following parameters.
26098
26099 + loader - Loader instance
26100 + response - The server response
26101 + active - The active request
26102
26103 The function must return false is loading is not successful. Below is a sample of using a custom renderer:
26104
26105     new Ext.Component({
26106         loader: {
26107             url: 'myPage.php',
26108             renderer: function(loader, response, active) {
26109                 var text = response.responseText;
26110                 loader.getTarget().update('The response is ' + text);
26111                 return true;
26112             }
26113         }
26114     });
26115      * @markdown
26116      */
26117     renderer: 'html',
26118
26119     /**
26120      * Set a {Ext.Component} as the target of this loader. Note that if the target is changed,
26121      * any active requests will be aborted.
26122      * @param {String/Ext.Component} target The component to be the target of this loader. If a string is passed
26123      * it will be looked up via its id.
26124      */
26125     setTarget: function(target){
26126         var me = this;
26127         
26128         if (Ext.isString(target)) {
26129             target = Ext.getCmp(target);
26130         }
26131
26132         if (me.target && me.target != target) {
26133             me.abort();
26134         }
26135         me.target = target;
26136     },
26137     
26138     // inherit docs
26139     removeMask: function(){
26140         this.target.setLoading(false);
26141     },
26142     
26143     /**
26144      * Add the mask on the target
26145      * @private
26146      * @param {Mixed} mask The mask configuration
26147      */
26148     addMask: function(mask){
26149         this.target.setLoading(mask);
26150     },
26151
26152     /**
26153      * Get the target of this loader.
26154      * @return {Ext.Component} target The target, null if none exists.
26155      */
26156     
26157     setOptions: function(active, options){
26158         active.removeAll = Ext.isDefined(options.removeAll) ? options.removeAll : this.removeAll;
26159     },
26160
26161     /**
26162      * Gets the renderer to use
26163      * @private
26164      * @param {String/Function} renderer The renderer to use
26165      * @return {Function} A rendering function to use.
26166      */
26167     getRenderer: function(renderer){
26168         if (Ext.isFunction(renderer)) {
26169             return renderer;
26170         }
26171
26172         var renderers = this.statics().Renderer;
26173         switch (renderer) {
26174             case 'component':
26175                 return renderers.Component;
26176             case 'data':
26177                 return renderers.Data;
26178             default:
26179                 return Ext.ElementLoader.Renderer.Html;
26180         }
26181     }
26182 });
26183
26184 /**
26185  * @class Ext.layout.component.Auto
26186  * @extends Ext.layout.component.Component
26187  * @private
26188  *
26189  * <p>The AutoLayout is the default layout manager delegated by {@link Ext.Component} to
26190  * render any child Elements when no <tt>{@link Ext.Component#layout layout}</tt> is configured.</p>
26191  */
26192
26193 Ext.define('Ext.layout.component.Auto', {
26194
26195     /* Begin Definitions */
26196
26197     alias: 'layout.autocomponent',
26198
26199     extend: 'Ext.layout.component.Component',
26200
26201     /* End Definitions */
26202
26203     type: 'autocomponent',
26204
26205     onLayout : function(width, height) {
26206         this.setTargetSize(width, height);
26207     }
26208 });
26209 /**
26210  * @class Ext.AbstractComponent
26211  * <p>An abstract base class which provides shared methods for Components across the Sencha product line.</p>
26212  * <p>Please refer to sub class's documentation</p>
26213  * @constructor
26214  */
26215
26216 Ext.define('Ext.AbstractComponent', {
26217
26218     /* Begin Definitions */
26219
26220     mixins: {
26221         observable: 'Ext.util.Observable',
26222         animate: 'Ext.util.Animate',
26223         state: 'Ext.state.Stateful'
26224     },
26225
26226     requires: [
26227         'Ext.PluginManager',
26228         'Ext.ComponentManager',
26229         'Ext.core.Element',
26230         'Ext.core.DomHelper',
26231         'Ext.XTemplate',
26232         'Ext.ComponentQuery',
26233         'Ext.LoadMask',
26234         'Ext.ComponentLoader',
26235         'Ext.EventManager',
26236         'Ext.layout.Layout',
26237         'Ext.layout.component.Auto'
26238     ],
26239
26240     // Please remember to add dependencies whenever you use it
26241     // I had to fix these many times already
26242     uses: [
26243         'Ext.ZIndexManager'
26244     ],
26245
26246     statics: {
26247         AUTO_ID: 1000
26248     },
26249
26250     /* End Definitions */
26251
26252     isComponent: true,
26253
26254     getAutoId: function() {
26255         return ++Ext.AbstractComponent.AUTO_ID;
26256     },
26257
26258     /**
26259      * @cfg {String} id
26260      * <p>The <b><u>unique id of this component instance</u></b> (defaults to an {@link #getId auto-assigned id}).</p>
26261      * <p>It should not be necessary to use this configuration except for singleton objects in your application.
26262      * Components created with an id may be accessed globally using {@link Ext#getCmp Ext.getCmp}.</p>
26263      * <p>Instead of using assigned ids, use the {@link #itemId} config, and {@link Ext.ComponentQuery ComponentQuery} which
26264      * provides selector-based searching for Sencha Components analogous to DOM querying. The {@link Ext.container.Container Container}
26265      * class contains {@link Ext.container.Container#down shortcut methods} to query its descendant Components by selector.</p>
26266      * <p>Note that this id will also be used as the element id for the containing HTML element
26267      * that is rendered to the page for this component. This allows you to write id-based CSS
26268      * rules to style the specific instance of this component uniquely, and also to select
26269      * sub-elements using this component's id as the parent.</p>
26270      * <p><b>Note</b>: to avoid complications imposed by a unique <tt>id</tt> also see <code>{@link #itemId}</code>.</p>
26271      * <p><b>Note</b>: to access the container of a Component see <code>{@link #ownerCt}</code>.</p>
26272      */
26273
26274     /**
26275      * @cfg {String} itemId
26276      * <p>An <tt>itemId</tt> can be used as an alternative way to get a reference to a component
26277      * when no object reference is available.  Instead of using an <code>{@link #id}</code> with
26278      * {@link Ext}.{@link Ext#getCmp getCmp}, use <code>itemId</code> with
26279      * {@link Ext.container.Container}.{@link Ext.container.Container#getComponent getComponent} which will retrieve
26280      * <code>itemId</code>'s or <tt>{@link #id}</tt>'s. Since <code>itemId</code>'s are an index to the
26281      * container's internal MixedCollection, the <code>itemId</code> is scoped locally to the container --
26282      * avoiding potential conflicts with {@link Ext.ComponentManager} which requires a <b>unique</b>
26283      * <code>{@link #id}</code>.</p>
26284      * <pre><code>
26285 var c = new Ext.panel.Panel({ //
26286     {@link Ext.Component#height height}: 300,
26287     {@link #renderTo}: document.body,
26288     {@link Ext.container.Container#layout layout}: 'auto',
26289     {@link Ext.container.Container#items items}: [
26290         {
26291             itemId: 'p1',
26292             {@link Ext.panel.Panel#title title}: 'Panel 1',
26293             {@link Ext.Component#height height}: 150
26294         },
26295         {
26296             itemId: 'p2',
26297             {@link Ext.panel.Panel#title title}: 'Panel 2',
26298             {@link Ext.Component#height height}: 150
26299         }
26300     ]
26301 })
26302 p1 = c.{@link Ext.container.Container#getComponent getComponent}('p1'); // not the same as {@link Ext#getCmp Ext.getCmp()}
26303 p2 = p1.{@link #ownerCt}.{@link Ext.container.Container#getComponent getComponent}('p2'); // reference via a sibling
26304      * </code></pre>
26305      * <p>Also see <tt>{@link #id}</tt>, <code>{@link #query}</code>, <code>{@link #down}</code> and <code>{@link #child}</code>.</p>
26306      * <p><b>Note</b>: to access the container of an item see <tt>{@link #ownerCt}</tt>.</p>
26307      */
26308
26309     /**
26310      * This Component's owner {@link Ext.container.Container Container} (defaults to undefined, and is set automatically when
26311      * this Component is added to a Container).  Read-only.
26312      * <p><b>Note</b>: to access items within the Container see <tt>{@link #itemId}</tt>.</p>
26313      * @type Ext.Container
26314      * @property ownerCt
26315      */
26316
26317     /**
26318      * @cfg {Mixed} autoEl
26319      * <p>A tag name or {@link Ext.core.DomHelper DomHelper} spec used to create the {@link #getEl Element} which will
26320      * encapsulate this Component.</p>
26321      * <p>You do not normally need to specify this. For the base classes {@link Ext.Component} and {@link Ext.container.Container},
26322      * this defaults to <b><tt>'div'</tt></b>. The more complex Sencha classes use a more complex
26323      * DOM structure specified by their own {@link #renderTpl}s.</p>
26324      * <p>This is intended to allow the developer to create application-specific utility Components encapsulated by
26325      * different DOM elements. Example usage:</p><pre><code>
26326 {
26327     xtype: 'component',
26328     autoEl: {
26329         tag: 'img',
26330         src: 'http://www.example.com/example.jpg'
26331     }
26332 }, {
26333     xtype: 'component',
26334     autoEl: {
26335         tag: 'blockquote',
26336         html: 'autoEl is cool!'
26337     }
26338 }, {
26339     xtype: 'container',
26340     autoEl: 'ul',
26341     cls: 'ux-unordered-list',
26342     items: {
26343         xtype: 'component',
26344         autoEl: 'li',
26345         html: 'First list item'
26346     }
26347 }
26348 </code></pre>
26349      */
26350
26351     /**
26352      * @cfg {Mixed} renderTpl
26353      * <p>An {@link Ext.XTemplate XTemplate} used to create the internal structure inside this Component's
26354      * encapsulating {@link #getEl Element}.</p>
26355      * <p>You do not normally need to specify this. For the base classes {@link Ext.Component}
26356      * and {@link Ext.container.Container}, this defaults to <b><code>null</code></b> which means that they will be initially rendered
26357      * with no internal structure; they render their {@link #getEl Element} empty. The more specialized ExtJS and Touch classes
26358      * which use a more complex DOM structure, provide their own template definitions.</p>
26359      * <p>This is intended to allow the developer to create application-specific utility Components with customized
26360      * internal structure.</p>
26361      * <p>Upon rendering, any created child elements may be automatically imported into object properties using the
26362      * {@link #renderSelectors} option.</p>
26363      */
26364     renderTpl: null,
26365
26366     /**
26367      * @cfg {Object} renderSelectors
26368
26369 An object containing properties specifying {@link Ext.DomQuery DomQuery} selectors which identify child elements
26370 created by the render process.
26371
26372 After the Component's internal structure is rendered according to the {@link #renderTpl}, this object is iterated through,
26373 and the found Elements are added as properties to the Component using the `renderSelector` property name.
26374
26375 For example, a Component which rendered an image, and description into its element might use the following properties
26376 coded into its prototype:
26377
26378     renderTpl: '&lt;img src="{imageUrl}" class="x-image-component-img">&lt;div class="x-image-component-desc">{description}&gt;/div&lt;',
26379
26380     renderSelectors: {
26381         image: 'img.x-image-component-img',
26382         descEl: 'div.x-image-component-desc'
26383     }
26384
26385 After rendering, the Component would have a property <code>image</code> referencing its child `img` Element,
26386 and a property `descEl` referencing the `div` Element which contains the description.
26387
26388      * @markdown
26389      */
26390
26391     /**
26392      * @cfg {Mixed} renderTo
26393      * <p>Specify the id of the element, a DOM element or an existing Element that this component
26394      * will be rendered into.</p><div><ul>
26395      * <li><b>Notes</b> : <ul>
26396      * <div class="sub-desc">Do <u>not</u> use this option if the Component is to be a child item of
26397      * a {@link Ext.container.Container Container}. It is the responsibility of the
26398      * {@link Ext.container.Container Container}'s {@link Ext.container.Container#layout layout manager}
26399      * to render and manage its child items.</div>
26400      * <div class="sub-desc">When using this config, a call to render() is not required.</div>
26401      * </ul></li>
26402      * </ul></div>
26403      * <p>See <code>{@link #render}</code> also.</p>
26404      */
26405
26406     /**
26407      * @cfg {Boolean} frame
26408      * <p>Specify as <code>true</code> to have the Component inject framing elements within the Component at render time to
26409      * provide a graphical rounded frame around the Component content.</p>
26410      * <p>This is only necessary when running on outdated, or non standard-compliant browsers such as Microsoft's Internet Explorer
26411      * prior to version 9 which do not support rounded corners natively.</p>
26412      * <p>The extra space taken up by this framing is available from the read only property {@link #frameSize}.</p>
26413      */
26414
26415     /**
26416      * <p>Read-only property indicating the width of any framing elements which were added within the encapsulating element
26417      * to provide graphical, rounded borders. See the {@link #frame} config.</p>
26418      * <p> This is an object containing the frame width in pixels for all four sides of the Component containing
26419      * the following properties:</p><div class="mdetail-params"><ul>
26420      * <li><code>top</code> The width of the top framing element in pixels.</li>
26421      * <li><code>right</code> The width of the right framing element in pixels.</li>
26422      * <li><code>bottom</code> The width of the bottom framing element in pixels.</li>
26423      * <li><code>left</code> The width of the left framing element in pixels.</li>
26424      * </ul></div>
26425      * @property frameSize
26426      * @type {Object}
26427      */
26428
26429     /**
26430      * @cfg {String/Object} componentLayout
26431      * <p>The sizing and positioning of a Component's internal Elements is the responsibility of
26432      * the Component's layout manager which sizes a Component's internal structure in response to the Component being sized.</p>
26433      * <p>Generally, developers will not use this configuration as all provided Components which need their internal
26434      * elements sizing (Such as {@link Ext.form.field.Base input fields}) come with their own componentLayout managers.</p>
26435      * <p>The {@link Ext.layout.container.Auto default layout manager} will be used on instances of the base Ext.Component class
26436      * which simply sizes the Component's encapsulating element to the height and width specified in the {@link #setSize} method.</p>
26437      */
26438
26439     /**
26440      * @cfg {Mixed} tpl
26441      * An <bold>{@link Ext.Template}</bold>, <bold>{@link Ext.XTemplate}</bold>
26442      * or an array of strings to form an Ext.XTemplate.
26443      * Used in conjunction with the <code>{@link #data}</code> and
26444      * <code>{@link #tplWriteMode}</code> configurations.
26445      */
26446
26447     /**
26448      * @cfg {Mixed} data
26449      * The initial set of data to apply to the <code>{@link #tpl}</code> to
26450      * update the content area of the Component.
26451      */
26452
26453     /**
26454      * @cfg {String} tplWriteMode The Ext.(X)Template method to use when
26455      * updating the content area of the Component. Defaults to <code>'overwrite'</code>
26456      * (see <code>{@link Ext.XTemplate#overwrite}</code>).
26457      */
26458     tplWriteMode: 'overwrite',
26459
26460     /**
26461      * @cfg {String} baseCls
26462      * The base CSS class to apply to this components's element. This will also be prepended to
26463      * elements within this component like Panel's body will get a class x-panel-body. This means
26464      * that if you create a subclass of Panel, and you want it to get all the Panels styling for the
26465      * element and the body, you leave the baseCls x-panel and use componentCls to add specific styling for this
26466      * component.
26467      */
26468     baseCls: Ext.baseCSSPrefix + 'component',
26469
26470     /**
26471      * @cfg {String} componentCls
26472      * CSS Class to be added to a components root level element to give distinction to it
26473      * via styling.
26474      */
26475
26476     /**
26477      * @cfg {String} cls
26478      * An optional extra CSS class that will be added to this component's Element (defaults to '').  This can be
26479      * useful for adding customized styles to the component or any of its children using standard CSS rules.
26480      */
26481
26482     /**
26483      * @cfg {String} overCls
26484      * An optional extra CSS class that will be added to this component's Element when the mouse moves
26485      * over the Element, and removed when the mouse moves out. (defaults to '').  This can be
26486      * useful for adding customized 'active' or 'hover' styles to the component or any of its children using standard CSS rules.
26487      */
26488
26489     /**
26490      * @cfg {String} disabledCls
26491      * CSS class to add when the Component is disabled. Defaults to 'x-item-disabled'.
26492      */
26493     disabledCls: Ext.baseCSSPrefix + 'item-disabled',
26494
26495     /**
26496      * @cfg {String/Array} ui
26497      * A set style for a component. Can be a string or an Array of multiple strings (UIs)
26498      */
26499     ui: 'default',
26500     
26501     /**
26502      * @cfg {Array} uiCls
26503      * An array of of classNames which are currently applied to this component
26504      * @private
26505      */
26506     uiCls: [],
26507     
26508     /**
26509      * @cfg {String} style
26510      * A custom style specification to be applied to this component's Element.  Should be a valid argument to
26511      * {@link Ext.core.Element#applyStyles}.
26512      * <pre><code>
26513         new Ext.panel.Panel({
26514             title: 'Some Title',
26515             renderTo: Ext.getBody(),
26516             width: 400, height: 300,
26517             layout: 'form',
26518             items: [{
26519                 xtype: 'textarea',
26520                 style: {
26521                     width: '95%',
26522                     marginBottom: '10px'
26523                 }
26524             },
26525             new Ext.button.Button({
26526                 text: 'Send',
26527                 minWidth: '100',
26528                 style: {
26529                     marginBottom: '10px'
26530                 }
26531             })
26532             ]
26533         });
26534      </code></pre>
26535      */
26536
26537     /**
26538      * @cfg {Number} width
26539      * The width of this component in pixels.
26540      */
26541
26542     /**
26543      * @cfg {Number} height
26544      * The height of this component in pixels.
26545      */
26546
26547     /**
26548      * @cfg {Number/String} border
26549      * Specifies the border for this component. The border can be a single numeric value to apply to all sides or
26550      * it can be a CSS style specification for each style, for example: '10 5 3 10'.
26551      */
26552
26553     /**
26554      * @cfg {Number/String} padding
26555      * Specifies the padding for this component. The padding can be a single numeric value to apply to all sides or
26556      * it can be a CSS style specification for each style, for example: '10 5 3 10'.
26557      */
26558
26559     /**
26560      * @cfg {Number/String} margin
26561      * Specifies the margin for this component. The margin can be a single numeric value to apply to all sides or
26562      * it can be a CSS style specification for each style, for example: '10 5 3 10'.
26563      */
26564
26565     /**
26566      * @cfg {Boolean} hidden
26567      * Defaults to false.
26568      */
26569     hidden: false,
26570
26571     /**
26572      * @cfg {Boolean} disabled
26573      * Defaults to false.
26574      */
26575     disabled: false,
26576
26577     /**
26578      * @cfg {Boolean} draggable
26579      * Allows the component to be dragged.
26580      */
26581
26582     /**
26583      * Read-only property indicating whether or not the component can be dragged
26584      * @property draggable
26585      * @type {Boolean}
26586      */
26587     draggable: false,
26588
26589     /**
26590      * @cfg {Boolean} floating
26591      * Create the Component as a floating and use absolute positioning.
26592      * Defaults to false.
26593      */
26594     floating: false,
26595
26596     /**
26597      * @cfg {String} hideMode
26598      * A String which specifies how this Component's encapsulating DOM element will be hidden.
26599      * Values may be<div class="mdetail-params"><ul>
26600      * <li><code>'display'</code> : The Component will be hidden using the <code>display: none</code> style.</li>
26601      * <li><code>'visibility'</code> : The Component will be hidden using the <code>visibility: hidden</code> style.</li>
26602      * <li><code>'offsets'</code> : The Component will be hidden by absolutely positioning it out of the visible area of the document. This
26603      * is useful when a hidden Component must maintain measurable dimensions. Hiding using <code>display</code> results
26604      * in a Component having zero dimensions.</li></ul></div>
26605      * Defaults to <code>'display'</code>.
26606      */
26607     hideMode: 'display',
26608
26609     /**
26610      * @cfg {String} contentEl
26611      * <p>Optional. Specify an existing HTML element, or the <code>id</code> of an existing HTML element to use as the content
26612      * for this component.</p>
26613      * <ul>
26614      * <li><b>Description</b> :
26615      * <div class="sub-desc">This config option is used to take an existing HTML element and place it in the layout element
26616      * of a new component (it simply moves the specified DOM element <i>after the Component is rendered</i> to use as the content.</div></li>
26617      * <li><b>Notes</b> :
26618      * <div class="sub-desc">The specified HTML element is appended to the layout element of the component <i>after any configured
26619      * {@link #html HTML} has been inserted</i>, and so the document will not contain this element at the time the {@link #render} event is fired.</div>
26620      * <div class="sub-desc">The specified HTML element used will not participate in any <code><b>{@link Ext.container.Container#layout layout}</b></code>
26621      * scheme that the Component may use. It is just HTML. Layouts operate on child <code><b>{@link Ext.container.Container#items items}</b></code>.</div>
26622      * <div class="sub-desc">Add either the <code>x-hidden</code> or the <code>x-hide-display</code> CSS class to
26623      * prevent a brief flicker of the content before it is rendered to the panel.</div></li>
26624      * </ul>
26625      */
26626
26627     /**
26628      * @cfg {String/Object} html
26629      * An HTML fragment, or a {@link Ext.core.DomHelper DomHelper} specification to use as the layout element
26630      * content (defaults to ''). The HTML content is added after the component is rendered,
26631      * so the document will not contain this HTML at the time the {@link #render} event is fired.
26632      * This content is inserted into the body <i>before</i> any configured {@link #contentEl} is appended.
26633      */
26634
26635     /**
26636      * @cfg {String} styleHtmlContent
26637      * True to automatically style the html inside the content target of this component (body for panels).
26638      * Defaults to false.
26639      */
26640     styleHtmlContent: false,
26641
26642     /**
26643      * @cfg {String} styleHtmlCls
26644      * The class that is added to the content target when you set styleHtmlContent to true.
26645      * Defaults to 'x-html'
26646      */
26647     styleHtmlCls: Ext.baseCSSPrefix + 'html',
26648
26649     /**
26650      * @cfg {Number} minHeight
26651      * <p>The minimum value in pixels which this Component will set its height to.</p>
26652      * <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
26653      */
26654     /**
26655      * @cfg {Number} minWidth
26656      * <p>The minimum value in pixels which this Component will set its width to.</p>
26657      * <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
26658      */
26659     /**
26660      * @cfg {Number} maxHeight
26661      * <p>The maximum value in pixels which this Component will set its height to.</p>
26662      * <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
26663      */
26664     /**
26665      * @cfg {Number} maxWidth
26666      * <p>The maximum value in pixels which this Component will set its width to.</p>
26667      * <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
26668      */
26669
26670     /**
26671      * @cfg {Ext.ComponentLoader/Object} loader
26672      * A configuration object or an instance of a {@link Ext.ComponentLoader} to load remote
26673      * content for this Component.
26674      */
26675
26676      // @private
26677      allowDomMove: true,
26678
26679      /**
26680       * @cfg {Boolean} autoShow True to automatically show the component upon creation.
26681       * This config option may only be used for {@link #floating} components or components
26682       * that use {@link #autoRender}. Defaults to <tt>false</tt>.
26683       */
26684      autoShow: false,
26685
26686     /**
26687      * @cfg {Mixed} autoRender
26688      * <p>This config is intended mainly for {@link #floating} Components which may or may not be shown. Instead
26689      * of using {@link #renderTo} in the configuration, and rendering upon construction, this allows a Component
26690      * to render itself upon first <i>{@link #show}</i>.</p>
26691      * <p>Specify as <code>true</code> to have this Component render to the document body upon first show.</p>
26692      * <p>Specify as an element, or the ID of an element to have this Component render to a specific element upon first show.</p>
26693      * <p><b>This defaults to <code>true</code> for the {@link Ext.window.Window Window} class.</b></p>
26694      */
26695      autoRender: false,
26696
26697      needsLayout: false,
26698
26699     /**
26700      * @cfg {Object/Array} plugins
26701      * An object or array of objects that will provide custom functionality for this component.  The only
26702      * requirement for a valid plugin is that it contain an init method that accepts a reference of type Ext.Component.
26703      * When a component is created, if any plugins are available, the component will call the init method on each
26704      * plugin, passing a reference to itself.  Each plugin can then call methods or respond to events on the
26705      * component as needed to provide its functionality.
26706      */
26707
26708     /**
26709      * Read-only property indicating whether or not the component has been rendered.
26710      * @property rendered
26711      * @type {Boolean}
26712      */
26713     rendered: false,
26714
26715     weight: 0,
26716
26717     trimRe: /^\s+|\s+$/g,
26718     spacesRe: /\s+/,
26719     
26720     
26721     /**
26722      * This is an internal flag that you use when creating custom components.
26723      * By default this is set to true which means that every component gets a mask when its disabled.
26724      * Components like FieldContainer, FieldSet, Field, Button, Tab override this property to false
26725      * since they want to implement custom disable logic.
26726      * @property maskOnDisable
26727      * @type {Boolean}
26728      */     
26729     maskOnDisable: true,
26730
26731     constructor : function(config) {
26732         var me = this,
26733             i, len;
26734
26735         config = config || {};
26736         me.initialConfig = config;
26737         Ext.apply(me, config);
26738
26739         me.addEvents(
26740             /**
26741              * @event beforeactivate
26742              * Fires before a Component has been visually activated.
26743              * Returning false from an event listener can prevent the activate
26744              * from occurring.
26745              * @param {Ext.Component} this
26746              */
26747              'beforeactivate',
26748             /**
26749              * @event activate
26750              * Fires after a Component has been visually activated.
26751              * @param {Ext.Component} this
26752              */
26753              'activate',
26754             /**
26755              * @event beforedeactivate
26756              * Fires before a Component has been visually deactivated.
26757              * Returning false from an event listener can prevent the deactivate
26758              * from occurring.
26759              * @param {Ext.Component} this
26760              */
26761              'beforedeactivate',
26762             /**
26763              * @event deactivate
26764              * Fires after a Component has been visually deactivated.
26765              * @param {Ext.Component} this
26766              */
26767              'deactivate',
26768             /**
26769              * @event added
26770              * Fires after a Component had been added to a Container.
26771              * @param {Ext.Component} this
26772              * @param {Ext.container.Container} container Parent Container
26773              * @param {Number} pos position of Component
26774              */
26775              'added',
26776             /**
26777              * @event disable
26778              * Fires after the component is disabled.
26779              * @param {Ext.Component} this
26780              */
26781              'disable',
26782             /**
26783              * @event enable
26784              * Fires after the component is enabled.
26785              * @param {Ext.Component} this
26786              */
26787              'enable',
26788             /**
26789              * @event beforeshow
26790              * Fires before the component is shown when calling the {@link #show} method.
26791              * Return false from an event handler to stop the show.
26792              * @param {Ext.Component} this
26793              */
26794              'beforeshow',
26795             /**
26796              * @event show
26797              * Fires after the component is shown when calling the {@link #show} method.
26798              * @param {Ext.Component} this
26799              */
26800              'show',
26801             /**
26802              * @event beforehide
26803              * Fires before the component is hidden when calling the {@link #hide} method.
26804              * Return false from an event handler to stop the hide.
26805              * @param {Ext.Component} this
26806              */
26807              'beforehide',
26808             /**
26809              * @event hide
26810              * Fires after the component is hidden.
26811              * Fires after the component is hidden when calling the {@link #hide} method.
26812              * @param {Ext.Component} this
26813              */
26814              'hide',
26815             /**
26816              * @event removed
26817              * Fires when a component is removed from an Ext.container.Container
26818              * @param {Ext.Component} this
26819              * @param {Ext.container.Container} ownerCt Container which holds the component
26820              */
26821              'removed',
26822             /**
26823              * @event beforerender
26824              * Fires before the component is {@link #rendered}. Return false from an
26825              * event handler to stop the {@link #render}.
26826              * @param {Ext.Component} this
26827              */
26828              'beforerender',
26829             /**
26830              * @event render
26831              * Fires after the component markup is {@link #rendered}.
26832              * @param {Ext.Component} this
26833              */
26834              'render',
26835             /**
26836              * @event afterrender
26837              * <p>Fires after the component rendering is finished.</p>
26838              * <p>The afterrender event is fired after this Component has been {@link #rendered}, been postprocesed
26839              * by any afterRender method defined for the Component.</p>
26840              * @param {Ext.Component} this
26841              */
26842              'afterrender',
26843             /**
26844              * @event beforedestroy
26845              * Fires before the component is {@link #destroy}ed. Return false from an event handler to stop the {@link #destroy}.
26846              * @param {Ext.Component} this
26847              */
26848              'beforedestroy',
26849             /**
26850              * @event destroy
26851              * Fires after the component is {@link #destroy}ed.
26852              * @param {Ext.Component} this
26853              */
26854              'destroy',
26855             /**
26856              * @event resize
26857              * Fires after the component is resized.
26858              * @param {Ext.Component} this
26859              * @param {Number} adjWidth The box-adjusted width that was set
26860              * @param {Number} adjHeight The box-adjusted height that was set
26861              */
26862              'resize',
26863             /**
26864              * @event move
26865              * Fires after the component is moved.
26866              * @param {Ext.Component} this
26867              * @param {Number} x The new x position
26868              * @param {Number} y The new y position
26869              */
26870              'move'
26871         );
26872
26873         me.getId();
26874
26875         me.mons = [];
26876         me.additionalCls = [];
26877         me.renderData = me.renderData || {};
26878         me.renderSelectors = me.renderSelectors || {};
26879
26880         if (me.plugins) {
26881             me.plugins = [].concat(me.plugins);
26882             for (i = 0, len = me.plugins.length; i < len; i++) {
26883                 me.plugins[i] = me.constructPlugin(me.plugins[i]);
26884             }
26885         }
26886         
26887         me.initComponent();
26888
26889         // ititComponent gets a chance to change the id property before registering
26890         Ext.ComponentManager.register(me);
26891
26892         // Dont pass the config so that it is not applied to 'this' again
26893         me.mixins.observable.constructor.call(me);
26894         me.mixins.state.constructor.call(me, config);
26895
26896         // Move this into Observable?
26897         if (me.plugins) {
26898             me.plugins = [].concat(me.plugins);
26899             for (i = 0, len = me.plugins.length; i < len; i++) {
26900                 me.plugins[i] = me.initPlugin(me.plugins[i]);
26901             }
26902         }
26903
26904         me.loader = me.getLoader();
26905
26906         if (me.renderTo) {
26907             me.render(me.renderTo);
26908         }
26909
26910         if (me.autoShow) {
26911             me.show();
26912         }
26913         
26914         if (Ext.isDefined(me.disabledClass)) {
26915             if (Ext.isDefined(Ext.global.console)) {
26916                 Ext.global.console.warn('Ext.Component: disabledClass has been deprecated. Please use disabledCls.');
26917             }
26918             me.disabledCls = me.disabledClass;
26919             delete me.disabledClass;
26920         }
26921     },
26922
26923     initComponent: Ext.emptyFn,
26924
26925     show: Ext.emptyFn,
26926
26927     animate: function(animObj) {
26928         var me = this,
26929             to;
26930
26931         animObj = animObj || {};
26932         to = animObj.to || {};
26933
26934         if (Ext.fx.Manager.hasFxBlock(me.id)) {
26935             return me;
26936         }
26937         // Special processing for animating Component dimensions.
26938         if (!animObj.dynamic && (to.height || to.width)) {
26939             var curWidth = me.getWidth(),
26940                 w = curWidth,
26941                 curHeight = me.getHeight(),
26942                 h = curHeight,
26943                 needsResize = false;
26944
26945             if (to.height && to.height > curHeight) {
26946                 h = to.height;
26947                 needsResize = true;
26948             }
26949             if (to.width && to.width > curWidth) {
26950                 w = to.width;
26951                 needsResize = true;
26952             }
26953
26954             // If any dimensions are being increased, we must resize the internal structure
26955             // of the Component, but then clip it by sizing its encapsulating element back to original dimensions.
26956             // The animation will then progressively reveal the larger content.
26957             if (needsResize) {
26958                 var clearWidth = !Ext.isNumber(me.width),
26959                     clearHeight = !Ext.isNumber(me.height);
26960
26961                 me.componentLayout.childrenChanged = true;
26962                 me.setSize(w, h, me.ownerCt);
26963                 me.el.setSize(curWidth, curHeight);
26964                 if (clearWidth) {
26965                     delete me.width;
26966                 }
26967                 if (clearHeight) {
26968                     delete me.height;
26969                 }
26970             }
26971         }
26972         return me.mixins.animate.animate.apply(me, arguments);
26973     },
26974
26975     /**
26976      * <p>This method finds the topmost active layout who's processing will eventually determine the size and position of this
26977      * Component.<p>
26978      * <p>This method is useful when dynamically adding Components into Containers, and some processing must take place after the
26979      * final sizing and positioning of the Component has been performed.</p>
26980      * @returns
26981      */
26982     findLayoutController: function() {
26983         return this.findParentBy(function(c) {
26984             // Return true if we are at the root of the Container tree
26985             // or this Container's layout is busy but the next one up is not.
26986             return !c.ownerCt || (c.layout.layoutBusy && !c.ownerCt.layout.layoutBusy);
26987         });
26988     },
26989
26990     onShow : function() {
26991         // Layout if needed
26992         var needsLayout = this.needsLayout;
26993         if (Ext.isObject(needsLayout)) {
26994             this.doComponentLayout(needsLayout.width, needsLayout.height, needsLayout.isSetSize, needsLayout.ownerCt);
26995         }
26996     },
26997
26998     constructPlugin: function(plugin) {
26999         if (plugin.ptype && typeof plugin.init != 'function') {
27000             plugin.cmp = this;
27001             plugin = Ext.PluginManager.create(plugin);
27002         }
27003         else if (typeof plugin == 'string') {
27004             plugin = Ext.PluginManager.create({
27005                 ptype: plugin,
27006                 cmp: this
27007             });
27008         }
27009         return plugin;
27010     },
27011
27012
27013     // @private
27014     initPlugin : function(plugin) {
27015         plugin.init(this);
27016
27017         return plugin;
27018     },
27019
27020     /**
27021      * Handles autoRender.
27022      * Floating Components may have an ownerCt. If they are asking to be constrained, constrain them within that
27023      * ownerCt, and have their z-index managed locally. Floating Components are always rendered to document.body
27024      */
27025     doAutoRender: function() {
27026         var me = this;
27027         if (me.floating) {
27028             me.render(document.body);
27029         } else {
27030             me.render(Ext.isBoolean(me.autoRender) ? Ext.getBody() : me.autoRender);
27031         }
27032     },
27033
27034     // @private
27035     render : function(container, position) {
27036         var me = this;
27037
27038         if (!me.rendered && me.fireEvent('beforerender', me) !== false) {
27039             // If this.el is defined, we want to make sure we are dealing with
27040             // an Ext Element.
27041             if (me.el) {
27042                 me.el = Ext.get(me.el);
27043             }
27044
27045             // Perform render-time processing for floating Components
27046             if (me.floating) {
27047                 me.onFloatRender();
27048             }
27049
27050             container = me.initContainer(container);
27051
27052             me.onRender(container, position);
27053
27054             // Tell the encapsulating element to hide itself in the way the Component is configured to hide
27055             // This means DISPLAY, VISIBILITY or OFFSETS.
27056             me.el.setVisibilityMode(Ext.core.Element[me.hideMode.toUpperCase()]);
27057
27058             if (me.overCls) {
27059                 me.el.hover(me.addOverCls, me.removeOverCls, me);
27060             }
27061
27062             me.fireEvent('render', me);
27063
27064             me.initContent();
27065
27066             me.afterRender(container);
27067             me.fireEvent('afterrender', me);
27068
27069             me.initEvents();
27070
27071             if (me.hidden) {
27072                 // Hiding during the render process should not perform any ancillary
27073                 // actions that the full hide process does; It is not hiding, it begins in a hidden state.'
27074                 // So just make the element hidden according to the configured hideMode
27075                 me.el.hide();
27076             }
27077
27078             if (me.disabled) {
27079                 // pass silent so the event doesn't fire the first time.
27080                 me.disable(true);
27081             }
27082         }
27083         return me;
27084     },
27085
27086     // @private
27087     onRender : function(container, position) {
27088         var me = this,
27089             el = me.el,
27090             cls = me.initCls(),
27091             styles = me.initStyles(),
27092             renderTpl, renderData, i;
27093
27094         position = me.getInsertPosition(position);
27095
27096         if (!el) {
27097             if (position) {
27098                 el = Ext.core.DomHelper.insertBefore(position, me.getElConfig(), true);
27099             }
27100             else {
27101                 el = Ext.core.DomHelper.append(container, me.getElConfig(), true);
27102             }
27103         }
27104         else if (me.allowDomMove !== false) {
27105             if (position) {
27106                 container.dom.insertBefore(el.dom, position);
27107             } else {
27108                 container.dom.appendChild(el.dom);
27109             }
27110         }
27111
27112         if (Ext.scopeResetCSS && !me.ownerCt) {
27113             // If this component's el is the body element, we add the reset class to the html tag
27114             if (el.dom == Ext.getBody().dom) {
27115                 el.parent().addCls(Ext.baseCSSPrefix + 'reset');
27116             }
27117             else {
27118                 // Else we wrap this element in an element that adds the reset class.
27119                 me.resetEl = el.wrap({
27120                     cls: Ext.baseCSSPrefix + 'reset'
27121                 });
27122             }
27123         }
27124
27125         el.addCls(cls);
27126         el.setStyle(styles);
27127
27128         // Here we check if the component has a height set through style or css.
27129         // If it does then we set the this.height to that value and it won't be
27130         // considered an auto height component
27131         // if (this.height === undefined) {
27132         //     var height = el.getHeight();
27133         //     // This hopefully means that the panel has an explicit height set in style or css
27134         //     if (height - el.getPadding('tb') - el.getBorderWidth('tb') > 0) {
27135         //         this.height = height;
27136         //     }
27137         // }
27138
27139         me.el = el;
27140         
27141         me.rendered = true;
27142         me.addUIToElement(true);
27143         //loop through all exisiting uiCls and update the ui in them
27144         for (i = 0; i < me.uiCls.length; i++) {
27145             me.addUIClsToElement(me.uiCls[i], true);
27146         }
27147         me.rendered = false;
27148         me.initFrame();
27149
27150         renderTpl = me.initRenderTpl();
27151         if (renderTpl) {
27152             renderData = me.initRenderData();
27153             renderTpl.append(me.getTargetEl(), renderData);
27154         }
27155
27156         me.applyRenderSelectors();
27157         
27158         me.rendered = true;
27159         
27160         me.setUI(me.ui);
27161     },
27162
27163     // @private
27164     afterRender : function() {
27165         var me = this,
27166             pos,
27167             xy;
27168
27169         me.getComponentLayout();
27170
27171         // Set the size if a size is configured, or if this is the outermost Container
27172         if (!me.ownerCt || (me.height || me.width)) {
27173             me.setSize(me.width, me.height);
27174         }
27175
27176         // For floaters, calculate x and y if they aren't defined by aligning
27177         // the sized element to the center of either the the container or the ownerCt
27178         if (me.floating && (me.x === undefined || me.y === undefined)) {
27179             if (me.floatParent) {
27180                 xy = me.el.getAlignToXY(me.floatParent.getTargetEl(), 'c-c');
27181                 pos = me.floatParent.getTargetEl().translatePoints(xy[0], xy[1]);
27182             } else {
27183                 xy = me.el.getAlignToXY(me.container, 'c-c');
27184                 pos = me.container.translatePoints(xy[0], xy[1]);
27185             }
27186             me.x = me.x === undefined ? pos.left: me.x;
27187             me.y = me.y === undefined ? pos.top: me.y;
27188         }
27189
27190         if (Ext.isDefined(me.x) || Ext.isDefined(me.y)) {
27191             me.setPosition(me.x, me.y);
27192         }
27193
27194         if (me.styleHtmlContent) {
27195             me.getTargetEl().addCls(me.styleHtmlCls);
27196         }
27197     },
27198
27199     frameCls: Ext.baseCSSPrefix + 'frame',
27200
27201     frameTpl: [
27202         '<tpl if="top">',
27203             '<tpl if="left"><div class="{frameCls}-tl {baseCls}-tl {baseCls}-{ui}-tl<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tl</tpl></tpl>" style="background-position: {tl}; padding-left: {frameWidth}px" role="presentation"></tpl>',
27204                 '<tpl if="right"><div class="{frameCls}-tr {baseCls}-tr {baseCls}-{ui}-tr<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tr</tpl></tpl>" style="background-position: {tr}; padding-right: {frameWidth}px" role="presentation"></tpl>',
27205                     '<div class="{frameCls}-tc {baseCls}-tc {baseCls}-{ui}-tc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tc</tpl></tpl>" style="background-position: {tc}; height: {frameWidth}px" role="presentation"></div>',
27206                 '<tpl if="right"></div></tpl>',
27207             '<tpl if="left"></div></tpl>',
27208         '</tpl>',
27209         '<tpl if="left"><div class="{frameCls}-ml {baseCls}-ml {baseCls}-{ui}-ml<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-ml</tpl></tpl>" style="background-position: {ml}; padding-left: {frameWidth}px" role="presentation"></tpl>',
27210             '<tpl if="right"><div class="{frameCls}-mr {baseCls}-mr {baseCls}-{ui}-mr<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-mr</tpl></tpl>" style="background-position: {mr}; padding-right: {frameWidth}px" role="presentation"></tpl>',
27211                 '<div class="{frameCls}-mc {baseCls}-mc {baseCls}-{ui}-mc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-mc</tpl></tpl>" role="presentation"></div>',
27212             '<tpl if="right"></div></tpl>',
27213         '<tpl if="left"></div></tpl>',
27214         '<tpl if="bottom">',
27215             '<tpl if="left"><div class="{frameCls}-bl {baseCls}-bl {baseCls}-{ui}-bl<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-bl</tpl></tpl>" style="background-position: {bl}; padding-left: {frameWidth}px" role="presentation"></tpl>',
27216                 '<tpl if="right"><div class="{frameCls}-br {baseCls}-br {baseCls}-{ui}-br<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-br</tpl></tpl>" style="background-position: {br}; padding-right: {frameWidth}px" role="presentation"></tpl>',
27217                     '<div class="{frameCls}-bc {baseCls}-bc {baseCls}-{ui}-bc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-bc</tpl></tpl>" style="background-position: {bc}; height: {frameWidth}px" role="presentation"></div>',
27218                 '<tpl if="right"></div></tpl>',
27219             '<tpl if="left"></div></tpl>',
27220         '</tpl>'
27221     ],
27222
27223     frameTableTpl: [
27224         '<table><tbody>',
27225             '<tpl if="top">',
27226                 '<tr>',
27227                     '<tpl if="left"><td class="{frameCls}-tl {baseCls}-tl {baseCls}-{ui}-tl<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tl</tpl></tpl>" style="background-position: {tl}; padding-left:{frameWidth}px" role="presentation"></td></tpl>',
27228                     '<td class="{frameCls}-tc {baseCls}-tc {baseCls}-{ui}-tc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tc</tpl></tpl>" style="background-position: {tc}; height: {frameWidth}px" role="presentation"></td>',
27229                     '<tpl if="right"><td class="{frameCls}-tr {baseCls}-tr {baseCls}-{ui}-tr<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-tr</tpl></tpl>" style="background-position: {tr}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
27230                 '</tr>',
27231             '</tpl>',
27232             '<tr>',
27233                 '<tpl if="left"><td class="{frameCls}-ml {baseCls}-ml {baseCls}-{ui}-ml<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-ml</tpl></tpl>" style="background-position: {ml}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
27234                 '<td class="{frameCls}-mc {baseCls}-mc {baseCls}-{ui}-mc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-mc</tpl></tpl>" style="background-position: 0 0;" role="presentation"></td>',
27235                 '<tpl if="right"><td class="{frameCls}-mr {baseCls}-mr {baseCls}-{ui}-mr<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-mr</tpl></tpl>" style="background-position: {mr}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
27236             '</tr>',
27237             '<tpl if="bottom">',
27238                 '<tr>',
27239                     '<tpl if="left"><td class="{frameCls}-bl {baseCls}-bl {baseCls}-{ui}-bl<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-bl</tpl></tpl>" style="background-position: {bl}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
27240                     '<td class="{frameCls}-bc {baseCls}-bc {baseCls}-{ui}-bc<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-bc</tpl></tpl>" style="background-position: {bc}; height: {frameWidth}px" role="presentation"></td>',
27241                     '<tpl if="right"><td class="{frameCls}-br {baseCls}-br {baseCls}-{ui}-br<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-{parent.ui}-{.}-br</tpl></tpl>" style="background-position: {br}; padding-left: {frameWidth}px" role="presentation"></td></tpl>',
27242                 '</tr>',
27243             '</tpl>',
27244         '</tbody></table>'
27245     ],
27246     
27247     /**
27248      * @private
27249      */
27250     initFrame : function() {
27251         if (Ext.supports.CSS3BorderRadius) {
27252             return false;
27253         }
27254         
27255         var me = this,
27256             frameInfo = me.getFrameInfo(),
27257             frameWidth = frameInfo.width,
27258             frameTpl = me.getFrameTpl(frameInfo.table);
27259                         
27260         if (me.frame) {
27261             // Here we render the frameTpl to this component. This inserts the 9point div or the table framing.
27262             frameTpl.insertFirst(me.el, Ext.apply({}, {
27263                 ui:         me.ui,
27264                 uiCls:      me.uiCls,
27265                 frameCls:   me.frameCls,
27266                 baseCls:    me.baseCls,
27267                 frameWidth: frameWidth,
27268                 top:        !!frameInfo.top,
27269                 left:       !!frameInfo.left,
27270                 right:      !!frameInfo.right,
27271                 bottom:     !!frameInfo.bottom
27272             }, me.getFramePositions(frameInfo)));
27273
27274             // The frameBody is returned in getTargetEl, so that layouts render items to the correct target.=
27275             me.frameBody = me.el.down('.' + me.frameCls + '-mc');
27276             
27277             // Add the render selectors for each of the frame elements
27278             Ext.apply(me.renderSelectors, {
27279                 frameTL: '.' + me.baseCls + '-tl',
27280                 frameTC: '.' + me.baseCls + '-tc',
27281                 frameTR: '.' + me.baseCls + '-tr',
27282                 frameML: '.' + me.baseCls + '-ml',
27283                 frameMC: '.' + me.baseCls + '-mc',
27284                 frameMR: '.' + me.baseCls + '-mr',
27285                 frameBL: '.' + me.baseCls + '-bl',
27286                 frameBC: '.' + me.baseCls + '-bc',
27287                 frameBR: '.' + me.baseCls + '-br'
27288             });
27289         }
27290     },
27291     
27292     updateFrame: function() {
27293         if (Ext.supports.CSS3BorderRadius) {
27294             return false;
27295         }
27296         
27297         var me = this,
27298             wasTable = this.frameSize && this.frameSize.table,
27299             oldFrameTL = this.frameTL,
27300             oldFrameBL = this.frameBL,
27301             oldFrameML = this.frameML,
27302             oldFrameMC = this.frameMC,
27303             newMCClassName;
27304         
27305         this.initFrame();
27306         
27307         if (oldFrameMC) {
27308             if (me.frame) {                
27309                 // Reapply render selectors
27310                 delete me.frameTL;
27311                 delete me.frameTC;
27312                 delete me.frameTR;
27313                 delete me.frameML;
27314                 delete me.frameMC;
27315                 delete me.frameMR;
27316                 delete me.frameBL;
27317                 delete me.frameBC;
27318                 delete me.frameBR;    
27319                 this.applyRenderSelectors();
27320                 
27321                 // Store the class names set on the new mc
27322                 newMCClassName = this.frameMC.dom.className;
27323                 
27324                 // Replace the new mc with the old mc
27325                 oldFrameMC.insertAfter(this.frameMC);
27326                 this.frameMC.remove();
27327                 
27328                 // Restore the reference to the old frame mc as the framebody
27329                 this.frameBody = this.frameMC = oldFrameMC;
27330                 
27331                 // Apply the new mc classes to the old mc element
27332                 oldFrameMC.dom.className = newMCClassName;
27333                 
27334                 // Remove the old framing
27335                 if (wasTable) {
27336                     me.el.query('> table')[1].remove();
27337                 }                                
27338                 else {
27339                     if (oldFrameTL) {
27340                         oldFrameTL.remove();
27341                     }
27342                     if (oldFrameBL) {
27343                         oldFrameBL.remove();
27344                     }
27345                     oldFrameML.remove();
27346                 }
27347             }
27348             else {
27349                 // We were framed but not anymore. Move all content from the old frame to the body
27350                 
27351             }
27352         }
27353         else if (me.frame) {
27354             this.applyRenderSelectors();
27355         }
27356     },
27357     
27358     getFrameInfo: function() {
27359         if (Ext.supports.CSS3BorderRadius) {
27360             return false;
27361         }
27362         
27363         var me = this,
27364             left = me.el.getStyle('background-position-x'),
27365             top = me.el.getStyle('background-position-y'),
27366             info, frameInfo = false, max;
27367
27368         // Some browsers dont support background-position-x and y, so for those
27369         // browsers let's split background-position into two parts.
27370         if (!left && !top) {
27371             info = me.el.getStyle('background-position').split(' ');
27372             left = info[0];
27373             top = info[1];
27374         }
27375         
27376         // We actually pass a string in the form of '[type][tl][tr]px [type][br][bl]px' as
27377         // the background position of this.el from the css to indicate to IE that this component needs
27378         // framing. We parse it here and change the markup accordingly.
27379         if (parseInt(left, 10) >= 1000000 && parseInt(top, 10) >= 1000000) {
27380             max = Math.max;
27381             
27382             frameInfo = {
27383                 // Table markup starts with 110, div markup with 100.
27384                 table: left.substr(0, 3) == '110',
27385                 
27386                 // Determine if we are dealing with a horizontal or vertical component
27387                 vertical: top.substr(0, 3) == '110',
27388                 
27389                 // Get and parse the different border radius sizes
27390                 top:    max(left.substr(3, 2), left.substr(5, 2)),
27391                 right:  max(left.substr(5, 2), top.substr(3, 2)),
27392                 bottom: max(top.substr(3, 2), top.substr(5, 2)),
27393                 left:   max(top.substr(5, 2), left.substr(3, 2))
27394             };
27395             
27396             frameInfo.width = max(frameInfo.top, frameInfo.right, frameInfo.bottom, frameInfo.left);
27397
27398             // Just to be sure we set the background image of the el to none.
27399             me.el.setStyle('background-image', 'none');
27400         }        
27401         
27402         // This happens when you set frame: true explicitly without using the x-frame mixin in sass.
27403         // This way IE can't figure out what sizes to use and thus framing can't work.
27404         if (me.frame === true && !frameInfo) {
27405             Ext.Error.raise("You have set frame: true explicity on this component while it doesn't have any " +
27406                             "framing defined in the CSS template. In this case IE can't figure out what sizes " +
27407                             "to use and thus framing on this component will be disabled.");
27408         }
27409         
27410         me.frame = me.frame || !!frameInfo;
27411         me.frameSize = frameInfo || false;
27412         
27413         return frameInfo;
27414     },
27415     
27416     getFramePositions: function(frameInfo) {
27417         var me = this,
27418             frameWidth = frameInfo.width,
27419             dock = me.dock,
27420             positions, tc, bc, ml, mr;
27421             
27422         if (frameInfo.vertical) {
27423             tc = '0 -' + (frameWidth * 0) + 'px';
27424             bc = '0 -' + (frameWidth * 1) + 'px';
27425             
27426             if (dock && dock == "right") {
27427                 tc = 'right -' + (frameWidth * 0) + 'px';
27428                 bc = 'right -' + (frameWidth * 1) + 'px';
27429             }
27430             
27431             positions = {
27432                 tl: '0 -' + (frameWidth * 0) + 'px',
27433                 tr: '0 -' + (frameWidth * 1) + 'px',
27434                 bl: '0 -' + (frameWidth * 2) + 'px',
27435                 br: '0 -' + (frameWidth * 3) + 'px',
27436
27437                 ml: '-' + (frameWidth * 1) + 'px 0',
27438                 mr: 'right 0',
27439
27440                 tc: tc,
27441                 bc: bc
27442             };
27443         } else {
27444             ml = '-' + (frameWidth * 0) + 'px 0';
27445             mr = 'right 0';
27446             
27447             if (dock && dock == "bottom") {
27448                 ml = 'left bottom';
27449                 mr = 'right bottom';
27450             }
27451             
27452             positions = {
27453                 tl: '0 -' + (frameWidth * 2) + 'px',
27454                 tr: 'right -' + (frameWidth * 3) + 'px',
27455                 bl: '0 -' + (frameWidth * 4) + 'px',
27456                 br: 'right -' + (frameWidth * 5) + 'px',
27457
27458                 ml: ml,
27459                 mr: mr,
27460
27461                 tc: '0 -' + (frameWidth * 0) + 'px',
27462                 bc: '0 -' + (frameWidth * 1) + 'px'
27463             };
27464         }
27465         
27466         return positions;
27467     },
27468     
27469     /**
27470      * @private
27471      */
27472     getFrameTpl : function(table) {
27473         return table ? this.getTpl('frameTableTpl') : this.getTpl('frameTpl');
27474     },
27475
27476     /**
27477      * <p>Creates an array of class names from the configurations to add to this Component's <code>el</code> on render.</p>
27478      * <p>Private, but (possibly) used by ComponentQuery for selection by class name if Component is not rendered.</p>
27479      * @return {Array} An array of class names with which the Component's element will be rendered.
27480      * @private
27481      */
27482     initCls: function() {
27483         var me = this,
27484             cls = [];
27485
27486         cls.push(me.baseCls);
27487
27488         if (Ext.isDefined(me.cmpCls)) {
27489             if (Ext.isDefined(Ext.global.console)) {
27490                 Ext.global.console.warn('Ext.Component: cmpCls has been deprecated. Please use componentCls.');
27491             }
27492             me.componentCls = me.cmpCls;
27493             delete me.cmpCls;
27494         }
27495
27496         if (me.componentCls) {
27497             cls.push(me.componentCls);
27498         } else {
27499             me.componentCls = me.baseCls;
27500         }
27501         if (me.cls) {
27502             cls.push(me.cls);
27503             delete me.cls;
27504         }
27505
27506         return cls.concat(me.additionalCls);
27507     },
27508     
27509     /**
27510      * Sets the UI for the component. This will remove any existing UIs on the component. It will also
27511      * loop through any uiCls set on the component and rename them so they include the new UI
27512      * @param {String} ui The new UI for the component
27513      */
27514     setUI: function(ui) {
27515         var me = this,
27516             oldUICls = Ext.Array.clone(me.uiCls),
27517             newUICls = [],
27518             cls,
27519             i;
27520         
27521         //loop through all exisiting uiCls and update the ui in them
27522         for (i = 0; i < oldUICls.length; i++) {
27523             cls = oldUICls[i];
27524             
27525             me.removeClsWithUI(cls);
27526             newUICls.push(cls);
27527         }
27528         
27529         //remove the UI from the element
27530         me.removeUIFromElement();
27531         
27532         //set the UI
27533         me.ui = ui;
27534         
27535         //add the new UI to the elemend
27536         me.addUIToElement();
27537         
27538         //loop through all exisiting uiCls and update the ui in them
27539         for (i = 0; i < newUICls.length; i++) {
27540             cls = newUICls[i];
27541             
27542             me.addClsWithUI(cls);
27543         }
27544     },
27545     
27546     /**
27547      * Adds a cls to the uiCls array, which will also call {@link #addUIClsToElement} and adds
27548      * to all elements of this component.
27549      * @param {String/Array} cls A string or an array of strings to add to the uiCls
27550      */
27551     addClsWithUI: function(cls) {
27552         var me = this,
27553             i;
27554         
27555         if (!Ext.isArray(cls)) {
27556             cls = [cls];
27557         }
27558         
27559         for (i = 0; i < cls.length; i++) {
27560             if (cls[i] && !me.hasUICls(cls[i])) {
27561                 me.uiCls = Ext.Array.clone(me.uiCls);
27562                 me.uiCls.push(cls[i]);
27563                 me.addUIClsToElement(cls[i]);
27564             }
27565         }
27566     },
27567     
27568     /**
27569      * Removes a cls to the uiCls array, which will also call {@link #removeUIClsToElement} and removes
27570      * it from all elements of this component.
27571      * @param {String/Array} cls A string or an array of strings to remove to the uiCls
27572      */
27573     removeClsWithUI: function(cls) {
27574         var me = this,
27575             i;
27576         
27577         if (!Ext.isArray(cls)) {
27578             cls = [cls];
27579         }
27580         
27581         for (i = 0; i < cls.length; i++) {
27582             if (cls[i] && me.hasUICls(cls[i])) {
27583                 me.uiCls = Ext.Array.remove(me.uiCls, cls[i]);
27584                 me.removeUIClsFromElement(cls[i]);
27585             }
27586         }
27587     },
27588     
27589     /**
27590      * Checks if there is currently a specified uiCls
27591      * @param {String} cls The cls to check
27592      */
27593     hasUICls: function(cls) {
27594         var me = this,
27595             uiCls = me.uiCls || [];
27596         
27597         return Ext.Array.contains(uiCls, cls);
27598     },
27599     
27600     /**
27601      * Method which adds a specified UI + uiCls to the components element.
27602      * Can be overridden to remove the UI from more than just the components element.
27603      * @param {String} ui The UI to remove from the element
27604      * @private
27605      */
27606     addUIClsToElement: function(cls, force) {
27607         var me = this;
27608         
27609         me.addCls(Ext.baseCSSPrefix + cls);
27610         me.addCls(me.baseCls + '-' + cls);
27611         me.addCls(me.baseCls + '-' + me.ui + '-' + cls);
27612         
27613         if (!force && me.rendered && me.frame && !Ext.supports.CSS3BorderRadius) {
27614             // define each element of the frame
27615             var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
27616                 i, el;
27617             
27618             // loop through each of them, and if they are defined add the ui
27619             for (i = 0; i < els.length; i++) {
27620                 el = me['frame' + els[i].toUpperCase()];
27621                 
27622                 if (el && el.dom) {
27623                     el.addCls(me.baseCls + '-' + me.ui + '-' + els[i]);
27624                     el.addCls(me.baseCls + '-' + me.ui + '-' + cls + '-' + els[i]);
27625                 }
27626             }
27627         }
27628     },
27629     
27630     /**
27631      * Method which removes a specified UI + uiCls from the components element.
27632      * The cls which is added to the element will be: `this.baseCls + '-' + ui`
27633      * @param {String} ui The UI to add to the element
27634      * @private
27635      */
27636     removeUIClsFromElement: function(cls, force) {
27637         var me = this;
27638         
27639         me.removeCls(Ext.baseCSSPrefix + cls);
27640         me.removeCls(me.baseCls + '-' + cls);
27641         me.removeCls(me.baseCls + '-' + me.ui + '-' + cls);
27642         
27643         if (!force &&me.rendered && me.frame && !Ext.supports.CSS3BorderRadius) {
27644             // define each element of the frame
27645             var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
27646                 i, el;
27647             
27648             // loop through each of them, and if they are defined add the ui
27649             for (i = 0; i < els.length; i++) {
27650                 el = me['frame' + els[i].toUpperCase()];
27651                 if (el && el.dom) {
27652                     el.removeCls(me.baseCls + '-' + me.ui + '-' + cls + '-' + els[i]);
27653                 }
27654             }
27655         }
27656     },
27657     
27658     /**
27659      * Method which adds a specified UI to the components element.
27660      * @private
27661      */
27662     addUIToElement: function(force) {
27663         var me = this;
27664         
27665         me.addCls(me.baseCls + '-' + me.ui);
27666         
27667         if (me.rendered && me.frame && !Ext.supports.CSS3BorderRadius) {
27668             // define each element of the frame
27669             var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
27670                 i, el;
27671             
27672             // loop through each of them, and if they are defined add the ui
27673             for (i = 0; i < els.length; i++) {
27674                 el = me['frame' + els[i].toUpperCase()];
27675                 
27676                 if (el) {
27677                     el.addCls(me.baseCls + '-' + me.ui + '-' + els[i]);
27678                 }
27679             }
27680         }
27681     },
27682     
27683     /**
27684      * Method which removes a specified UI from the components element.
27685      * @private
27686      */
27687     removeUIFromElement: function() {
27688         var me = this;
27689         
27690         me.removeCls(me.baseCls + '-' + me.ui);
27691         
27692         if (me.rendered && me.frame && !Ext.supports.CSS3BorderRadius) {
27693             // define each element of the frame
27694             var els = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'],
27695                 i, el;
27696             
27697             // loop through each of them, and if they are defined add the ui
27698             for (i = 0; i < els.length; i++) {
27699                 el = me['frame' + els[i].toUpperCase()];
27700                 if (el) {
27701                     el.removeCls(me.baseCls + '-' + me.ui + '-' + els[i]);
27702                 }
27703             }
27704         }
27705     },
27706     
27707     getElConfig : function() {
27708         var result = this.autoEl || {tag: 'div'};
27709         result.id = this.id;
27710         return result;
27711     },
27712
27713     /**
27714      * This function takes the position argument passed to onRender and returns a
27715      * DOM element that you can use in the insertBefore.
27716      * @param {String/Number/Element/HTMLElement} position Index, element id or element you want
27717      * to put this component before.
27718      * @return {HTMLElement} DOM element that you can use in the insertBefore
27719      */
27720     getInsertPosition: function(position) {
27721         // Convert the position to an element to insert before
27722         if (position !== undefined) {
27723             if (Ext.isNumber(position)) {
27724                 position = this.container.dom.childNodes[position];
27725             }
27726             else {
27727                 position = Ext.getDom(position);
27728             }
27729         }
27730
27731         return position;
27732     },
27733
27734     /**
27735      * Adds ctCls to container.
27736      * @return {Ext.core.Element} The initialized container
27737      * @private
27738      */
27739     initContainer: function(container) {
27740         var me = this;
27741
27742         // If you render a component specifying the el, we get the container
27743         // of the el, and make sure we dont move the el around in the dom
27744         // during the render
27745         if (!container && me.el) {
27746             container = me.el.dom.parentNode;
27747             me.allowDomMove = false;
27748         }
27749
27750         me.container = Ext.get(container);
27751
27752         if (me.ctCls) {
27753             me.container.addCls(me.ctCls);
27754         }
27755
27756         return me.container;
27757     },
27758
27759     /**
27760      * Initialized the renderData to be used when rendering the renderTpl.
27761      * @return {Object} Object with keys and values that are going to be applied to the renderTpl
27762      * @private
27763      */
27764     initRenderData: function() {
27765         var me = this;
27766
27767         return Ext.applyIf(me.renderData, {
27768             ui: me.ui,
27769             uiCls: me.uiCls,
27770             baseCls: me.baseCls,
27771             componentCls: me.componentCls,
27772             frame: me.frame
27773         });
27774     },
27775
27776     /**
27777      * @private
27778      */
27779     getTpl: function(name) {
27780         var prototype = this.self.prototype,
27781             ownerPrototype;
27782
27783         if (this.hasOwnProperty(name)) {
27784             if (!(this[name] instanceof Ext.XTemplate)) {
27785                 this[name] = Ext.ClassManager.dynInstantiate('Ext.XTemplate', this[name]);
27786             }
27787
27788             return this[name];
27789         }
27790
27791         if (!(prototype[name] instanceof Ext.XTemplate)) {
27792             ownerPrototype = prototype;
27793
27794             do {
27795                 if (ownerPrototype.hasOwnProperty(name)) {
27796                     ownerPrototype[name] = Ext.ClassManager.dynInstantiate('Ext.XTemplate', ownerPrototype[name]);
27797                     break;
27798                 }
27799
27800                 ownerPrototype = ownerPrototype.superclass;
27801             } while (ownerPrototype);
27802         }
27803
27804         return prototype[name];
27805     },
27806
27807     /**
27808      * Initializes the renderTpl.
27809      * @return {Ext.XTemplate} The renderTpl XTemplate instance.
27810      * @private
27811      */
27812     initRenderTpl: function() {
27813         return this.getTpl('renderTpl');
27814     },
27815
27816     /**
27817      * Function description
27818      * @return {String} A CSS style string with style, padding, margin and border.
27819      * @private
27820      */
27821     initStyles: function() {
27822         var style = {},
27823             me = this,
27824             Element = Ext.core.Element;
27825
27826         if (Ext.isString(me.style)) {
27827             style = Element.parseStyles(me.style);
27828         } else {
27829             style = Ext.apply({}, me.style);
27830         }
27831
27832         // Convert the padding, margin and border properties from a space seperated string
27833         // into a proper style string
27834         if (me.padding !== undefined) {
27835             style.padding = Element.unitizeBox((me.padding === true) ? 5 : me.padding);
27836         }
27837
27838         if (me.margin !== undefined) {
27839             style.margin = Element.unitizeBox((me.margin === true) ? 5 : me.margin);
27840         }
27841
27842         delete me.style;
27843         return style;
27844     },
27845
27846     /**
27847      * Initializes this components contents. It checks for the properties
27848      * html, contentEl and tpl/data.
27849      * @private
27850      */
27851     initContent: function() {
27852         var me = this,
27853             target = me.getTargetEl(),
27854             contentEl,
27855             pre;
27856
27857         if (me.html) {
27858             target.update(Ext.core.DomHelper.markup(me.html));
27859             delete me.html;
27860         }
27861
27862         if (me.contentEl) {
27863             contentEl = Ext.get(me.contentEl);
27864             pre = Ext.baseCSSPrefix;
27865             contentEl.removeCls([pre + 'hidden', pre + 'hide-display', pre + 'hide-offsets', pre + 'hide-nosize']);
27866             target.appendChild(contentEl.dom);
27867         }
27868
27869         if (me.tpl) {
27870             // Make sure this.tpl is an instantiated XTemplate
27871             if (!me.tpl.isTemplate) {
27872                 me.tpl = Ext.create('Ext.XTemplate', me.tpl);
27873             }
27874
27875             if (me.data) {
27876                 me.tpl[me.tplWriteMode](target, me.data);
27877                 delete me.data;
27878             }
27879         }
27880     },
27881
27882     // @private
27883     initEvents : function() {
27884         var me = this,
27885             afterRenderEvents = me.afterRenderEvents,
27886             property, listeners;
27887         if (afterRenderEvents) {
27888             for (property in afterRenderEvents) {
27889                 if (afterRenderEvents.hasOwnProperty(property)) {
27890                     listeners = afterRenderEvents[property];
27891                     if (me[property] && me[property].on) {
27892                         me.mon(me[property], listeners);
27893                     }
27894                 }
27895             }
27896         }
27897     },
27898
27899     /**
27900      * Sets references to elements inside the component. E.g body -> x-panel-body
27901      * @private
27902      */
27903     applyRenderSelectors: function() {
27904         var selectors = this.renderSelectors || {},
27905             el = this.el.dom,
27906             selector;
27907
27908         for (selector in selectors) {
27909             if (selectors.hasOwnProperty(selector) && selectors[selector]) {
27910                 this[selector] = Ext.get(Ext.DomQuery.selectNode(selectors[selector], el));
27911             }
27912         }
27913     },
27914
27915     /**
27916      * Tests whether this Component matches the selector string.
27917      * @param {String} selector The selector string to test against.
27918      * @return {Boolean} True if this Component matches the selector.
27919      */
27920     is: function(selector) {
27921         return Ext.ComponentQuery.is(this, selector);
27922     },
27923
27924     /**
27925      * <p>Walks up the <code>ownerCt</code> axis looking for an ancestor Container which matches
27926      * the passed simple selector.</p>
27927      * <p>Example:<pre><code>
27928 var owningTabPanel = grid.up('tabpanel');
27929 </code></pre>
27930      * @param {String} selector Optional. The simple selector to test.
27931      * @return {Container} The matching ancestor Container (or <code>undefined</code> if no match was found).
27932      */
27933     up: function(selector) {
27934         var result = this.ownerCt;
27935         if (selector) {
27936             for (; result; result = result.ownerCt) {
27937                 if (Ext.ComponentQuery.is(result, selector)) {
27938                     return result;
27939                 }
27940             }
27941         }
27942         return result;
27943     },
27944
27945     /**
27946      * <p>Returns the next sibling of this Component.</p>
27947      * <p>Optionally selects the next sibling which matches the passed {@link Ext.ComponentQuery ComponentQuery} selector.</p>
27948      * <p>May also be refered to as <code><b>next()</b></code></p>
27949      * <p>Note that this is limited to siblings, and if no siblings of the item match, <code>null</code> is returned. Contrast with {@link #nextNode}</p>
27950      * @param {String} selector Optional A {@link Ext.ComponentQuery ComponentQuery} selector to filter the following items.
27951      * @returns The next sibling (or the next sibling which matches the selector). Returns null if there is no matching sibling.
27952      */
27953     nextSibling: function(selector) {
27954         var o = this.ownerCt, it, last, idx, c;
27955         if (o) {
27956             it = o.items;
27957             idx = it.indexOf(this) + 1;
27958             if (idx) {
27959                 if (selector) {
27960                     for (last = it.getCount(); idx < last; idx++) {
27961                         if ((c = it.getAt(idx)).is(selector)) {
27962                             return c;
27963                         }
27964                     }
27965                 } else {
27966                     if (idx < it.getCount()) {
27967                         return it.getAt(idx);
27968                     }
27969                 }
27970             }
27971         }
27972         return null;
27973     },
27974
27975     /**
27976      * <p>Returns the previous sibling of this Component.</p>
27977      * <p>Optionally selects the previous sibling which matches the passed {@link Ext.ComponentQuery ComponentQuery} selector.</p>
27978      * <p>May also be refered to as <code><b>prev()</b></code></p>
27979      * <p>Note that this is limited to siblings, and if no siblings of the item match, <code>null</code> is returned. Contrast with {@link #previousNode}</p>
27980      * @param {String} selector Optional. A {@link Ext.ComponentQuery ComponentQuery} selector to filter the preceding items.
27981      * @returns The previous sibling (or the previous sibling which matches the selector). Returns null if there is no matching sibling.
27982      */
27983     previousSibling: function(selector) {
27984         var o = this.ownerCt, it, idx, c;
27985         if (o) {
27986             it = o.items;
27987             idx = it.indexOf(this);
27988             if (idx != -1) {
27989                 if (selector) {
27990                     for (--idx; idx >= 0; idx--) {
27991                         if ((c = it.getAt(idx)).is(selector)) {
27992                             return c;
27993                         }
27994                     }
27995                 } else {
27996                     if (idx) {
27997                         return it.getAt(--idx);
27998                     }
27999                 }
28000             }
28001         }
28002         return null;
28003     },
28004
28005     /**
28006      * <p>Returns the previous node in the Component tree in tree traversal order.</p>
28007      * <p>Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will
28008      * walk the tree in reverse order to attempt to find a match. Contrast with {@link #previousSibling}.</p>
28009      * @param {String} selector Optional. A {@link Ext.ComponentQuery ComponentQuery} selector to filter the preceding nodes.
28010      * @returns The previous node (or the previous node which matches the selector). Returns null if there is no matching node.
28011      */
28012     previousNode: function(selector, includeSelf) {
28013         var node = this,
28014             result,
28015             it, len, i;
28016
28017         // If asked to include self, test me
28018         if (includeSelf && node.is(selector)) {
28019             return node;
28020         }
28021
28022         result = this.prev(selector);
28023         if (result) {
28024             return result;
28025         }
28026
28027         if (node.ownerCt) {
28028             for (it = node.ownerCt.items.items, i = Ext.Array.indexOf(it, node) - 1; i > -1; i--) {
28029                 if (it[i].query) {
28030                     result = it[i].query(selector);
28031                     result = result[result.length - 1];
28032                     if (result) {
28033                         return result;
28034                     }
28035                 }
28036             }
28037             return node.ownerCt.previousNode(selector, true);
28038         }
28039     },
28040
28041     /**
28042      * <p>Returns the next node in the Component tree in tree traversal order.</p>
28043      * <p>Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will
28044      * walk the tree to attempt to find a match. Contrast with {@link #pnextSibling}.</p>
28045      * @param {String} selector Optional A {@link Ext.ComponentQuery ComponentQuery} selector to filter the following nodes.
28046      * @returns The next node (or the next node which matches the selector). Returns null if there is no matching node.
28047      */
28048     nextNode: function(selector, includeSelf) {
28049         var node = this,
28050             result,
28051             it, len, i;
28052
28053         // If asked to include self, test me
28054         if (includeSelf && node.is(selector)) {
28055             return node;
28056         }
28057
28058         result = this.next(selector);
28059         if (result) {
28060             return result;
28061         }
28062
28063         if (node.ownerCt) {
28064             for (it = node.ownerCt.items, i = it.indexOf(node) + 1, it = it.items, len = it.length; i < len; i++) {
28065                 if (it[i].down) {
28066                     result = it[i].down(selector);
28067                     if (result) {
28068                         return result;
28069                     }
28070                 }
28071             }
28072             return node.ownerCt.nextNode(selector);
28073         }
28074     },
28075
28076     /**
28077      * Retrieves the id of this component.
28078      * Will autogenerate an id if one has not already been set.
28079      */
28080     getId : function() {
28081         return this.id || (this.id = 'ext-comp-' + (this.getAutoId()));
28082     },
28083
28084     getItemId : function() {
28085         return this.itemId || this.id;
28086     },
28087
28088     /**
28089      * Retrieves the top level element representing this component.
28090      */
28091     getEl : function() {
28092         return this.el;
28093     },
28094
28095     /**
28096      * This is used to determine where to insert the 'html', 'contentEl' and 'items' in this component.
28097      * @private
28098      */
28099     getTargetEl: function() {
28100         return this.frameBody || this.el;
28101     },
28102
28103     /**
28104      * <p>Tests whether or not this Component is of a specific xtype. This can test whether this Component is descended
28105      * from the xtype (default) or whether it is directly of the xtype specified (shallow = true).</p>
28106      * <p><b>If using your own subclasses, be aware that a Component must register its own xtype
28107      * to participate in determination of inherited xtypes.</b></p>
28108      * <p>For a list of all available xtypes, see the {@link Ext.Component} header.</p>
28109      * <p>Example usage:</p>
28110      * <pre><code>
28111 var t = new Ext.form.field.Text();
28112 var isText = t.isXType('textfield');        // true
28113 var isBoxSubclass = t.isXType('field');       // true, descended from Ext.form.field.Base
28114 var isBoxInstance = t.isXType('field', true); // false, not a direct Ext.form.field.Base instance
28115 </code></pre>
28116      * @param {String} xtype The xtype to check for this Component
28117      * @param {Boolean} shallow (optional) False to check whether this Component is descended from the xtype (this is
28118      * the default), or true to check whether this Component is directly of the specified xtype.
28119      * @return {Boolean} True if this component descends from the specified xtype, false otherwise.
28120      */
28121     isXType: function(xtype, shallow) {
28122         //assume a string by default
28123         if (Ext.isFunction(xtype)) {
28124             xtype = xtype.xtype;
28125             //handle being passed the class, e.g. Ext.Component
28126         } else if (Ext.isObject(xtype)) {
28127             xtype = xtype.statics().xtype;
28128             //handle being passed an instance
28129         }
28130
28131         return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1: this.self.xtype == xtype;
28132     },
28133
28134     /**
28135      * <p>Returns this Component's xtype hierarchy as a slash-delimited string. For a list of all
28136      * available xtypes, see the {@link Ext.Component} header.</p>
28137      * <p><b>If using your own subclasses, be aware that a Component must register its own xtype
28138      * to participate in determination of inherited xtypes.</b></p>
28139      * <p>Example usage:</p>
28140      * <pre><code>
28141 var t = new Ext.form.field.Text();
28142 alert(t.getXTypes());  // alerts 'component/field/textfield'
28143 </code></pre>
28144      * @return {String} The xtype hierarchy string
28145      */
28146     getXTypes: function() {
28147         var self = this.self,
28148             xtypes      = [],
28149             parentPrototype  = this,
28150             xtype;
28151
28152         if (!self.xtypes) {
28153             while (parentPrototype && Ext.getClass(parentPrototype)) {
28154                 xtype = Ext.getClass(parentPrototype).xtype;
28155
28156                 if (xtype !== undefined) {
28157                     xtypes.unshift(xtype);
28158                 }
28159
28160                 parentPrototype = parentPrototype.superclass;
28161             }
28162
28163             self.xtypeChain = xtypes;
28164             self.xtypes = xtypes.join('/');
28165         }
28166
28167         return self.xtypes;
28168     },
28169
28170     /**
28171      * Update the content area of a component.
28172      * @param {Mixed} htmlOrData
28173      * If this component has been configured with a template via the tpl config
28174      * then it will use this argument as data to populate the template.
28175      * If this component was not configured with a template, the components
28176      * content area will be updated via Ext.core.Element update
28177      * @param {Boolean} loadScripts
28178      * (optional) Only legitimate when using the html configuration. Defaults to false
28179      * @param {Function} callback
28180      * (optional) Only legitimate when using the html configuration. Callback to execute when scripts have finished loading
28181      */
28182     update : function(htmlOrData, loadScripts, cb) {
28183         var me = this;
28184
28185         if (me.tpl && !Ext.isString(htmlOrData)) {
28186             me.data = htmlOrData;
28187             if (me.rendered) {
28188                 me.tpl[me.tplWriteMode](me.getTargetEl(), htmlOrData || {});
28189             }
28190         } else {
28191             me.html = Ext.isObject(htmlOrData) ? Ext.core.DomHelper.markup(htmlOrData) : htmlOrData;
28192             if (me.rendered) {
28193                 me.getTargetEl().update(me.html, loadScripts, cb);
28194             }
28195         }
28196
28197         if (me.rendered) {
28198             me.doComponentLayout();
28199         }
28200     },
28201
28202     /**
28203      * Convenience function to hide or show this component by boolean.
28204      * @param {Boolean} visible True to show, false to hide
28205      * @return {Ext.Component} this
28206      */
28207     setVisible : function(visible) {
28208         return this[visible ? 'show': 'hide']();
28209     },
28210
28211     /**
28212      * Returns true if this component is visible.
28213      * @param {Boolean} deep. <p>Optional. Pass <code>true</code> to interrogate the visibility status of all
28214      * parent Containers to determine whether this Component is truly visible to the user.</p>
28215      * <p>Generally, to determine whether a Component is hidden, the no argument form is needed. For example
28216      * when creating dynamically laid out UIs in a hidden Container before showing them.</p>
28217      * @return {Boolean} True if this component is visible, false otherwise.
28218      */
28219     isVisible: function(deep) {
28220         var me = this,
28221             child = me,
28222             visible = !me.hidden,
28223             ancestor = me.ownerCt;
28224
28225         // Clear hiddenOwnerCt property
28226         me.hiddenAncestor = false;
28227         if (me.destroyed) {
28228             return false;
28229         }
28230
28231         if (deep && visible && me.rendered && ancestor) {
28232             while (ancestor) {
28233                 // If any ancestor is hidden, then this is hidden.
28234                 // If an ancestor Panel (only Panels have a collapse method) is collapsed,
28235                 // then its layoutTarget (body) is hidden, so this is hidden unless its within a
28236                 // docked item; they are still visible when collapsed (Unless they themseves are hidden)
28237                 if (ancestor.hidden || (ancestor.collapsed &&
28238                         !(ancestor.getDockedItems && Ext.Array.contains(ancestor.getDockedItems(), child)))) {
28239                     // Store hiddenOwnerCt property if needed
28240                     me.hiddenAncestor = ancestor;
28241                     visible = false;
28242                     break;
28243                 }
28244                 child = ancestor;
28245                 ancestor = ancestor.ownerCt;
28246             }
28247         }
28248         return visible;
28249     },
28250
28251     /**
28252      * Enable the component
28253      * @param {Boolean} silent
28254      * Passing false will supress the 'enable' event from being fired.
28255      */
28256     enable: function(silent) {
28257         var me = this;
28258
28259         if (me.rendered) {
28260             me.el.removeCls(me.disabledCls);
28261             me.el.dom.disabled = false;
28262             me.onEnable();
28263         }
28264
28265         me.disabled = false;
28266
28267         if (silent !== true) {
28268             me.fireEvent('enable', me);
28269         }
28270
28271         return me;
28272     },
28273
28274     /**
28275      * Disable the component.
28276      * @param {Boolean} silent
28277      * Passing true, will supress the 'disable' event from being fired.
28278      */
28279     disable: function(silent) {
28280         var me = this;
28281
28282         if (me.rendered) {
28283             me.el.addCls(me.disabledCls);
28284             me.el.dom.disabled = true;
28285             me.onDisable();
28286         }
28287
28288         me.disabled = true;
28289
28290         if (silent !== true) {
28291             me.fireEvent('disable', me);
28292         }
28293
28294         return me;
28295     },
28296     
28297     // @private
28298     onEnable: function() {
28299         if (this.maskOnDisable) {
28300             this.el.unmask();
28301         }        
28302     },
28303
28304     // @private
28305     onDisable : function() {
28306         if (this.maskOnDisable) {
28307             this.el.mask();
28308         }
28309     },
28310     
28311     /**
28312      * Method to determine whether this Component is currently disabled.
28313      * @return {Boolean} the disabled state of this Component.
28314      */
28315     isDisabled : function() {
28316         return this.disabled;
28317     },
28318
28319     /**
28320      * Enable or disable the component.
28321      * @param {Boolean} disabled
28322      */
28323     setDisabled : function(disabled) {
28324         return this[disabled ? 'disable': 'enable']();
28325     },
28326
28327     /**
28328      * Method to determine whether this Component is currently set to hidden.
28329      * @return {Boolean} the hidden state of this Component.
28330      */
28331     isHidden : function() {
28332         return this.hidden;
28333     },
28334
28335     /**
28336      * Adds a CSS class to the top level element representing this component.
28337      * @param {String} cls The CSS class name to add
28338      * @return {Ext.Component} Returns the Component to allow method chaining.
28339      */
28340     addCls : function(className) {
28341         var me = this;
28342         if (!className) {
28343             return me;
28344         }
28345         if (!Ext.isArray(className)){
28346             className = className.replace(me.trimRe, '').split(me.spacesRe);
28347         }
28348         if (me.rendered) {
28349             me.el.addCls(className);
28350         }
28351         else {
28352             me.additionalCls = Ext.Array.unique(me.additionalCls.concat(className));
28353         }
28354         return me;
28355     },
28356
28357     /**
28358      * @deprecated 4.0 Replaced by {link:#addCls}
28359      * Adds a CSS class to the top level element representing this component.
28360      * @param {String} cls The CSS class name to add
28361      * @return {Ext.Component} Returns the Component to allow method chaining.
28362      */
28363     addClass : function() {
28364         return this.addCls.apply(this, arguments);
28365     },
28366
28367     /**
28368      * Removes a CSS class from the top level element representing this component.
28369      * @returns {Ext.Component} Returns the Component to allow method chaining.
28370      */
28371     removeCls : function(className) {
28372         var me = this;
28373
28374         if (!className) {
28375             return me;
28376         }
28377         if (!Ext.isArray(className)){
28378             className = className.replace(me.trimRe, '').split(me.spacesRe);
28379         }
28380         if (me.rendered) {
28381             me.el.removeCls(className);
28382         }
28383         else if (me.additionalCls.length) {
28384             Ext.each(className, function(cls) {
28385                 Ext.Array.remove(me.additionalCls, cls);
28386             });
28387         }
28388         return me;
28389     },
28390
28391     removeClass : function() {
28392         if (Ext.isDefined(Ext.global.console)) {
28393             Ext.global.console.warn('Ext.Component: removeClass has been deprecated. Please use removeCls.');
28394         }
28395         return this.removeCls.apply(this, arguments);
28396     },
28397
28398     addOverCls: function() {
28399         var me = this;
28400         if (!me.disabled) {
28401             me.el.addCls(me.overCls);
28402         }
28403     },
28404
28405     removeOverCls: function() {
28406         this.el.removeCls(this.overCls);
28407     },
28408
28409     addListener : function(element, listeners, scope, options) {
28410         var me = this,
28411             fn,
28412             option;
28413
28414         if (Ext.isString(element) && (Ext.isObject(listeners) || options && options.element)) {
28415             if (options.element) {
28416                 fn = listeners;
28417
28418                 listeners = {};
28419                 listeners[element] = fn;
28420                 element = options.element;
28421                 if (scope) {
28422                     listeners.scope = scope;
28423                 }
28424
28425                 for (option in options) {
28426                     if (options.hasOwnProperty(option)) {
28427                         if (me.eventOptionsRe.test(option)) {
28428                             listeners[option] = options[option];
28429                         }
28430                     }
28431                 }
28432             }
28433
28434             // At this point we have a variable called element,
28435             // and a listeners object that can be passed to on
28436             if (me[element] && me[element].on) {
28437                 me.mon(me[element], listeners);
28438             } else {
28439                 me.afterRenderEvents = me.afterRenderEvents || {};
28440                 me.afterRenderEvents[element] = listeners;
28441             }
28442         }
28443
28444         return me.mixins.observable.addListener.apply(me, arguments);
28445     },
28446
28447     // @TODO: implement removelistener to support the dom event stuff
28448
28449     /**
28450      * Provides the link for Observable's fireEvent method to bubble up the ownership hierarchy.
28451      * @return {Ext.container.Container} the Container which owns this Component.
28452      */
28453     getBubbleTarget : function() {
28454         return this.ownerCt;
28455     },
28456
28457     /**
28458      * Method to determine whether this Component is floating.
28459      * @return {Boolean} the floating state of this component.
28460      */
28461     isFloating : function() {
28462         return this.floating;
28463     },
28464
28465     /**
28466      * Method to determine whether this Component is draggable.
28467      * @return {Boolean} the draggable state of this component.
28468      */
28469     isDraggable : function() {
28470         return !!this.draggable;
28471     },
28472
28473     /**
28474      * Method to determine whether this Component is droppable.
28475      * @return {Boolean} the droppable state of this component.
28476      */
28477     isDroppable : function() {
28478         return !!this.droppable;
28479     },
28480
28481     /**
28482      * @private
28483      * Method to manage awareness of when components are added to their
28484      * respective Container, firing an added event.
28485      * References are established at add time rather than at render time.
28486      * @param {Ext.container.Container} container Container which holds the component
28487      * @param {number} pos Position at which the component was added
28488      */
28489     onAdded : function(container, pos) {
28490         this.ownerCt = container;
28491         this.fireEvent('added', this, container, pos);
28492     },
28493
28494     /**
28495      * @private
28496      * Method to manage awareness of when components are removed from their
28497      * respective Container, firing an removed event. References are properly
28498      * cleaned up after removing a component from its owning container.
28499      */
28500     onRemoved : function() {
28501         var me = this;
28502
28503         me.fireEvent('removed', me, me.ownerCt);
28504         delete me.ownerCt;
28505     },
28506
28507     // @private
28508     beforeDestroy : Ext.emptyFn,
28509     // @private
28510     // @private
28511     onResize : Ext.emptyFn,
28512
28513     /**
28514      * Sets the width and height of this Component. This method fires the {@link #resize} event. This method can accept
28515      * either width and height as separate arguments, or you can pass a size object like <code>{width:10, height:20}</code>.
28516      * @param {Mixed} width The new width to set. This may be one of:<div class="mdetail-params"><ul>
28517      * <li>A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.core.Element#defaultUnit}s (by default, pixels).</li>
28518      * <li>A String used to set the CSS width style.</li>
28519      * <li>A size object in the format <code>{width: widthValue, height: heightValue}</code>.</li>
28520      * <li><code>undefined</code> to leave the width unchanged.</li>
28521      * </ul></div>
28522      * @param {Mixed} height The new height to set (not required if a size object is passed as the first arg).
28523      * This may be one of:<div class="mdetail-params"><ul>
28524      * <li>A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.core.Element#defaultUnit}s (by default, pixels).</li>
28525      * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
28526      * <li><code>undefined</code> to leave the height unchanged.</li>
28527      * </ul></div>
28528      * @return {Ext.Component} this
28529      */
28530     setSize : function(width, height) {
28531         var me = this,
28532             layoutCollection;
28533
28534         // support for standard size objects
28535         if (Ext.isObject(width)) {
28536             height = width.height;
28537             width  = width.width;
28538         }
28539
28540         // Constrain within configured maxima
28541         if (Ext.isNumber(width)) {
28542             width = Ext.Number.constrain(width, me.minWidth, me.maxWidth);
28543         }
28544         if (Ext.isNumber(height)) {
28545             height = Ext.Number.constrain(height, me.minHeight, me.maxHeight);
28546         }
28547
28548         if (!me.rendered || !me.isVisible()) {
28549             // If an ownerCt is hidden, add my reference onto the layoutOnShow stack.  Set the needsLayout flag.
28550             if (me.hiddenAncestor) {
28551                 layoutCollection = me.hiddenAncestor.layoutOnShow;
28552                 layoutCollection.remove(me);
28553                 layoutCollection.add(me);
28554             }
28555             me.needsLayout = {
28556                 width: width,
28557                 height: height,
28558                 isSetSize: true
28559             };
28560             if (!me.rendered) {
28561                 me.width  = (width !== undefined) ? width : me.width;
28562                 me.height = (height !== undefined) ? height : me.height;
28563             }
28564             return me;
28565         }
28566         me.doComponentLayout(width, height, true);
28567
28568         return me;
28569     },
28570
28571     setCalculatedSize : function(width, height, ownerCt) {
28572         var me = this,
28573             layoutCollection;
28574
28575         // support for standard size objects
28576         if (Ext.isObject(width)) {
28577             ownerCt = width.ownerCt;
28578             height = width.height;
28579             width  = width.width;
28580         }
28581
28582         // Constrain within configured maxima
28583         if (Ext.isNumber(width)) {
28584             width = Ext.Number.constrain(width, me.minWidth, me.maxWidth);
28585         }
28586         if (Ext.isNumber(height)) {
28587             height = Ext.Number.constrain(height, me.minHeight, me.maxHeight);
28588         }
28589
28590         if (!me.rendered || !me.isVisible()) {
28591             // If an ownerCt is hidden, add my reference onto the layoutOnShow stack.  Set the needsLayout flag.
28592             if (me.hiddenAncestor) {
28593                 layoutCollection = me.hiddenAncestor.layoutOnShow;
28594                 layoutCollection.remove(me);
28595                 layoutCollection.add(me);
28596             }
28597             me.needsLayout = {
28598                 width: width,
28599                 height: height,
28600                 isSetSize: false,
28601                 ownerCt: ownerCt
28602             };
28603             return me;
28604         }
28605         me.doComponentLayout(width, height, false, ownerCt);
28606
28607         return me;
28608     },
28609
28610     /**
28611      * This method needs to be called whenever you change something on this component that requires the Component's
28612      * layout to be recalculated.
28613      * @return {Ext.container.Container} this
28614      */
28615     doComponentLayout : function(width, height, isSetSize, ownerCt) {
28616         var me = this,
28617             componentLayout = me.getComponentLayout();
28618
28619         // collapsed state is not relevant here, so no testing done.
28620         // Only Panels have a collapse method, and that just sets the width/height such that only
28621         // a single docked Header parallel to the collapseTo side are visible, and the Panel body is hidden.
28622         if (me.rendered && componentLayout) {
28623             width = (width !== undefined) ? width : me.width;
28624             height = (height !== undefined) ? height : me.height;
28625             if (isSetSize) {
28626                 me.width = width;
28627                 me.height = height;
28628             }
28629
28630             componentLayout.layout(width, height, isSetSize, ownerCt);
28631         }
28632         return me;
28633     },
28634
28635     // @private
28636     setComponentLayout : function(layout) {
28637         var currentLayout = this.componentLayout;
28638         if (currentLayout && currentLayout.isLayout && currentLayout != layout) {
28639             currentLayout.setOwner(null);
28640         }
28641         this.componentLayout = layout;
28642         layout.setOwner(this);
28643     },
28644
28645     getComponentLayout : function() {
28646         var me = this;
28647
28648         if (!me.componentLayout || !me.componentLayout.isLayout) {
28649             me.setComponentLayout(Ext.layout.Layout.create(me.componentLayout, 'autocomponent'));
28650         }
28651         return me.componentLayout;
28652     },
28653
28654     /**
28655      * @param {Number} adjWidth The box-adjusted width that was set
28656      * @param {Number} adjHeight The box-adjusted height that was set
28657      * @param {Boolean} isSetSize Whether or not the height/width are stored on the component permanently
28658      * @param {Ext.Component} layoutOwner Component which sent the layout. Only used when isSetSize is false.
28659      */
28660     afterComponentLayout: function(width, height, isSetSize, layoutOwner) {
28661         this.fireEvent('resize', this, width, height);
28662     },
28663
28664     /**
28665      * Occurs before componentLayout is run. Returning false from this method will prevent the componentLayout
28666      * from being executed.
28667      * @param {Number} adjWidth The box-adjusted width that was set
28668      * @param {Number} adjHeight The box-adjusted height that was set
28669      * @param {Boolean} isSetSize Whether or not the height/width are stored on the component permanently
28670      * @param {Ext.Component} layoutOwner Component which sent the layout. Only used when isSetSize is false.
28671      */
28672     beforeComponentLayout: function(width, height, isSetSize, layoutOwner) {
28673         return true;
28674     },
28675
28676     /**
28677      * Sets the left and top of the component.  To set the page XY position instead, use {@link #setPagePosition}.
28678      * This method fires the {@link #move} event.
28679      * @param {Number} left The new left
28680      * @param {Number} top The new top
28681      * @return {Ext.Component} this
28682      */
28683     setPosition : function(x, y) {
28684         var me = this;
28685
28686         if (Ext.isObject(x)) {
28687             y = x.y;
28688             x = x.x;
28689         }
28690
28691         if (!me.rendered) {
28692             return me;
28693         }
28694
28695         if (x !== undefined || y !== undefined) {
28696             me.el.setBox(x, y);
28697             me.onPosition(x, y);
28698             me.fireEvent('move', me, x, y);
28699         }
28700         return me;
28701     },
28702
28703     /* @private
28704      * Called after the component is moved, this method is empty by default but can be implemented by any
28705      * subclass that needs to perform custom logic after a move occurs.
28706      * @param {Number} x The new x position
28707      * @param {Number} y The new y position
28708      */
28709     onPosition: Ext.emptyFn,
28710
28711     /**
28712      * Sets the width of the component.  This method fires the {@link #resize} event.
28713      * @param {Number} width The new width to setThis may be one of:<div class="mdetail-params"><ul>
28714      * <li>A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.core.Element#defaultUnit}s (by default, pixels).</li>
28715      * <li>A String used to set the CSS width style.</li>
28716      * </ul></div>
28717      * @return {Ext.Component} this
28718      */
28719     setWidth : function(width) {
28720         return this.setSize(width);
28721     },
28722
28723     /**
28724      * Sets the height of the component.  This method fires the {@link #resize} event.
28725      * @param {Number} height The new height to set. This may be one of:<div class="mdetail-params"><ul>
28726      * <li>A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.core.Element#defaultUnit}s (by default, pixels).</li>
28727      * <li>A String used to set the CSS height style.</li>
28728      * <li><i>undefined</i> to leave the height unchanged.</li>
28729      * </ul></div>
28730      * @return {Ext.Component} this
28731      */
28732     setHeight : function(height) {
28733         return this.setSize(undefined, height);
28734     },
28735
28736     /**
28737      * Gets the current size of the component's underlying element.
28738      * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
28739      */
28740     getSize : function() {
28741         return this.el.getSize();
28742     },
28743
28744     /**
28745      * Gets the current width of the component's underlying element.
28746      * @return {Number}
28747      */
28748     getWidth : function() {
28749         return this.el.getWidth();
28750     },
28751
28752     /**
28753      * Gets the current height of the component's underlying element.
28754      * @return {Number}
28755      */
28756     getHeight : function() {
28757         return this.el.getHeight();
28758     },
28759
28760     /**
28761      * Gets the {@link Ext.ComponentLoader} for this Component.
28762      * @return {Ext.ComponentLoader} The loader instance, null if it doesn't exist.
28763      */
28764     getLoader: function(){
28765         var me = this,
28766             autoLoad = me.autoLoad ? (Ext.isObject(me.autoLoad) ? me.autoLoad : {url: me.autoLoad}) : null,
28767             loader = me.loader || autoLoad;
28768
28769         if (loader) {
28770             if (!loader.isLoader) {
28771                 me.loader = Ext.create('Ext.ComponentLoader', Ext.apply({
28772                     target: me,
28773                     autoLoad: autoLoad
28774                 }, loader));
28775             } else {
28776                 loader.setTarget(me);
28777             }
28778             return me.loader;
28779
28780         }
28781         return null;
28782     },
28783
28784     /**
28785      * This method allows you to show or hide a LoadMask on top of this component.
28786      * @param {Boolean/Object/String} load True to show the default LoadMask, a config object
28787      * that will be passed to the LoadMask constructor, or a message String to show. False to
28788      * hide the current LoadMask.
28789      * @param {Boolean} targetEl True to mask the targetEl of this Component instead of the this.el.
28790      * For example, setting this to true on a Panel will cause only the body to be masked. (defaults to false)
28791      * @return {Ext.LoadMask} The LoadMask instance that has just been shown.
28792      */
28793     setLoading : function(load, targetEl) {
28794         var me = this,
28795             config;
28796
28797         if (me.rendered) {
28798             if (load !== false && !me.collapsed) {
28799                 if (Ext.isObject(load)) {
28800                     config = load;
28801                 }
28802                 else if (Ext.isString(load)) {
28803                     config = {msg: load};
28804                 }
28805                 else {
28806                     config = {};
28807                 }
28808                 me.loadMask = me.loadMask || Ext.create('Ext.LoadMask', targetEl ? me.getTargetEl() : me.el, config);
28809                 me.loadMask.show();
28810             } else if (me.loadMask) {
28811                 Ext.destroy(me.loadMask);
28812                 me.loadMask = null;
28813             }
28814         }
28815
28816         return me.loadMask;
28817     },
28818
28819     /**
28820      * Sets the dock position of this component in its parent panel. Note that
28821      * this only has effect if this item is part of the dockedItems collection
28822      * of a parent that has a DockLayout (note that any Panel has a DockLayout
28823      * by default)
28824      * @return {Component} this
28825      */
28826     setDocked : function(dock, layoutParent) {
28827         var me = this;
28828
28829         me.dock = dock;
28830         if (layoutParent && me.ownerCt && me.rendered) {
28831             me.ownerCt.doComponentLayout();
28832         }
28833         return me;
28834     },
28835
28836     onDestroy : function() {
28837         var me = this;
28838
28839         if (me.monitorResize && Ext.EventManager.resizeEvent) {
28840             Ext.EventManager.resizeEvent.removeListener(me.setSize, me);
28841         }
28842         Ext.destroy(me.componentLayout, me.loadMask);
28843     },
28844
28845     /**
28846      * Destroys the Component.
28847      */
28848     destroy : function() {
28849         var me = this;
28850
28851         if (!me.isDestroyed) {
28852             if (me.fireEvent('beforedestroy', me) !== false) {
28853                 me.destroying = true;
28854                 me.beforeDestroy();
28855
28856                 if (me.floating) {
28857                     delete me.floatParent;
28858                     // A zIndexManager is stamped into a *floating* Component when it is added to a Container.
28859                     // If it has no zIndexManager at render time, it is assigned to the global Ext.WindowManager instance.
28860                     if (me.zIndexManager) {
28861                         me.zIndexManager.unregister(me);
28862                     }
28863                 } else if (me.ownerCt && me.ownerCt.remove) {
28864                     me.ownerCt.remove(me, false);
28865                 }
28866
28867                 if (me.rendered) {
28868                     me.el.remove();
28869                 }
28870
28871                 me.onDestroy();
28872
28873                 // Attempt to destroy all plugins
28874                 Ext.destroy(me.plugins);
28875
28876                 Ext.ComponentManager.unregister(me);
28877                 me.fireEvent('destroy', me);
28878
28879                 me.mixins.state.destroy.call(me);
28880
28881                 me.clearListeners();
28882                 me.destroying = false;
28883                 me.isDestroyed = true;
28884             }
28885         }
28886     },
28887
28888     /**
28889      * Retrieves a plugin by its pluginId which has been bound to this
28890      * component.
28891      * @returns {Ext.AbstractPlugin} pluginInstance
28892      */
28893     getPlugin: function(pluginId) {
28894         var i = 0,
28895             plugins = this.plugins,
28896             ln = plugins.length;
28897         for (; i < ln; i++) {
28898             if (plugins[i].pluginId === pluginId) {
28899                 return plugins[i];
28900             }
28901         }
28902     },
28903     
28904     /**
28905      * Determines whether this component is the descendant of a particular container.
28906      * @param {Ext.Container} container
28907      * @returns {Boolean} isDescendant
28908      */
28909     isDescendantOf: function(container) {
28910         return !!this.findParentBy(function(p){
28911             return p === container;
28912         });
28913     }
28914 }, function() {
28915     this.createAlias({
28916         on: 'addListener',
28917         prev: 'previousSibling',
28918         next: 'nextSibling'
28919     });
28920 });
28921
28922 /**
28923  * @class Ext.AbstractPlugin
28924  * @extends Object
28925  *
28926  * Plugins are injected 
28927  */
28928 Ext.define('Ext.AbstractPlugin', {
28929     disabled: false,
28930     
28931     constructor: function(config) {
28932         if (!config.cmp && Ext.global.console) {
28933             Ext.global.console.warn("Attempted to attach a plugin ");
28934         }
28935         Ext.apply(this, config);
28936     },
28937     
28938     getCmp: function() {
28939         return this.cmp;
28940     },
28941
28942     /**
28943      * The init method is invoked after initComponent has been run for the
28944      * component which we are injecting the plugin into.
28945      */
28946     init: Ext.emptyFn,
28947
28948     /**
28949      * The destroy method is invoked by the owning Component at the time the Component is being destroyed.
28950      * Use this method to clean up an resources.
28951      */
28952     destroy: Ext.emptyFn,
28953
28954     /**
28955      * Enable the plugin and set the disabled flag to false.
28956      */
28957     enable: function() {
28958         this.disabled = false;
28959     },
28960
28961     /**
28962      * Disable the plugin and set the disabled flag to true.
28963      */
28964     disable: function() {
28965         this.disabled = true;
28966     }
28967 });
28968
28969 /**
28970  * @class Ext.data.Connection
28971  * The Connection class encapsulates a connection to the page's originating domain, allowing requests to be made either
28972  * to a configured URL, or to a URL specified at request time.
28973  *
28974  * Requests made by this class are asynchronous, and will return immediately. No data from the server will be available
28975  * to the statement immediately following the {@link #request} call. To process returned data, use a success callback
28976  * in the request options object, or an {@link #requestcomplete event listener}.
28977  *
28978  * <p><u>File Uploads</u></p>
28979  *
28980  * File uploads are not performed using normal "Ajax" techniques, that is they are not performed using XMLHttpRequests.
28981  * Instead the form is submitted in the standard manner with the DOM &lt;form&gt; element temporarily modified to have its
28982  * target set to refer to a dynamically generated, hidden &lt;iframe&gt; which is inserted into the document but removed
28983  * after the return data has been gathered.
28984  *
28985  * The server response is parsed by the browser to create the document for the IFRAME. If the server is using JSON to
28986  * send the return object, then the Content-Type header must be set to "text/html" in order to tell the browser to
28987  * insert the text unchanged into the document body.
28988  *
28989  * Characters which are significant to an HTML parser must be sent as HTML entities, so encode "&lt;" as "&amp;lt;", "&amp;" as
28990  * "&amp;amp;" etc.
28991  *
28992  * The response text is retrieved from the document, and a fake XMLHttpRequest object is created containing a
28993  * responseText property in order to conform to the requirements of event handlers and callbacks.
28994  *
28995  * Be aware that file upload packets are sent with the content type multipart/form and some server technologies
28996  * (notably JEE) may require some custom processing in order to retrieve parameter names and parameter values from the
28997  * packet content.
28998  *
28999  * Also note that it's not possible to check the response code of the hidden iframe, so the success handler will ALWAYS fire.
29000  */
29001 Ext.define('Ext.data.Connection', {
29002     mixins: {
29003         observable: 'Ext.util.Observable'
29004     },
29005
29006     statics: {
29007         requestId: 0
29008     },
29009
29010     url: null,
29011     async: true,
29012     method: null,
29013     username: '',
29014     password: '',
29015
29016     /**
29017      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
29018      * @type Boolean
29019      */
29020     disableCaching: true,
29021
29022     /**
29023      * @cfg {String} disableCachingParam (Optional) Change the parameter which is sent went disabling caching
29024      * through a cache buster. Defaults to '_dc'
29025      * @type String
29026      */
29027     disableCachingParam: '_dc',
29028
29029     /**
29030      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
29031      */
29032     timeout : 30000,
29033
29034     /**
29035      * @param {Object} extraParams (Optional) Any parameters to be appended to the request.
29036      */
29037
29038     useDefaultHeader : true,
29039     defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8',
29040     useDefaultXhrHeader : true,
29041     defaultXhrHeader : 'XMLHttpRequest',
29042
29043     constructor : function(config) {
29044         config = config || {};
29045         Ext.apply(this, config);
29046
29047         this.addEvents(
29048             /**
29049              * @event beforerequest
29050              * Fires before a network request is made to retrieve a data object.
29051              * @param {Connection} conn This Connection object.
29052              * @param {Object} options The options config object passed to the {@link #request} method.
29053              */
29054             'beforerequest',
29055             /**
29056              * @event requestcomplete
29057              * Fires if the request was successfully completed.
29058              * @param {Connection} conn This Connection object.
29059              * @param {Object} response The XHR object containing the response data.
29060              * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
29061              * for details.
29062              * @param {Object} options The options config object passed to the {@link #request} method.
29063              */
29064             'requestcomplete',
29065             /**
29066              * @event requestexception
29067              * Fires if an error HTTP status was returned from the server.
29068              * See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP Status Code Definitions</a>
29069              * for details of HTTP status codes.
29070              * @param {Connection} conn This Connection object.
29071              * @param {Object} response The XHR object containing the response data.
29072              * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
29073              * for details.
29074              * @param {Object} options The options config object passed to the {@link #request} method.
29075              */
29076             'requestexception'
29077         );
29078         this.requests = {};
29079         this.mixins.observable.constructor.call(this);
29080     },
29081
29082     /**
29083      * <p>Sends an HTTP request to a remote server.</p>
29084      * <p><b>Important:</b> Ajax server requests are asynchronous, and this call will
29085      * return before the response has been received. Process any returned data
29086      * in a callback function.</p>
29087      * <pre><code>
29088 Ext.Ajax.request({
29089 url: 'ajax_demo/sample.json',
29090 success: function(response, opts) {
29091   var obj = Ext.decode(response.responseText);
29092   console.dir(obj);
29093 },
29094 failure: function(response, opts) {
29095   console.log('server-side failure with status code ' + response.status);
29096 }
29097 });
29098      * </code></pre>
29099      * <p>To execute a callback function in the correct scope, use the <tt>scope</tt> option.</p>
29100      * @param {Object} options An object which may contain the following properties:<ul>
29101      * <li><b>url</b> : String/Function (Optional)<div class="sub-desc">The URL to
29102      * which to send the request, or a function to call which returns a URL string. The scope of the
29103      * function is specified by the <tt>scope</tt> option. Defaults to the configured
29104      * <tt>{@link #url}</tt>.</div></li>
29105      * <li><b>params</b> : Object/String/Function (Optional)<div class="sub-desc">
29106      * An object containing properties which are used as parameters to the
29107      * request, a url encoded string or a function to call to get either. The scope of the function
29108      * is specified by the <tt>scope</tt> option.</div></li>
29109      * <li><b>method</b> : String (Optional)<div class="sub-desc">The HTTP method to use
29110      * for the request. Defaults to the configured method, or if no method was configured,
29111      * "GET" if no parameters are being sent, and "POST" if parameters are being sent.  Note that
29112      * the method name is case-sensitive and should be all caps.</div></li>
29113      * <li><b>callback</b> : Function (Optional)<div class="sub-desc">The
29114      * function to be called upon receipt of the HTTP response. The callback is
29115      * called regardless of success or failure and is passed the following
29116      * parameters:<ul>
29117      * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
29118      * <li><b>success</b> : Boolean<div class="sub-desc">True if the request succeeded.</div></li>
29119      * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.
29120      * See <a href="http://www.w3.org/TR/XMLHttpRequest/">http://www.w3.org/TR/XMLHttpRequest/</a> for details about
29121      * accessing elements of the response.</div></li>
29122      * </ul></div></li>
29123      * <li><a id="request-option-success"></a><b>success</b> : Function (Optional)<div class="sub-desc">The function
29124      * to be called upon success of the request. The callback is passed the following
29125      * parameters:<ul>
29126      * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
29127      * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
29128      * </ul></div></li>
29129      * <li><b>failure</b> : Function (Optional)<div class="sub-desc">The function
29130      * to be called upon failure of the request. The callback is passed the
29131      * following parameters:<ul>
29132      * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
29133      * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
29134      * </ul></div></li>
29135      * <li><b>scope</b> : Object (Optional)<div class="sub-desc">The scope in
29136      * which to execute the callbacks: The "this" object for the callback function. If the <tt>url</tt>, or <tt>params</tt> options were
29137      * specified as functions from which to draw values, then this also serves as the scope for those function calls.
29138      * Defaults to the browser window.</div></li>
29139      * <li><b>timeout</b> : Number (Optional)<div class="sub-desc">The timeout in milliseconds to be used for this request. Defaults to 30 seconds.</div></li>
29140      * <li><b>form</b> : Element/HTMLElement/String (Optional)<div class="sub-desc">The <tt>&lt;form&gt;</tt>
29141      * Element or the id of the <tt>&lt;form&gt;</tt> to pull parameters from.</div></li>
29142      * <li><a id="request-option-isUpload"></a><b>isUpload</b> : Boolean (Optional)<div class="sub-desc"><b>Only meaningful when used
29143      * with the <tt>form</tt> option</b>.
29144      * <p>True if the form object is a file upload (will be set automatically if the form was
29145      * configured with <b><tt>enctype</tt></b> "multipart/form-data").</p>
29146      * <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>
29147      * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
29148      * DOM <tt>&lt;form></tt> element temporarily modified to have its
29149      * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
29150      * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
29151      * but removed after the return data has been gathered.</p>
29152      * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
29153      * server is using JSON to send the return object, then the
29154      * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
29155      * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
29156      * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
29157      * is created containing a <tt>responseText</tt> property in order to conform to the
29158      * requirements of event handlers and callbacks.</p>
29159      * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
29160      * and some server technologies (notably JEE) may require some custom processing in order to
29161      * retrieve parameter names and parameter values from the packet content.</p>
29162      * </div></li>
29163      * <li><b>headers</b> : Object (Optional)<div class="sub-desc">Request
29164      * headers to set for the request.</div></li>
29165      * <li><b>xmlData</b> : Object (Optional)<div class="sub-desc">XML document
29166      * to use for the post. Note: This will be used instead of params for the post
29167      * data. Any params will be appended to the URL.</div></li>
29168      * <li><b>jsonData</b> : Object/String (Optional)<div class="sub-desc">JSON
29169      * data to use as the post. Note: This will be used instead of params for the post
29170      * data. Any params will be appended to the URL.</div></li>
29171      * <li><b>disableCaching</b> : Boolean (Optional)<div class="sub-desc">True
29172      * to add a unique cache-buster param to GET requests.</div></li>
29173      * </ul></p>
29174      * <p>The options object may also contain any other property which might be needed to perform
29175      * postprocessing in a callback because it is passed to callback functions.</p>
29176      * @return {Object} request The request object. This may be used
29177      * to cancel the request.
29178      */
29179     request : function(options) {
29180         options = options || {};
29181         var me = this,
29182             scope = options.scope || window,
29183             username = options.username || me.username,
29184             password = options.password || me.password || '',
29185             async,
29186             requestOptions,
29187             request,
29188             headers,
29189             xhr;
29190
29191         if (me.fireEvent('beforerequest', me, options) !== false) {
29192
29193             requestOptions = me.setOptions(options, scope);
29194
29195             if (this.isFormUpload(options) === true) {
29196                 this.upload(options.form, requestOptions.url, requestOptions.data, options);
29197                 return null;
29198             }
29199
29200             // if autoabort is set, cancel the current transactions
29201             if (options.autoAbort === true || me.autoAbort) {
29202                 me.abort();
29203             }
29204
29205             // create a connection object
29206             xhr = this.getXhrInstance();
29207
29208             async = options.async !== false ? (options.async || me.async) : false;
29209
29210             // open the request
29211             if (username) {
29212                 xhr.open(requestOptions.method, requestOptions.url, async, username, password);
29213             } else {
29214                 xhr.open(requestOptions.method, requestOptions.url, async);
29215             }
29216
29217             headers = me.setupHeaders(xhr, options, requestOptions.data, requestOptions.params);
29218
29219             // create the transaction object
29220             request = {
29221                 id: ++Ext.data.Connection.requestId,
29222                 xhr: xhr,
29223                 headers: headers,
29224                 options: options,
29225                 async: async,
29226                 timeout: setTimeout(function() {
29227                     request.timedout = true;
29228                     me.abort(request);
29229                 }, options.timeout || me.timeout)
29230             };
29231             me.requests[request.id] = request;
29232
29233             // bind our statechange listener
29234             if (async) {
29235                 xhr.onreadystatechange = Ext.Function.bind(me.onStateChange, me, [request]);
29236             }
29237
29238             // start the request!
29239             xhr.send(requestOptions.data);
29240             if (!async) {
29241                 return this.onComplete(request);
29242             }
29243             return request;
29244         } else {
29245             Ext.callback(options.callback, options.scope, [options, undefined, undefined]);
29246             return null;
29247         }
29248     },
29249
29250     /**
29251      * Upload a form using a hidden iframe.
29252      * @param {Mixed} form The form to upload
29253      * @param {String} url The url to post to
29254      * @param {String} params Any extra parameters to pass
29255      * @param {Object} options The initial options
29256      */
29257     upload: function(form, url, params, options){
29258         form = Ext.getDom(form);
29259         options = options || {};
29260
29261         var id = Ext.id(),
29262                 frame = document.createElement('iframe'),
29263                 hiddens = [],
29264                 encoding = 'multipart/form-data',
29265                 buf = {
29266                     target: form.target,
29267                     method: form.method,
29268                     encoding: form.encoding,
29269                     enctype: form.enctype,
29270                     action: form.action
29271                 }, hiddenItem;
29272
29273         /*
29274          * Originally this behaviour was modified for Opera 10 to apply the secure URL after
29275          * the frame had been added to the document. It seems this has since been corrected in
29276          * Opera so the behaviour has been reverted, the URL will be set before being added.
29277          */
29278         Ext.fly(frame).set({
29279             id: id,
29280             name: id,
29281             cls: Ext.baseCSSPrefix + 'hide-display',
29282             src: Ext.SSL_SECURE_URL
29283         });
29284
29285         document.body.appendChild(frame);
29286
29287         // This is required so that IE doesn't pop the response up in a new window.
29288         if (document.frames) {
29289            document.frames[id].name = id;
29290         }
29291
29292         Ext.fly(form).set({
29293             target: id,
29294             method: 'POST',
29295             enctype: encoding,
29296             encoding: encoding,
29297             action: url || buf.action
29298         });
29299
29300         // add dynamic params
29301         if (params) {
29302             Ext.iterate(Ext.Object.fromQueryString(params), function(name, value){
29303                 hiddenItem = document.createElement('input');
29304                 Ext.fly(hiddenItem).set({
29305                     type: 'hidden',
29306                     value: value,
29307                     name: name
29308                 });
29309                 form.appendChild(hiddenItem);
29310                 hiddens.push(hiddenItem);
29311             });
29312         }
29313
29314         Ext.fly(frame).on('load', Ext.Function.bind(this.onUploadComplete, this, [frame, options]), null, {single: true});
29315         form.submit();
29316
29317         Ext.fly(form).set(buf);
29318         Ext.each(hiddens, function(h) {
29319             Ext.removeNode(h);
29320         });
29321     },
29322
29323     onUploadComplete: function(frame, options){
29324         var me = this,
29325             // bogus response object
29326             response = {
29327                 responseText: '',
29328                 responseXML: null
29329             }, doc, firstChild;
29330
29331         try {
29332             doc = frame.contentWindow.document || frame.contentDocument || window.frames[id].document;
29333             if (doc) {
29334                 if (doc.body) {
29335                     if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in textarea
29336                         response.responseText = firstChild.value;
29337                     } else {
29338                         response.responseText = doc.body.innerHTML;
29339                     }
29340                 }
29341                 //in IE the document may still have a body even if returns XML.
29342                 response.responseXML = doc.XMLDocument || doc;
29343             }
29344         } catch (e) {
29345         }
29346
29347         me.fireEvent('requestcomplete', me, response, options);
29348
29349         Ext.callback(options.success, options.scope, [response, options]);
29350         Ext.callback(options.callback, options.scope, [options, true, response]);
29351
29352         setTimeout(function(){
29353             Ext.removeNode(frame);
29354         }, 100);
29355     },
29356
29357     /**
29358      * Detect whether the form is intended to be used for an upload.
29359      * @private
29360      */
29361     isFormUpload: function(options){
29362         var form = this.getForm(options);
29363         if (form) {
29364             return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
29365         }
29366         return false;
29367     },
29368
29369     /**
29370      * Get the form object from options.
29371      * @private
29372      * @param {Object} options The request options
29373      * @return {HTMLElement} The form, null if not passed
29374      */
29375     getForm: function(options){
29376         return Ext.getDom(options.form) || null;
29377     },
29378
29379     /**
29380      * Set various options such as the url, params for the request
29381      * @param {Object} options The initial options
29382      * @param {Object} scope The scope to execute in
29383      * @return {Object} The params for the request
29384      */
29385     setOptions: function(options, scope){
29386         var me =  this,
29387             params = options.params || {},
29388             extraParams = me.extraParams,
29389             urlParams = options.urlParams,
29390             url = options.url || me.url,
29391             jsonData = options.jsonData,
29392             method,
29393             disableCache,
29394             data;
29395
29396
29397         // allow params to be a method that returns the params object
29398         if (Ext.isFunction(params)) {
29399             params = params.call(scope, options);
29400         }
29401
29402         // allow url to be a method that returns the actual url
29403         if (Ext.isFunction(url)) {
29404             url = url.call(scope, options);
29405         }
29406
29407         url = this.setupUrl(options, url);
29408
29409         if (!url) {
29410             Ext.Error.raise({
29411                 options: options,
29412                 msg: 'No URL specified'
29413             });
29414         }
29415
29416         // check for xml or json data, and make sure json data is encoded
29417         data = options.rawData || options.xmlData || jsonData || null;
29418         if (jsonData && !Ext.isPrimitive(jsonData)) {
29419             data = Ext.encode(data);
29420         }
29421
29422         // make sure params are a url encoded string and include any extraParams if specified
29423         if (Ext.isObject(params)) {
29424             params = Ext.Object.toQueryString(params);
29425         }
29426
29427         if (Ext.isObject(extraParams)) {
29428             extraParams = Ext.Object.toQueryString(extraParams);
29429         }
29430
29431         params = params + ((extraParams) ? ((params) ? '&' : '') + extraParams : '');
29432
29433         urlParams = Ext.isObject(urlParams) ? Ext.Object.toQueryString(urlParams) : urlParams;
29434
29435         params = this.setupParams(options, params);
29436
29437         // decide the proper method for this request
29438         method = (options.method || me.method || ((params || data) ? 'POST' : 'GET')).toUpperCase();
29439         this.setupMethod(options, method);
29440
29441
29442         disableCache = options.disableCaching !== false ? (options.disableCaching || me.disableCaching) : false;
29443         // if the method is get append date to prevent caching
29444         if (method === 'GET' && disableCache) {
29445             url = Ext.urlAppend(url, (options.disableCachingParam || me.disableCachingParam) + '=' + (new Date().getTime()));
29446         }
29447
29448         // if the method is get or there is json/xml data append the params to the url
29449         if ((method == 'GET' || data) && params) {
29450             url = Ext.urlAppend(url, params);
29451             params = null;
29452         }
29453
29454         // allow params to be forced into the url
29455         if (urlParams) {
29456             url = Ext.urlAppend(url, urlParams);
29457         }
29458
29459         return {
29460             url: url,
29461             method: method,
29462             data: data || params || null
29463         };
29464     },
29465
29466     /**
29467      * Template method for overriding url
29468      * @private
29469      * @param {Object} options
29470      * @param {String} url
29471      * @return {String} The modified url
29472      */
29473     setupUrl: function(options, url){
29474         var form = this.getForm(options);
29475         if (form) {
29476             url = url || form.action;
29477         }
29478         return url;
29479     },
29480
29481
29482     /**
29483      * Template method for overriding params
29484      * @private
29485      * @param {Object} options
29486      * @param {String} params
29487      * @return {String} The modified params
29488      */
29489     setupParams: function(options, params) {
29490         var form = this.getForm(options),
29491             serializedForm;
29492         if (form && !this.isFormUpload(options)) {
29493             serializedForm = Ext.core.Element.serializeForm(form);
29494             params = params ? (params + '&' + serializedForm) : serializedForm;
29495         }
29496         return params;
29497     },
29498
29499     /**
29500      * Template method for overriding method
29501      * @private
29502      * @param {Object} options
29503      * @param {String} method
29504      * @return {String} The modified method
29505      */
29506     setupMethod: function(options, method){
29507         if (this.isFormUpload(options)) {
29508             return 'POST';
29509         }
29510         return method;
29511     },
29512
29513     /**
29514      * Setup all the headers for the request
29515      * @private
29516      * @param {Object} xhr The xhr object
29517      * @param {Object} options The options for the request
29518      * @param {Object} data The data for the request
29519      * @param {Object} params The params for the request
29520      */
29521     setupHeaders: function(xhr, options, data, params){
29522         var me = this,
29523             headers = Ext.apply({}, options.headers || {}, me.defaultHeaders || {}),
29524             contentType = me.defaultPostHeader,
29525             jsonData = options.jsonData,
29526             xmlData = options.xmlData,
29527             key,
29528             header;
29529
29530         if (!headers['Content-Type'] && (data || params)) {
29531             if (data) {
29532                 if (options.rawData) {
29533                     contentType = 'text/plain';
29534                 } else {
29535                     if (xmlData && Ext.isDefined(xmlData)) {
29536                         contentType = 'text/xml';
29537                     } else if (jsonData && Ext.isDefined(jsonData)) {
29538                         contentType = 'application/json';
29539                     }
29540                 }
29541             }
29542             headers['Content-Type'] = contentType;
29543         }
29544
29545         if (me.useDefaultXhrHeader && !headers['X-Requested-With']) {
29546             headers['X-Requested-With'] = me.defaultXhrHeader;
29547         }
29548         // set up all the request headers on the xhr object
29549         try{
29550             for (key in headers) {
29551                 if (headers.hasOwnProperty(key)) {
29552                     header = headers[key];
29553                     xhr.setRequestHeader(key, header);
29554                 }
29555
29556             }
29557         } catch(e) {
29558             me.fireEvent('exception', key, header);
29559         }
29560         return headers;
29561     },
29562
29563     /**
29564      * Creates the appropriate XHR transport for the browser.
29565      * @private
29566      */
29567     getXhrInstance: (function(){
29568         var options = [function(){
29569             return new XMLHttpRequest();
29570         }, function(){
29571             return new ActiveXObject('MSXML2.XMLHTTP.3.0');
29572         }, function(){
29573             return new ActiveXObject('MSXML2.XMLHTTP');
29574         }, function(){
29575             return new ActiveXObject('Microsoft.XMLHTTP');
29576         }], i = 0,
29577             len = options.length,
29578             xhr;
29579
29580         for(; i < len; ++i) {
29581             try{
29582                 xhr = options[i];
29583                 xhr();
29584                 break;
29585             }catch(e){}
29586         }
29587         return xhr;
29588     })(),
29589
29590     /**
29591      * Determine whether this object has a request outstanding.
29592      * @param {Object} request (Optional) defaults to the last transaction
29593      * @return {Boolean} True if there is an outstanding request.
29594      */
29595     isLoading : function(request) {
29596         if (!(request && request.xhr)) {
29597             return false;
29598         }
29599         // if there is a connection and readyState is not 0 or 4
29600         var state = request.xhr.readyState;
29601         return !(state === 0 || state == 4);
29602     },
29603
29604     /**
29605      * Aborts any outstanding request.
29606      * @param {Object} request (Optional) defaults to the last request
29607      */
29608     abort : function(request) {
29609         var me = this,
29610             requests = me.requests,
29611             id;
29612
29613         if (request && me.isLoading(request)) {
29614             /**
29615              * Clear out the onreadystatechange here, this allows us
29616              * greater control, the browser may/may not fire the function
29617              * depending on a series of conditions.
29618              */
29619             request.xhr.onreadystatechange = null;
29620             request.xhr.abort();
29621             me.clearTimeout(request);
29622             if (!request.timedout) {
29623                 request.aborted = true;
29624             }
29625             me.onComplete(request);
29626             me.cleanup(request);
29627         } else if (!request) {
29628             for(id in requests) {
29629                 if (requests.hasOwnProperty(id)) {
29630                     me.abort(requests[id]);
29631                 }
29632             }
29633         }
29634     },
29635
29636     /**
29637      * Fires when the state of the xhr changes
29638      * @private
29639      * @param {Object} request The request
29640      */
29641     onStateChange : function(request) {
29642         if (request.xhr.readyState == 4) {
29643             this.clearTimeout(request);
29644             this.onComplete(request);
29645             this.cleanup(request);
29646         }
29647     },
29648
29649     /**
29650      * Clear the timeout on the request
29651      * @private
29652      * @param {Object} The request
29653      */
29654     clearTimeout: function(request){
29655         clearTimeout(request.timeout);
29656         delete request.timeout;
29657     },
29658
29659     /**
29660      * Clean up any left over information from the request
29661      * @private
29662      * @param {Object} The request
29663      */
29664     cleanup: function(request){
29665         request.xhr = null;
29666         delete request.xhr;
29667     },
29668
29669     /**
29670      * To be called when the request has come back from the server
29671      * @private
29672      * @param {Object} request
29673      * @return {Object} The response
29674      */
29675     onComplete : function(request) {
29676         var me = this,
29677             options = request.options,
29678             result = me.parseStatus(request.xhr.status),
29679             success = result.success,
29680             response;
29681
29682         if (success) {
29683             response = me.createResponse(request);
29684             me.fireEvent('requestcomplete', me, response, options);
29685             Ext.callback(options.success, options.scope, [response, options]);
29686         } else {
29687             if (result.isException || request.aborted || request.timedout) {
29688                 response = me.createException(request);
29689             } else {
29690                 response = me.createResponse(request);
29691             }
29692             me.fireEvent('requestexception', me, response, options);
29693             Ext.callback(options.failure, options.scope, [response, options]);
29694         }
29695         Ext.callback(options.callback, options.scope, [options, success, response]);
29696         delete me.requests[request.id];
29697         return response;
29698     },
29699
29700     /**
29701      * Check if the response status was successful
29702      * @param {Number} status The status code
29703      * @return {Object} An object containing success/status state
29704      */
29705     parseStatus: function(status) {
29706         // see: https://prototype.lighthouseapp.com/projects/8886/tickets/129-ie-mangles-http-response-status-code-204-to-1223
29707         status = status == 1223 ? 204 : status;
29708
29709         var success = (status >= 200 && status < 300) || status == 304,
29710             isException = false;
29711
29712         if (!success) {
29713             switch (status) {
29714                 case 12002:
29715                 case 12029:
29716                 case 12030:
29717                 case 12031:
29718                 case 12152:
29719                 case 13030:
29720                     isException = true;
29721                     break;
29722             }
29723         }
29724         return {
29725             success: success,
29726             isException: isException
29727         };
29728     },
29729
29730     /**
29731      * Create the response object
29732      * @private
29733      * @param {Object} request
29734      */
29735     createResponse : function(request) {
29736         var xhr = request.xhr,
29737             headers = {},
29738             lines = xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'),
29739             count = lines.length,
29740             line, index, key, value, response;
29741
29742         while (count--) {
29743             line = lines[count];
29744             index = line.indexOf(':');
29745             if(index >= 0) {
29746                 key = line.substr(0, index).toLowerCase();
29747                 if (line.charAt(index + 1) == ' ') {
29748                     ++index;
29749                 }
29750                 headers[key] = line.substr(index + 1);
29751             }
29752         }
29753
29754         request.xhr = null;
29755         delete request.xhr;
29756
29757         response = {
29758             request: request,
29759             requestId : request.id,
29760             status : xhr.status,
29761             statusText : xhr.statusText,
29762             getResponseHeader : function(header){ return headers[header.toLowerCase()]; },
29763             getAllResponseHeaders : function(){ return headers; },
29764             responseText : xhr.responseText,
29765             responseXML : xhr.responseXML
29766         };
29767
29768         // If we don't explicitly tear down the xhr reference, IE6/IE7 will hold this in the closure of the
29769         // functions created with getResponseHeader/getAllResponseHeaders
29770         xhr = null;
29771         return response;
29772     },
29773
29774     /**
29775      * Create the exception object
29776      * @private
29777      * @param {Object} request
29778      */
29779     createException : function(request) {
29780         return {
29781             request : request,
29782             requestId : request.id,
29783             status : request.aborted ? -1 : 0,
29784             statusText : request.aborted ? 'transaction aborted' : 'communication failure',
29785             aborted: request.aborted,
29786             timedout: request.timedout
29787         };
29788     }
29789 });
29790
29791 /**
29792  * @class Ext.Ajax
29793  * @singleton
29794  * @markdown
29795  * @extends Ext.data.Connection
29796
29797 A singleton instance of an {@link Ext.data.Connection}. This class
29798 is used to communicate with your server side code. It can be used as follows:
29799
29800     Ext.Ajax.request({
29801         url: 'page.php',
29802         params: {
29803             id: 1
29804         },
29805         success: function(response){
29806             var text = response.responseText;
29807             // process server response here
29808         }
29809     });
29810
29811 Default options for all requests can be set be changing a property on the Ext.Ajax class:
29812
29813     Ext.Ajax.timeout = 60000; // 60 seconds
29814
29815 Any options specified in the request method for the Ajax request will override any
29816 defaults set on the Ext.Ajax class. In the code sample below, the timeout for the
29817 request will be 60 seconds.
29818
29819     Ext.Ajax.timeout = 120000; // 120 seconds
29820     Ext.Ajax.request({
29821         url: 'page.aspx',
29822         timeout: 60000
29823     });
29824
29825 In general, this class will be used for all Ajax requests in your application.
29826 The main reason for creating a separate {@link Ext.data.Connection} is for a
29827 series of requests that share common settings that are different to all other
29828 requests in the application.
29829
29830  */
29831 Ext.define('Ext.Ajax', {
29832     extend: 'Ext.data.Connection',
29833     singleton: true,
29834
29835     /**
29836      * @cfg {String} url @hide
29837      */
29838     /**
29839      * @cfg {Object} extraParams @hide
29840      */
29841     /**
29842      * @cfg {Object} defaultHeaders @hide
29843      */
29844     /**
29845      * @cfg {String} method (Optional) @hide
29846      */
29847     /**
29848      * @cfg {Number} timeout (Optional) @hide
29849      */
29850     /**
29851      * @cfg {Boolean} autoAbort (Optional) @hide
29852      */
29853
29854     /**
29855      * @cfg {Boolean} disableCaching (Optional) @hide
29856      */
29857
29858     /**
29859      * @property  disableCaching
29860      * True to add a unique cache-buster param to GET requests. (defaults to true)
29861      * @type Boolean
29862      */
29863     /**
29864      * @property  url
29865      * The default URL to be used for requests to the server. (defaults to undefined)
29866      * If the server receives all requests through one URL, setting this once is easier than
29867      * entering it on every request.
29868      * @type String
29869      */
29870     /**
29871      * @property  extraParams
29872      * An object containing properties which are used as extra parameters to each request made
29873      * by this object (defaults to undefined). Session information and other data that you need
29874      * to pass with each request are commonly put here.
29875      * @type Object
29876      */
29877     /**
29878      * @property  defaultHeaders
29879      * An object containing request headers which are added to each request made by this object
29880      * (defaults to undefined).
29881      * @type Object
29882      */
29883     /**
29884      * @property  method
29885      * The default HTTP method to be used for requests. Note that this is case-sensitive and
29886      * should be all caps (defaults to undefined; if not set but params are present will use
29887      * <tt>"POST"</tt>, otherwise will use <tt>"GET"</tt>.)
29888      * @type String
29889      */
29890     /**
29891      * @property  timeout
29892      * The timeout in milliseconds to be used for requests. (defaults to 30000)
29893      * @type Number
29894      */
29895
29896     /**
29897      * @property  autoAbort
29898      * Whether a new request should abort any pending requests. (defaults to false)
29899      * @type Boolean
29900      */
29901     autoAbort : false
29902 });
29903 /**
29904  * @author Ed Spencer
29905  * @class Ext.data.Association
29906  * @extends Object
29907  *
29908  * <p>Associations enable you to express relationships between different {@link Ext.data.Model Models}. Let's say we're
29909  * writing an ecommerce system where Users can make Orders - there's a relationship between these Models that we can
29910  * express like this:</p>
29911  *
29912 <pre><code>
29913 Ext.define('User', {
29914     extend: 'Ext.data.Model',
29915     fields: ['id', 'name', 'email'],
29916
29917     hasMany: {model: 'Order', name: 'orders'}
29918 });
29919
29920 Ext.define('Order', {
29921     extend: 'Ext.data.Model',
29922     fields: ['id', 'user_id', 'status', 'price'],
29923
29924     belongsTo: 'User'
29925 });
29926 </code></pre>
29927  *
29928  * <p>We've set up two models - User and Order - and told them about each other. You can set up as many associations on
29929  * each Model as you need using the two default types - {@link Ext.data.HasManyAssociation hasMany} and
29930  * {@link Ext.data.BelongsToAssociation belongsTo}. There's much more detail on the usage of each of those inside their
29931  * documentation pages. If you're not familiar with Models already, {@link Ext.data.Model there is plenty on those too}.</p>
29932  *
29933  * <p><u>Further Reading</u></p>
29934  *
29935  * <ul style="list-style-type: disc; padding-left: 20px;">
29936  *   <li>{@link Ext.data.HasManyAssociation hasMany associations}
29937  *   <li>{@link Ext.data.BelongsToAssociation belongsTo associations}
29938  *   <li>{@link Ext.data.Model using Models}
29939  * </ul>
29940  * 
29941  * <b>Self association models</b>
29942  * <p>We can also have models that create parent/child associations between the same type. Below is an example, where
29943  * groups can be nested inside other groups:</p>
29944  * <pre><code>
29945
29946 // Server Data
29947 {
29948     "groups": {
29949         "id": 10,
29950         "parent_id": 100,
29951         "name": "Main Group",
29952         "parent_group": {
29953             "id": 100,
29954             "parent_id": null,
29955             "name": "Parent Group"
29956         },
29957         "child_groups": [{
29958             "id": 2,
29959             "parent_id": 10,
29960             "name": "Child Group 1"
29961         },{
29962             "id": 3,
29963             "parent_id": 10,
29964             "name": "Child Group 2"
29965         },{
29966             "id": 4,
29967             "parent_id": 10,
29968             "name": "Child Group 3"
29969         }]
29970     }
29971 }
29972
29973 // Client code
29974 Ext.define('Group', {
29975     extend: 'Ext.data.Model',
29976     fields: ['id', 'parent_id', 'name'],
29977     proxy: {
29978         type: 'ajax',
29979         url: 'data.json',
29980         reader: {
29981             type: 'json',
29982             root: 'groups'
29983         }
29984     },
29985     associations: [{
29986         type: 'hasMany',
29987         model: 'Group',
29988         primaryKey: 'id',
29989         foreignKey: 'parent_id',
29990         autoLoad: true,
29991         associationKey: 'child_groups' // read child data from child_groups
29992     }, {
29993         type: 'belongsTo',
29994         model: 'Group',
29995         primaryKey: 'id',
29996         foreignKey: 'parent_id',
29997         autoLoad: true,
29998         associationKey: 'parent_group' // read parent data from parent_group
29999     }]
30000 });
30001
30002
30003 Ext.onReady(function(){
30004     
30005     Group.load(10, {
30006         success: function(group){
30007             console.log(group.getGroup().get('name'));
30008             
30009             group.groups().each(function(rec){
30010                 console.log(rec.get('name'));
30011             });
30012         }
30013     });
30014     
30015 });
30016  * </code></pre>
30017  *
30018  * @constructor
30019  * @param {Object} config Optional config object
30020  */
30021 Ext.define('Ext.data.Association', {
30022     /**
30023      * @cfg {String} ownerModel The string name of the model that owns the association. Required
30024      */
30025
30026     /**
30027      * @cfg {String} associatedModel The string name of the model that is being associated with. Required
30028      */
30029
30030     /**
30031      * @cfg {String} primaryKey The name of the primary key on the associated model. Defaults to 'id'.
30032      * In general this will be the {@link Ext.data.Model#idProperty} of the Model.
30033      */
30034     primaryKey: 'id',
30035
30036     /**
30037      * @cfg {Ext.data.reader.Reader} reader A special reader to read associated data
30038      */
30039     
30040     /**
30041      * @cfg {String} associationKey The name of the property in the data to read the association from.
30042      * Defaults to the name of the associated model.
30043      */
30044
30045     defaultReaderType: 'json',
30046
30047     statics: {
30048         create: function(association){
30049             if (!association.isAssociation) {
30050                 if (Ext.isString(association)) {
30051                     association = {
30052                         type: association
30053                     };
30054                 }
30055
30056                 switch (association.type) {
30057                     case 'belongsTo':
30058                         return Ext.create('Ext.data.BelongsToAssociation', association);
30059                     case 'hasMany':
30060                         return Ext.create('Ext.data.HasManyAssociation', association);
30061                     //TODO Add this back when it's fixed
30062 //                    case 'polymorphic':
30063 //                        return Ext.create('Ext.data.PolymorphicAssociation', association);
30064                     default:
30065                         Ext.Error.raise('Unknown Association type: "' + association.type + '"');
30066                 }
30067             }
30068             return association;
30069         }
30070     },
30071
30072     constructor: function(config) {
30073         Ext.apply(this, config);
30074
30075         var types           = Ext.ModelManager.types,
30076             ownerName       = config.ownerModel,
30077             associatedName  = config.associatedModel,
30078             ownerModel      = types[ownerName],
30079             associatedModel = types[associatedName],
30080             ownerProto;
30081
30082         if (ownerModel === undefined) {
30083             Ext.Error.raise("The configured ownerModel was not valid (you tried " + ownerName + ")");
30084         }
30085         if (associatedModel === undefined) {
30086             Ext.Error.raise("The configured associatedModel was not valid (you tried " + associatedName + ")");
30087         }
30088
30089         this.ownerModel = ownerModel;
30090         this.associatedModel = associatedModel;
30091
30092         /**
30093          * The name of the model that 'owns' the association
30094          * @property ownerName
30095          * @type String
30096          */
30097
30098         /**
30099          * The name of the model is on the other end of the association (e.g. if a User model hasMany Orders, this is 'Order')
30100          * @property associatedName
30101          * @type String
30102          */
30103
30104         Ext.applyIf(this, {
30105             ownerName : ownerName,
30106             associatedName: associatedName
30107         });
30108     },
30109
30110     /**
30111      * Get a specialized reader for reading associated data
30112      * @return {Ext.data.reader.Reader} The reader, null if not supplied
30113      */
30114     getReader: function(){
30115         var me = this,
30116             reader = me.reader,
30117             model = me.associatedModel;
30118
30119         if (reader) {
30120             if (Ext.isString(reader)) {
30121                 reader = {
30122                     type: reader
30123                 };
30124             }
30125             if (reader.isReader) {
30126                 reader.setModel(model);
30127             } else {
30128                 Ext.applyIf(reader, {
30129                     model: model,
30130                     type : me.defaultReaderType
30131                 });
30132             }
30133             me.reader = Ext.createByAlias('reader.' + reader.type, reader);
30134         }
30135         return me.reader || null;
30136     }
30137 });
30138
30139 /**
30140  * @author Ed Spencer
30141  * @class Ext.ModelManager
30142  * @extends Ext.AbstractManager
30143
30144 The ModelManager keeps track of all {@link Ext.data.Model} types defined in your application.
30145
30146 __Creating Model Instances__
30147 Model instances can be created by using the {@link #create} function. It is also possible to do
30148 this by using the Model type directly. The following snippets are equivalent:
30149
30150     Ext.define('User', {
30151         extend: 'Ext.data.Model',
30152         fields: ['first', 'last']
30153     });
30154     
30155     // method 1, create through the manager
30156     Ext.ModelManager.create({
30157         first: 'Ed',
30158         last: 'Spencer'
30159     }, 'User');
30160     
30161     // method 2, create on the type directly
30162     new User({
30163         first: 'Ed',
30164         last: 'Spencer'
30165     });
30166     
30167 __Accessing Model Types__
30168 A reference to a Model type can be obtained by using the {@link #getModel} function. Since models types
30169 are normal classes, you can access the type directly. The following snippets are equivalent:
30170
30171     Ext.define('User', {
30172         extend: 'Ext.data.Model',
30173         fields: ['first', 'last']
30174     });
30175     
30176     // method 1, access model type through the manager
30177     var UserType = Ext.ModelManager.getModel('User');
30178     
30179     // method 2, reference the type directly
30180     var UserType = User;
30181
30182  * @markdown
30183  * @singleton
30184  */
30185 Ext.define('Ext.ModelManager', {
30186     extend: 'Ext.AbstractManager',
30187     alternateClassName: 'Ext.ModelMgr',
30188     requires: ['Ext.data.Association'],
30189     
30190     singleton: true,
30191     
30192     typeName: 'mtype',
30193     
30194     /**
30195      * Private stack of associations that must be created once their associated model has been defined
30196      * @property associationStack
30197      * @type Array
30198      */
30199     associationStack: [],
30200     
30201     /**
30202      * Registers a model definition. All model plugins marked with isDefault: true are bootstrapped
30203      * immediately, as are any addition plugins defined in the model config.
30204      * @private
30205      */
30206     registerType: function(name, config) {
30207         var proto = config.prototype,
30208             model;
30209         if (proto && proto.isModel) {
30210             // registering an already defined model
30211             model = config;
30212         } else {
30213             // passing in a configuration
30214             if (!config.extend) {
30215                 config.extend = 'Ext.data.Model';
30216             }
30217             model = Ext.define(name, config);
30218         }
30219         this.types[name] = model;
30220         return model;
30221     },
30222     
30223     /**
30224      * @private
30225      * Private callback called whenever a model has just been defined. This sets up any associations
30226      * that were waiting for the given model to be defined
30227      * @param {Function} model The model that was just created
30228      */
30229     onModelDefined: function(model) {
30230         var stack  = this.associationStack,
30231             length = stack.length,
30232             create = [],
30233             association, i, created;
30234         
30235         for (i = 0; i < length; i++) {
30236             association = stack[i];
30237             
30238             if (association.associatedModel == model.modelName) {
30239                 create.push(association);
30240             }
30241         }
30242         
30243         for (i = 0, length = create.length; i < length; i++) {
30244             created = create[i];
30245             this.types[created.ownerModel].prototype.associations.add(Ext.data.Association.create(created));
30246             Ext.Array.remove(stack, created);
30247         }
30248     },
30249     
30250     /**
30251      * Registers an association where one of the models defined doesn't exist yet.
30252      * The ModelManager will check when new models are registered if it can link them
30253      * together
30254      * @private
30255      * @param {Ext.data.Association} association The association
30256      */
30257     registerDeferredAssociation: function(association){
30258         this.associationStack.push(association);
30259     },
30260     
30261     /**
30262      * Returns the {@link Ext.data.Model} for a given model name
30263      * @param {String/Object} id The id of the model or the model instance.
30264      */
30265     getModel: function(id) {
30266         var model = id;
30267         if (typeof model == 'string') {
30268             model = this.types[model];
30269         }
30270         return model;
30271     },
30272     
30273     /**
30274      * Creates a new instance of a Model using the given data.
30275      * @param {Object} data Data to initialize the Model's fields with
30276      * @param {String} name The name of the model to create
30277      * @param {Number} id Optional unique id of the Model instance (see {@link Ext.data.Model})
30278      */
30279     create: function(config, name, id) {
30280         var con = typeof name == 'function' ? name : this.types[name || config.name];
30281         
30282         return new con(config, id);
30283     }
30284 }, function() {
30285     
30286     /**
30287      * Creates a new Model class from the specified config object. See {@link Ext.data.Model} for full examples.
30288      * 
30289      * @param {Object} config A configuration object for the Model you wish to create.
30290      * @return {Ext.data.Model} The newly registered Model
30291      * @member Ext
30292      * @method regModel
30293      */
30294     Ext.regModel = function() {
30295         if (Ext.isDefined(Ext.global.console)) {
30296             Ext.global.console.warn('Ext.regModel has been deprecated. Models can now be created by extending Ext.data.Model: Ext.define("MyModel", {extend: "Ext.data.Model", fields: []});.');
30297         }
30298         return this.ModelManager.registerType.apply(this.ModelManager, arguments);
30299     };
30300 });
30301
30302 /**
30303  * @class Ext.app.Controller
30304  * @constructor
30305  * 
30306  * Controllers are the glue that binds an application together. All they really do is listen for events (usually from
30307  * views) and take some action. Here's how we might create a Controller to manage Users:
30308  * 
30309  *     Ext.define('MyApp.controller.Users', {
30310  *         extend: 'Ext.app.Controller',
30311  * 
30312  *         init: function() {
30313  *             console.log('Initialized Users! This happens before the Application launch function is called');
30314  *         }
30315  *     });
30316  * 
30317  * The init function is a special method that is called when your application boots. It is called before the 
30318  * {@link Ext.app.Application Application}'s launch function is executed so gives a hook point to run any code before
30319  * your Viewport is created.
30320  * 
30321  * The init function is a great place to set up how your controller interacts with the view, and is usually used in 
30322  * conjunction with another Controller function - {@link Ext.app.Controller#control control}. The control function 
30323  * makes it easy to listen to events on your view classes and take some action with a handler function. Let's update
30324  * our Users controller to tell us when the panel is rendered:
30325  * 
30326  *     Ext.define('MyApp.controller.Users', {
30327  *         extend: 'Ext.app.Controller',
30328  * 
30329  *         init: function() {
30330  *             this.control({
30331  *                 'viewport > panel': {
30332  *                     render: this.onPanelRendered
30333  *                 }
30334  *             });
30335  *         },
30336  * 
30337  *         onPanelRendered: function() {
30338  *             console.log('The panel was rendered');
30339  *         }
30340  *     });
30341  * 
30342  * We've updated the init function to use this.control to set up listeners on views in our application. The control
30343  * function uses the new ComponentQuery engine to quickly and easily get references to components on the page. If you
30344  * are not familiar with ComponentQuery yet, be sure to check out THIS GUIDE for a full explanation. In brief though,
30345  * it allows us to pass a CSS-like selector that will find every matching component on the page.
30346  * 
30347  * In our init function above we supplied 'viewport > panel', which translates to "find me every Panel that is a direct
30348  * child of a Viewport". We then supplied an object that maps event names (just 'render' in this case) to handler 
30349  * functions. The overall effect is that whenever any component that matches our selector fires a 'render' event, our 
30350  * onPanelRendered function is called.
30351  * 
30352  * <u>Using refs</u>
30353  * 
30354  * One of the most useful parts of Controllers is the new ref system. These use the new {@link Ext.ComponentQuery} to
30355  * make it really easy to get references to Views on your page. Let's look at an example of this now:
30356  * 
30357  * Ext.define('MyApp.controller.Users', {
30358      extend: 'Ext.app.Controller',
30359
30360      refs: [
30361          {
30362              ref: 'list',
30363              selector: 'grid'
30364          }
30365      ],
30366
30367      init: function() {
30368          this.control({
30369              'button': {
30370                  click: this.refreshGrid
30371              }
30372          });
30373      },
30374
30375      refreshGrid: function() {
30376          this.getList().store.load();
30377      }
30378  });
30379  * 
30380  * This example assumes the existence of a {@link Ext.grid.Panel Grid} on the page, which contains a single button to 
30381  * refresh the Grid when clicked. In our refs array, we set up a reference to the grid. There are two parts to this - 
30382  * the 'selector', which is a {@link Ext.ComponentQuery ComponentQuery} selector which finds any grid on the page and
30383  * assigns it to the reference 'list'.
30384  * 
30385  * By giving the reference a name, we get a number of things for free. The first is the getList function that we use in
30386  * the refreshGrid method above. This is generated automatically by the Controller based on the name of our ref, which 
30387  * was capitalized and prepended with get to go from 'list' to 'getList'.
30388  * 
30389  * The way this works is that the first time getList is called by your code, the ComponentQuery selector is run and the
30390  * first component that matches the selector ('grid' in this case) will be returned. All future calls to getList will 
30391  * use a cached reference to that grid. Usually it is advised to use a specific ComponentQuery selector that will only
30392  * match a single View in your application (in the case above our selector will match any grid on the page).
30393  * 
30394  * Bringing it all together, our init function is called when the application boots, at which time we call this.control
30395  * to listen to any click on a {@link Ext.button.Button button} and call our refreshGrid function (again, this will 
30396  * match any button on the page so we advise a more specific selector than just 'button', but have left it this way for
30397  * simplicity). When the button is clicked we use out getList function to refresh the grid.
30398  * 
30399  * You can create any number of refs and control any number of components this way, simply adding more functions to 
30400  * your Controller as you go. For an example of real-world usage of Controllers see the Feed Viewer example in the 
30401  * examples/app/feed-viewer folder in the SDK download.
30402  * 
30403  * <u>Generated getter methods</u>
30404  * 
30405  * Refs aren't the only thing that generate convenient getter methods. Controllers often have to deal with Models and 
30406  * Stores so the framework offers a couple of easy ways to get access to those too. Let's look at another example:
30407  * 
30408  * Ext.define('MyApp.controller.Users', {
30409      extend: 'Ext.app.Controller',
30410
30411      models: ['User'],
30412      stores: ['AllUsers', 'AdminUsers'],
30413
30414      init: function() {
30415          var User = this.getUserModel(),
30416              allUsers = this.getAllUsersStore();
30417
30418          var ed = new User({name: 'Ed'});
30419          allUsers.add(ed);
30420      }
30421  });
30422  * 
30423  * By specifying Models and Stores that the Controller cares about, it again dynamically loads them from the appropriate
30424  * locations (app/model/User.js, app/store/AllUsers.js and app/store/AdminUsers.js in this case) and creates getter 
30425  * functions for them all. The example above will create a new User model instance and add it to the AllUsers Store.
30426  * Of course, you could do anything in this function but in this case we just did something simple to demonstrate the 
30427  * functionality.
30428  * 
30429  * <u>Further Reading</u>
30430  * 
30431  * For more information about writing Ext JS 4 applications, please see the <a href="../guide/application_architecture">
30432  * application architecture guide</a>. Also see the {@link Ext.app.Application} documentation.
30433  * 
30434  * @markdown
30435  * @docauthor Ed Spencer
30436  */  
30437 Ext.define('Ext.app.Controller', {
30438     /**
30439      * @cfg {Object} id The id of this controller. You can use this id when dispatching.
30440      */
30441
30442     mixins: {
30443         observable: 'Ext.util.Observable'
30444     },
30445
30446     onClassExtended: function(cls, data) {
30447         var className = Ext.getClassName(cls),
30448             match = className.match(/^(.*)\.controller\./);
30449
30450         if (match !== null) {
30451             var namespace = Ext.Loader.getPrefix(className) || match[1],
30452                 onBeforeClassCreated = data.onBeforeClassCreated,
30453                 requires = [],
30454                 modules = ['model', 'view', 'store'],
30455                 prefix;
30456
30457             data.onBeforeClassCreated = function(cls, data) {
30458                 var i, ln, module,
30459                     items, j, subLn, item;
30460
30461                 for (i = 0,ln = modules.length; i < ln; i++) {
30462                     module = modules[i];
30463
30464                     items = Ext.Array.from(data[module + 's']);
30465
30466                     for (j = 0,subLn = items.length; j < subLn; j++) {
30467                         item = items[j];
30468
30469                         prefix = Ext.Loader.getPrefix(item);
30470
30471                         if (prefix === '' || prefix === item) {
30472                             requires.push(namespace + '.' + module + '.' + item);
30473                         }
30474                         else {
30475                             requires.push(item);
30476                         }
30477                     }
30478                 }
30479
30480                 Ext.require(requires, Ext.Function.pass(onBeforeClassCreated, arguments, this));
30481             };
30482         }
30483     },
30484
30485     constructor: function(config) {
30486         this.mixins.observable.constructor.call(this, config);
30487
30488         Ext.apply(this, config || {});
30489
30490         this.createGetters('model', this.models);
30491         this.createGetters('store', this.stores);
30492         this.createGetters('view', this.views);
30493
30494         if (this.refs) {
30495             this.ref(this.refs);
30496         }
30497     },
30498
30499     // Template method
30500     init: function(application) {},
30501     // Template method
30502     onLaunch: function(application) {},
30503
30504     createGetters: function(type, refs) {
30505         type = Ext.String.capitalize(type);
30506         Ext.Array.each(refs, function(ref) {
30507             var fn = 'get',
30508                 parts = ref.split('.');
30509
30510             // Handle namespaced class names. E.g. feed.Add becomes getFeedAddView etc.
30511             Ext.Array.each(parts, function(part) {
30512                 fn += Ext.String.capitalize(part);
30513             });
30514             fn += type;
30515
30516             if (!this[fn]) {
30517                 this[fn] = Ext.Function.pass(this['get' + type], [ref], this);
30518             }
30519             // Execute it right away
30520             this[fn](ref);
30521         },
30522         this);
30523     },
30524
30525     ref: function(refs) {
30526         var me = this;
30527         refs = Ext.Array.from(refs);
30528         Ext.Array.each(refs, function(info) {
30529             var ref = info.ref,
30530                 fn = 'get' + Ext.String.capitalize(ref);
30531             if (!me[fn]) {
30532                 me[fn] = Ext.Function.pass(me.getRef, [ref, info], me);
30533             }
30534         });
30535     },
30536
30537     getRef: function(ref, info, config) {
30538         this.refCache = this.refCache || {};
30539         info = info || {};
30540         config = config || {};
30541
30542         Ext.apply(info, config);
30543
30544         if (info.forceCreate) {
30545             return Ext.ComponentManager.create(info, 'component');
30546         }
30547
30548         var me = this,
30549             selector = info.selector,
30550             cached = me.refCache[ref];
30551
30552         if (!cached) {
30553             me.refCache[ref] = cached = Ext.ComponentQuery.query(info.selector)[0];
30554             if (!cached && info.autoCreate) {
30555                 me.refCache[ref] = cached = Ext.ComponentManager.create(info, 'component');
30556             }
30557             if (cached) {
30558                 cached.on('beforedestroy', function() {
30559                     me.refCache[ref] = null;
30560                 });
30561             }
30562         }
30563
30564         return cached;
30565     },
30566
30567     control: function(selectors, listeners) {
30568         this.application.control(selectors, listeners, this);
30569     },
30570
30571     getController: function(name) {
30572         return this.application.getController(name);
30573     },
30574
30575     getStore: function(name) {
30576         return this.application.getStore(name);
30577     },
30578
30579     getModel: function(model) {
30580         return this.application.getModel(model);
30581     },
30582
30583     getView: function(view) {
30584         return this.application.getView(view);
30585     }
30586 });
30587
30588 /**
30589  * @class Ext.data.SortTypes
30590  * This class defines a series of static methods that are used on a
30591  * {@link Ext.data.Field} for performing sorting. The methods cast the 
30592  * underlying values into a data type that is appropriate for sorting on
30593  * that particular field.  If a {@link Ext.data.Field#type} is specified, 
30594  * the sortType will be set to a sane default if the sortType is not 
30595  * explicitly defined on the field. The sortType will make any necessary
30596  * modifications to the value and return it.
30597  * <ul>
30598  * <li><b>asText</b> - Removes any tags and converts the value to a string</li>
30599  * <li><b>asUCText</b> - Removes any tags and converts the value to an uppercase string</li>
30600  * <li><b>asUCText</b> - Converts the value to an uppercase string</li>
30601  * <li><b>asDate</b> - Converts the value into Unix epoch time</li>
30602  * <li><b>asFloat</b> - Converts the value to a floating point number</li>
30603  * <li><b>asInt</b> - Converts the value to an integer number</li>
30604  * </ul>
30605  * <p>
30606  * It is also possible to create a custom sortType that can be used throughout
30607  * an application.
30608  * <pre><code>
30609 Ext.apply(Ext.data.SortTypes, {
30610     asPerson: function(person){
30611         // expects an object with a first and last name property
30612         return person.lastName.toUpperCase() + person.firstName.toLowerCase();
30613     }    
30614 });
30615
30616 Ext.define('Employee', {
30617     extend: 'Ext.data.Model',
30618     fields: [{
30619         name: 'person',
30620         sortType: 'asPerson'
30621     }, {
30622         name: 'salary',
30623         type: 'float' // sortType set to asFloat
30624     }]
30625 });
30626  * </code></pre>
30627  * </p>
30628  * @singleton
30629  * @docauthor Evan Trimboli <evan@sencha.com>
30630  */
30631 Ext.define('Ext.data.SortTypes', {
30632     
30633     singleton: true,
30634     
30635     /**
30636      * Default sort that does nothing
30637      * @param {Mixed} s The value being converted
30638      * @return {Mixed} The comparison value
30639      */
30640     none : function(s) {
30641         return s;
30642     },
30643
30644     /**
30645      * The regular expression used to strip tags
30646      * @type {RegExp}
30647      * @property
30648      */
30649     stripTagsRE : /<\/?[^>]+>/gi,
30650
30651     /**
30652      * Strips all HTML tags to sort on text only
30653      * @param {Mixed} s The value being converted
30654      * @return {String} The comparison value
30655      */
30656     asText : function(s) {
30657         return String(s).replace(this.stripTagsRE, "");
30658     },
30659
30660     /**
30661      * Strips all HTML tags to sort on text only - Case insensitive
30662      * @param {Mixed} s The value being converted
30663      * @return {String} The comparison value
30664      */
30665     asUCText : function(s) {
30666         return String(s).toUpperCase().replace(this.stripTagsRE, "");
30667     },
30668
30669     /**
30670      * Case insensitive string
30671      * @param {Mixed} s The value being converted
30672      * @return {String} The comparison value
30673      */
30674     asUCString : function(s) {
30675         return String(s).toUpperCase();
30676     },
30677
30678     /**
30679      * Date sorting
30680      * @param {Mixed} s The value being converted
30681      * @return {Number} The comparison value
30682      */
30683     asDate : function(s) {
30684         if(!s){
30685             return 0;
30686         }
30687         if(Ext.isDate(s)){
30688             return s.getTime();
30689         }
30690         return Date.parse(String(s));
30691     },
30692
30693     /**
30694      * Float sorting
30695      * @param {Mixed} s The value being converted
30696      * @return {Float} The comparison value
30697      */
30698     asFloat : function(s) {
30699         var val = parseFloat(String(s).replace(/,/g, ""));
30700         return isNaN(val) ? 0 : val;
30701     },
30702
30703     /**
30704      * Integer sorting
30705      * @param {Mixed} s The value being converted
30706      * @return {Number} The comparison value
30707      */
30708     asInt : function(s) {
30709         var val = parseInt(String(s).replace(/,/g, ""), 10);
30710         return isNaN(val) ? 0 : val;
30711     }
30712 });
30713 /**
30714  * @author Ed Spencer
30715  * @class Ext.data.Errors
30716  * @extends Ext.util.MixedCollection
30717  * 
30718  * <p>Wraps a collection of validation error responses and provides convenient functions for
30719  * accessing and errors for specific fields.</p>
30720  * 
30721  * <p>Usually this class does not need to be instantiated directly - instances are instead created
30722  * automatically when {@link Ext.data.Model#validate validate} on a model instance:</p>
30723  * 
30724 <pre><code>
30725 //validate some existing model instance - in this case it returned 2 failures messages
30726 var errors = myModel.validate();
30727
30728 errors.isValid(); //false
30729
30730 errors.length; //2
30731 errors.getByField('name');  // [{field: 'name',  error: 'must be present'}]
30732 errors.getByField('title'); // [{field: 'title', error: 'is too short'}]
30733 </code></pre>
30734  */
30735 Ext.define('Ext.data.Errors', {
30736     extend: 'Ext.util.MixedCollection',
30737     
30738     /**
30739      * Returns true if there are no errors in the collection
30740      * @return {Boolean} 
30741      */
30742     isValid: function() {
30743         return this.length === 0;
30744     },
30745     
30746     /**
30747      * Returns all of the errors for the given field
30748      * @param {String} fieldName The field to get errors for
30749      * @return {Array} All errors for the given field
30750      */
30751     getByField: function(fieldName) {
30752         var errors = [],
30753             error, field, i;
30754             
30755         for (i = 0; i < this.length; i++) {
30756             error = this.items[i];
30757             
30758             if (error.field == fieldName) {
30759                 errors.push(error);
30760             }
30761         }
30762         
30763         return errors;
30764     }
30765 });
30766
30767 /**
30768  * @author Ed Spencer
30769  * @class Ext.data.Operation
30770  * @extends Object
30771  * 
30772  * <p>Represents a single read or write operation performed by a {@link Ext.data.proxy.Proxy Proxy}.
30773  * Operation objects are used to enable communication between Stores and Proxies. Application
30774  * developers should rarely need to interact with Operation objects directly.</p>
30775  * 
30776  * <p>Several Operations can be batched together in a {@link Ext.data.Batch batch}.</p>
30777  * 
30778  * @constructor
30779  * @param {Object} config Optional config object
30780  */
30781 Ext.define('Ext.data.Operation', {
30782     /**
30783      * @cfg {Boolean} synchronous True if this Operation is to be executed synchronously (defaults to true). This
30784      * property is inspected by a {@link Ext.data.Batch Batch} to see if a series of Operations can be executed in
30785      * parallel or not.
30786      */
30787     synchronous: true,
30788     
30789     /**
30790      * @cfg {String} action The action being performed by this Operation. Should be one of 'create', 'read', 'update' or 'destroy'
30791      */
30792     action: undefined,
30793     
30794     /**
30795      * @cfg {Array} filters Optional array of filter objects. Only applies to 'read' actions.
30796      */
30797     filters: undefined,
30798     
30799     /**
30800      * @cfg {Array} sorters Optional array of sorter objects. Only applies to 'read' actions.
30801      */
30802     sorters: undefined,
30803     
30804     /**
30805      * @cfg {Object} group Optional grouping configuration. Only applies to 'read' actions where grouping is desired.
30806      */
30807     group: undefined,
30808     
30809     /**
30810      * @cfg {Number} start The start index (offset), used in paging when running a 'read' action.
30811      */
30812     start: undefined,
30813     
30814     /**
30815      * @cfg {Number} limit The number of records to load. Used on 'read' actions when paging is being used.
30816      */
30817     limit: undefined,
30818     
30819     /**
30820      * @cfg {Ext.data.Batch} batch The batch that this Operation is a part of (optional)
30821      */
30822     batch: undefined,
30823         
30824     /**
30825      * Read-only property tracking the start status of this Operation. Use {@link #isStarted}.
30826      * @property started
30827      * @type Boolean
30828      * @private
30829      */
30830     started: false,
30831     
30832     /**
30833      * Read-only property tracking the run status of this Operation. Use {@link #isRunning}.
30834      * @property running
30835      * @type Boolean
30836      * @private
30837      */
30838     running: false,
30839     
30840     /**
30841      * Read-only property tracking the completion status of this Operation. Use {@link #isComplete}.
30842      * @property complete
30843      * @type Boolean
30844      * @private
30845      */
30846     complete: false,
30847     
30848     /**
30849      * Read-only property tracking whether the Operation was successful or not. This starts as undefined and is set to true
30850      * or false by the Proxy that is executing the Operation. It is also set to false by {@link #setException}. Use
30851      * {@link #wasSuccessful} to query success status.
30852      * @property success
30853      * @type Boolean
30854      * @private
30855      */
30856     success: undefined,
30857     
30858     /**
30859      * Read-only property tracking the exception status of this Operation. Use {@link #hasException} and see {@link #getError}.
30860      * @property exception
30861      * @type Boolean
30862      * @private
30863      */
30864     exception: false,
30865     
30866     /**
30867      * The error object passed when {@link #setException} was called. This could be any object or primitive.
30868      * @property error
30869      * @type Mixed
30870      * @private
30871      */
30872     error: undefined,
30873     
30874     constructor: function(config) {
30875         Ext.apply(this, config || {});
30876     },
30877     
30878     /**
30879      * Marks the Operation as started
30880      */
30881     setStarted: function() {
30882         this.started = true;
30883         this.running = true;
30884     },
30885     
30886     /**
30887      * Marks the Operation as completed
30888      */
30889     setCompleted: function() {
30890         this.complete = true;
30891         this.running  = false;
30892     },
30893     
30894     /**
30895      * Marks the Operation as successful
30896      */
30897     setSuccessful: function() {
30898         this.success = true;
30899     },
30900     
30901     /**
30902      * Marks the Operation as having experienced an exception. Can be supplied with an option error message/object.
30903      * @param {Mixed} error Optional error string/object
30904      */
30905     setException: function(error) {
30906         this.exception = true;
30907         this.success = false;
30908         this.running = false;
30909         this.error = error;
30910     },
30911     
30912     /**
30913      * Returns true if this Operation encountered an exception (see also {@link #getError})
30914      * @return {Boolean} True if there was an exception
30915      */
30916     hasException: function() {
30917         return this.exception === true;
30918     },
30919     
30920     /**
30921      * Returns the error string or object that was set using {@link #setException}
30922      * @return {Mixed} The error object
30923      */
30924     getError: function() {
30925         return this.error;
30926     },
30927     
30928     /**
30929      * Returns an array of Ext.data.Model instances as set by the Proxy.
30930      * @return {Array} Any loaded Records
30931      */
30932     getRecords: function() {
30933         var resultSet = this.getResultSet();
30934         
30935         return (resultSet === undefined ? this.records : resultSet.records);
30936     },
30937     
30938     /**
30939      * Returns the ResultSet object (if set by the Proxy). This object will contain the {@link Ext.data.Model model} instances
30940      * as well as meta data such as number of instances fetched, number available etc
30941      * @return {Ext.data.ResultSet} The ResultSet object
30942      */
30943     getResultSet: function() {
30944         return this.resultSet;
30945     },
30946     
30947     /**
30948      * Returns true if the Operation has been started. Note that the Operation may have started AND completed,
30949      * see {@link #isRunning} to test if the Operation is currently running.
30950      * @return {Boolean} True if the Operation has started
30951      */
30952     isStarted: function() {
30953         return this.started === true;
30954     },
30955     
30956     /**
30957      * Returns true if the Operation has been started but has not yet completed.
30958      * @return {Boolean} True if the Operation is currently running
30959      */
30960     isRunning: function() {
30961         return this.running === true;
30962     },
30963     
30964     /**
30965      * Returns true if the Operation has been completed
30966      * @return {Boolean} True if the Operation is complete
30967      */
30968     isComplete: function() {
30969         return this.complete === true;
30970     },
30971     
30972     /**
30973      * Returns true if the Operation has completed and was successful
30974      * @return {Boolean} True if successful
30975      */
30976     wasSuccessful: function() {
30977         return this.isComplete() && this.success === true;
30978     },
30979     
30980     /**
30981      * @private
30982      * Associates this Operation with a Batch
30983      * @param {Ext.data.Batch} batch The batch
30984      */
30985     setBatch: function(batch) {
30986         this.batch = batch;
30987     },
30988     
30989     /**
30990      * Checks whether this operation should cause writing to occur.
30991      * @return {Boolean} Whether the operation should cause a write to occur.
30992      */
30993     allowWrite: function() {
30994         return this.action != 'read';
30995     }
30996 });
30997 /**
30998  * @author Ed Spencer
30999  * @class Ext.data.validations
31000  * @extends Object
31001  * 
31002  * <p>This singleton contains a set of validation functions that can be used to validate any type
31003  * of data. They are most often used in {@link Ext.data.Model Models}, where they are automatically
31004  * set up and executed.</p>
31005  */
31006 Ext.define('Ext.data.validations', {
31007     singleton: true,
31008     
31009     /**
31010      * The default error message used when a presence validation fails
31011      * @property presenceMessage
31012      * @type String
31013      */
31014     presenceMessage: 'must be present',
31015     
31016     /**
31017      * The default error message used when a length validation fails
31018      * @property lengthMessage
31019      * @type String
31020      */
31021     lengthMessage: 'is the wrong length',
31022     
31023     /**
31024      * The default error message used when a format validation fails
31025      * @property formatMessage
31026      * @type Boolean
31027      */
31028     formatMessage: 'is the wrong format',
31029     
31030     /**
31031      * The default error message used when an inclusion validation fails
31032      * @property inclusionMessage
31033      * @type String
31034      */
31035     inclusionMessage: 'is not included in the list of acceptable values',
31036     
31037     /**
31038      * The default error message used when an exclusion validation fails
31039      * @property exclusionMessage
31040      * @type String
31041      */
31042     exclusionMessage: 'is not an acceptable value',
31043     
31044     /**
31045      * Validates that the given value is present
31046      * @param {Object} config Optional config object
31047      * @param {Mixed} value The value to validate
31048      * @return {Boolean} True if validation passed
31049      */
31050     presence: function(config, value) {
31051         if (value === undefined) {
31052             value = config;
31053         }
31054         
31055         return !!value;
31056     },
31057     
31058     /**
31059      * Returns true if the given value is between the configured min and max values
31060      * @param {Object} config Optional config object
31061      * @param {String} value The value to validate
31062      * @return {Boolean} True if the value passes validation
31063      */
31064     length: function(config, value) {
31065         if (value === undefined) {
31066             return false;
31067         }
31068         
31069         var length = value.length,
31070             min    = config.min,
31071             max    = config.max;
31072         
31073         if ((min && length < min) || (max && length > max)) {
31074             return false;
31075         } else {
31076             return true;
31077         }
31078     },
31079     
31080     /**
31081      * Returns true if the given value passes validation against the configured {@link #matcher} regex
31082      * @param {Object} config Optional config object
31083      * @param {String} value The value to validate
31084      * @return {Boolean} True if the value passes the format validation
31085      */
31086     format: function(config, value) {
31087         return !!(config.matcher && config.matcher.test(value));
31088     },
31089     
31090     /**
31091      * Validates that the given value is present in the configured {@link #list}
31092      * @param {String} value The value to validate
31093      * @return {Boolean} True if the value is present in the list
31094      */
31095     inclusion: function(config, value) {
31096         return config.list && Ext.Array.indexOf(config.list,value) != -1;
31097     },
31098     
31099     /**
31100      * Validates that the given value is present in the configured {@link #list}
31101      * @param {Object} config Optional config object
31102      * @param {String} value The value to validate
31103      * @return {Boolean} True if the value is not present in the list
31104      */
31105     exclusion: function(config, value) {
31106         return config.list && Ext.Array.indexOf(config.list,value) == -1;
31107     }
31108 });
31109 /**
31110  * @author Ed Spencer
31111  * @class Ext.data.ResultSet
31112  * @extends Object
31113  * 
31114  * <p>Simple wrapper class that represents a set of records returned by a Proxy.</p>
31115  * 
31116  * @constructor
31117  * Creates the new ResultSet
31118  */
31119 Ext.define('Ext.data.ResultSet', {
31120     /**
31121      * @cfg {Boolean} loaded
31122      * True if the records have already been loaded. This is only meaningful when dealing with
31123      * SQL-backed proxies
31124      */
31125     loaded: true,
31126     
31127     /**
31128      * @cfg {Number} count
31129      * The number of records in this ResultSet. Note that total may differ from this number
31130      */
31131     count: 0,
31132     
31133     /**
31134      * @cfg {Number} total
31135      * The total number of records reported by the data source. This ResultSet may form a subset of
31136      * those records (see count)
31137      */
31138     total: 0,
31139     
31140     /**
31141      * @cfg {Boolean} success
31142      * True if the ResultSet loaded successfully, false if any errors were encountered
31143      */
31144     success: false,
31145     
31146     /**
31147      * @cfg {Array} records The array of record instances. Required
31148      */
31149
31150     constructor: function(config) {
31151         Ext.apply(this, config);
31152         
31153         /**
31154          * DEPRECATED - will be removed in Ext JS 5.0. This is just a copy of this.total - use that instead
31155          * @property totalRecords
31156          * @type Mixed
31157          */
31158         this.totalRecords = this.total;
31159         
31160         if (config.count === undefined) {
31161             this.count = this.records.length;
31162         }
31163     }
31164 });
31165 /**
31166  * @author Ed Spencer
31167  * @class Ext.data.writer.Writer
31168  * @extends Object
31169  * 
31170  * <p>Base Writer class used by most subclasses of {@link Ext.data.proxy.Server}. This class is
31171  * responsible for taking a set of {@link Ext.data.Operation} objects and a {@link Ext.data.Request}
31172  * object and modifying that request based on the Operations.</p>
31173  * 
31174  * <p>For example a Ext.data.writer.Json would format the Operations and their {@link Ext.data.Model} 
31175  * instances based on the config options passed to the JsonWriter's constructor.</p>
31176  * 
31177  * <p>Writers are not needed for any kind of local storage - whether via a
31178  * {@link Ext.data.proxy.WebStorage Web Storage proxy} (see {@link Ext.data.proxy.LocalStorage localStorage}
31179  * and {@link Ext.data.proxy.SessionStorage sessionStorage}) or just in memory via a
31180  * {@link Ext.data.proxy.Memory MemoryProxy}.</p>
31181  * 
31182  * @constructor
31183  * @param {Object} config Optional config object
31184  */
31185 Ext.define('Ext.data.writer.Writer', {
31186     alias: 'writer.base',
31187     alternateClassName: ['Ext.data.DataWriter', 'Ext.data.Writer'],
31188     
31189     /**
31190      * @cfg {Boolean} writeAllFields True to write all fields from the record to the server. If set to false it
31191      * will only send the fields that were modified. Defaults to <tt>true</tt>. Note that any fields that have
31192      * {@link Ext.data.Field#persist} set to false will still be ignored.
31193      */
31194     writeAllFields: true,
31195     
31196     /**
31197      * @cfg {String} nameProperty This property is used to read the key for each value that will be sent to the server.
31198      * For example:
31199      * <pre><code>
31200 Ext.define('Person', {
31201     extend: 'Ext.data.Model',
31202     fields: [{
31203         name: 'first',
31204         mapping: 'firstName'
31205     }, {
31206         name: 'last',
31207         mapping: 'lastName'
31208     }, {
31209         name: 'age'
31210     }]
31211 });
31212 new Ext.data.writer.Writer({
31213     writeAllFields: true,
31214     nameProperty: 'mapping'
31215 });
31216
31217 // This will be sent to the server
31218 {
31219     firstName: 'first name value',
31220     lastName: 'last name value',
31221     age: 1
31222 }
31223
31224      * </code></pre>
31225      * Defaults to <tt>name</tt>. If the value is not present, the field name will always be used.
31226      */
31227     nameProperty: 'name',
31228
31229     constructor: function(config) {
31230         Ext.apply(this, config);
31231     },
31232
31233     /**
31234      * Prepares a Proxy's Ext.data.Request object
31235      * @param {Ext.data.Request} request The request object
31236      * @return {Ext.data.Request} The modified request object
31237      */
31238     write: function(request) {
31239         var operation = request.operation,
31240             records   = operation.records || [],
31241             len       = records.length,
31242             i         = 0,
31243             data      = [];
31244
31245         for (; i < len; i++) {
31246             data.push(this.getRecordData(records[i]));
31247         }
31248         return this.writeRecords(request, data);
31249     },
31250
31251     /**
31252      * Formats the data for each record before sending it to the server. This
31253      * method should be overridden to format the data in a way that differs from the default.
31254      * @param {Object} record The record that we are writing to the server.
31255      * @return {Object} An object literal of name/value keys to be written to the server.
31256      * By default this method returns the data property on the record.
31257      */
31258     getRecordData: function(record) {
31259         var isPhantom = record.phantom === true,
31260             writeAll = this.writeAllFields || isPhantom,
31261             nameProperty = this.nameProperty,
31262             fields = record.fields,
31263             data = {},
31264             changes,
31265             name,
31266             field,
31267             key;
31268         
31269         if (writeAll) {
31270             fields.each(function(field){
31271                 if (field.persist) {
31272                     name = field[nameProperty] || field.name;
31273                     data[name] = record.get(field.name);
31274                 }
31275             });
31276         } else {
31277             // Only write the changes
31278             changes = record.getChanges();
31279             for (key in changes) {
31280                 if (changes.hasOwnProperty(key)) {
31281                     field = fields.get(key);
31282                     name = field[nameProperty] || field.name;
31283                     data[name] = changes[key];
31284                 }
31285             }
31286             if (!isPhantom) {
31287                 // always include the id for non phantoms
31288                 data[record.idProperty] = record.getId();
31289             }
31290         }
31291         return data;
31292     }
31293 });
31294
31295 /**
31296  * @class Ext.util.Floating
31297  * A mixin to add floating capability to a Component
31298  */
31299 Ext.define('Ext.util.Floating', {
31300
31301     uses: ['Ext.Layer', 'Ext.window.Window'],
31302
31303     /**
31304      * @cfg {Boolean} focusOnToFront
31305      * Specifies whether the floated component should be automatically {@link #focus focused} when it is
31306      * {@link #toFront brought to the front}. Defaults to true.
31307      */
31308     focusOnToFront: true,
31309
31310     /**
31311      * @cfg {String/Boolean} shadow Specifies whether the floating component should be given a shadow. Set to
31312      * <tt>true</tt> to automatically create an {@link Ext.Shadow}, or a string indicating the
31313      * shadow's display {@link Ext.Shadow#mode}. Set to <tt>false</tt> to disable the shadow.
31314      * (Defaults to <tt>'sides'</tt>.)
31315      */
31316     shadow: 'sides',
31317
31318     constructor: function(config) {
31319         this.floating = true;
31320         this.el = Ext.create('Ext.Layer', Ext.apply({}, config, {
31321             hideMode: this.hideMode,
31322             hidden: this.hidden,
31323             shadow: Ext.isDefined(this.shadow) ? this.shadow : 'sides',
31324             shadowOffset: this.shadowOffset,
31325             constrain: false,
31326             shim: this.shim === false ? false : undefined
31327         }), this.el);
31328     },
31329
31330     onFloatRender: function() {
31331         var me = this;
31332         me.zIndexParent = me.getZIndexParent();
31333         me.setFloatParent(me.ownerCt);
31334         delete me.ownerCt;
31335
31336         if (me.zIndexParent) {
31337             me.zIndexParent.registerFloatingItem(me);
31338         } else {
31339             Ext.WindowManager.register(me);
31340         }
31341     },
31342
31343     setFloatParent: function(floatParent) {
31344         var me = this;
31345
31346         // Remove listeners from previous floatParent
31347         if (me.floatParent) {
31348             me.mun(me.floatParent, {
31349                 hide: me.onFloatParentHide,
31350                 show: me.onFloatParentShow,
31351                 scope: me
31352             });
31353         }
31354
31355         me.floatParent = floatParent;
31356
31357         // Floating Components as children of Containers must hide when their parent hides.
31358         if (floatParent) {
31359             me.mon(me.floatParent, {
31360                 hide: me.onFloatParentHide,
31361                 show: me.onFloatParentShow,
31362                 scope: me
31363             });
31364         }
31365
31366         // If a floating Component is configured to be constrained, but has no configured
31367         // constrainTo setting, set its constrainTo to be it's ownerCt before rendering.
31368         if ((me.constrain || me.constrainHeader) && !me.constrainTo) {
31369             me.constrainTo = floatParent ? floatParent.getTargetEl() : me.container;
31370         }
31371     },
31372
31373     onFloatParentHide: function() {
31374         this.showOnParentShow = this.isVisible();
31375         this.hide();
31376     },
31377
31378     onFloatParentShow: function() {
31379         if (this.showOnParentShow) {
31380             delete this.showOnParentShow;
31381             this.show();
31382         }
31383     },
31384
31385     /**
31386      * @private
31387      * <p>Finds the ancestor Container responsible for allocating zIndexes for the passed Component.</p>
31388      * <p>That will be the outermost floating Container (a Container which has no ownerCt and has floating:true).</p>
31389      * <p>If we have no ancestors, or we walk all the way up to the document body, there's no zIndexParent,
31390      * and the global Ext.WindowManager will be used.</p>
31391      */
31392     getZIndexParent: function() {
31393         var p = this.ownerCt,
31394             c;
31395
31396         if (p) {
31397             while (p) {
31398                 c = p;
31399                 p = p.ownerCt;
31400             }
31401             if (c.floating) {
31402                 return c;
31403             }
31404         }
31405     },
31406
31407     // private
31408     // z-index is managed by the zIndexManager and may be overwritten at any time.
31409     // Returns the next z-index to be used.
31410     // If this is a Container, then it will have rebased any managed floating Components,
31411     // and so the next available z-index will be approximately 10000 above that.
31412     setZIndex: function(index) {
31413         var me = this;
31414         this.el.setZIndex(index);
31415
31416         // Next item goes 10 above;
31417         index += 10;
31418
31419         // When a Container with floating items has its z-index set, it rebases any floating items it is managing.
31420         // The returned value is a round number approximately 10000 above the last z-index used.
31421         if (me.floatingItems) {
31422             index = Math.floor(me.floatingItems.setBase(index) / 100) * 100 + 10000;
31423         }
31424         return index;
31425     },
31426
31427     /**
31428      * <p>Moves this floating Component into a constrain region.</p>
31429      * <p>By default, this Component is constrained to be within the container it was added to, or the element
31430      * it was rendered to.</p>
31431      * <p>An alternative constraint may be passed.</p>
31432      * @param {Mixed} constrainTo Optional. The Element or {@link Ext.util.Region Region} into which this Component is to be constrained.
31433      */
31434     doConstrain: function(constrainTo) {
31435         var me = this,
31436             constrainEl,
31437             vector,
31438             xy;
31439
31440         if (me.constrain || me.constrainHeader) {
31441             if (me.constrainHeader) {
31442                 constrainEl = me.header.el;
31443             } else {
31444                 constrainEl = me.el;
31445             }
31446             vector = constrainEl.getConstrainVector(constrainTo || (me.floatParent && me.floatParent.getTargetEl()) || me.container);
31447             if (vector) {
31448                 xy = me.getPosition();
31449                 xy[0] += vector[0];
31450                 xy[1] += vector[1];
31451                 me.setPosition(xy);
31452             }
31453         }
31454     },
31455
31456     /**
31457      * Aligns this floating Component to the specified element
31458      * @param {Mixed} element The element or {@link Ext.Component} to align to. If passing a component, it must
31459      * be a omponent instance. If a string id is passed, it will be used as an element id.
31460      * @param {String} position (optional, defaults to "tl-bl?") The position to align to (see {@link Ext.core.Element#alignTo} for more details).
31461      * @param {Array} offsets (optional) Offset the positioning by [x, y]
31462      * @return {Component} this
31463      */
31464     alignTo: function(element, position, offsets) {
31465         if (element.isComponent) {
31466             element = element.getEl();
31467         }
31468         var xy = this.el.getAlignToXY(element, position, offsets);
31469         this.setPagePosition(xy);
31470         return this;
31471     },
31472
31473     /**
31474      * <p>Brings this floating Component to the front of any other visible, floating Components managed by the same {@link Ext.ZIndexManager ZIndexManager}</p>
31475      * <p>If this Component is modal, inserts the modal mask just below this Component in the z-index stack.</p>
31476      * @param {Boolean} preventFocus (optional) Specify <code>true</code> to prevent the Component from being focused.
31477      * @return {Component} this
31478      */
31479     toFront: function(preventFocus) {
31480         var me = this;
31481
31482         // Find the floating Component which provides the base for this Component's zIndexing.
31483         // That must move to front to then be able to rebase its zIndex stack and move this to the front
31484         if (me.zIndexParent) {
31485             me.zIndexParent.toFront(true);
31486         }
31487         if (me.zIndexManager.bringToFront(me)) {
31488             if (!Ext.isDefined(preventFocus)) {
31489                 preventFocus = !me.focusOnToFront;
31490             }
31491             if (!preventFocus) {
31492                 // Kick off a delayed focus request.
31493                 // If another floating Component is toFronted before the delay expires
31494                 // this will not receive focus.
31495                 me.focus(false, true);
31496             }
31497         }
31498         return me;
31499     },
31500
31501     /**
31502      * <p>This method is called internally by {@link Ext.ZIndexManager} to signal that a floating
31503      * Component has either been moved to the top of its zIndex stack, or pushed from the top of its zIndex stack.</p>
31504      * <p>If a <i>Window</i> is superceded by another Window, deactivating it hides its shadow.</p>
31505      * <p>This method also fires the {@link #activate} or {@link #deactivate} event depending on which action occurred.</p>
31506      * @param {Boolean} active True to activate the Component, false to deactivate it (defaults to false)
31507      * @param {Component} newActive The newly active Component which is taking over topmost zIndex position.
31508      */
31509     setActive: function(active, newActive) {
31510         if (active) {
31511             if ((this instanceof Ext.window.Window) && !this.maximized) {
31512                 this.el.enableShadow(true);
31513             }
31514             this.fireEvent('activate', this);
31515         } else {
31516             // Only the *Windows* in a zIndex stack share a shadow. All other types of floaters
31517             // can keep their shadows all the time
31518             if ((this instanceof Ext.window.Window) && (newActive instanceof Ext.window.Window)) {
31519                 this.el.disableShadow();
31520             }
31521             this.fireEvent('deactivate', this);
31522         }
31523     },
31524
31525     /**
31526      * Sends this Component to the back of (lower z-index than) any other visible windows
31527      * @return {Component} this
31528      */
31529     toBack: function() {
31530         this.zIndexManager.sendToBack(this);
31531         return this;
31532     },
31533
31534     /**
31535      * Center this Component in its container.
31536      * @return {Component} this
31537      */
31538     center: function() {
31539         var xy = this.el.getAlignToXY(this.container, 'c-c');
31540         this.setPagePosition(xy);
31541         return this;
31542     },
31543
31544     // private
31545     syncShadow : function(){
31546         if (this.floating) {
31547             this.el.sync(true);
31548         }
31549     },
31550
31551     // private
31552     fitContainer: function() {
31553         var parent = this.floatParent,
31554             container = parent ? parent.getTargetEl() : this.container,
31555             size = container.getViewSize(false);
31556
31557         this.setSize(size);
31558     }
31559 });
31560 /**
31561  * @class Ext.layout.container.AbstractContainer
31562  * @extends Ext.layout.Layout
31563  * Please refer to sub classes documentation
31564  */
31565
31566 Ext.define('Ext.layout.container.AbstractContainer', {
31567
31568     /* Begin Definitions */
31569
31570     extend: 'Ext.layout.Layout',
31571
31572     /* End Definitions */
31573
31574     type: 'container',
31575
31576     fixedLayout: true,
31577
31578     // @private
31579     managedHeight: true,
31580     // @private
31581     managedWidth: true,
31582
31583     /**
31584      * @cfg {Boolean} bindToOwnerCtComponent
31585      * Flag to notify the ownerCt Component on afterLayout of a change
31586      */
31587     bindToOwnerCtComponent: false,
31588
31589     /**
31590      * @cfg {Boolean} bindToOwnerCtContainer
31591      * Flag to notify the ownerCt Container on afterLayout of a change
31592      */
31593     bindToOwnerCtContainer: false,
31594
31595     /**
31596      * @cfg {String} itemCls
31597      * <p>An optional extra CSS class that will be added to the container. This can be useful for adding
31598      * customized styles to the container or any of its children using standard CSS rules. See
31599      * {@link Ext.Component}.{@link Ext.Component#ctCls ctCls} also.</p>
31600      * </p>
31601      */
31602
31603     isManaged: function(dimension) {
31604         dimension = Ext.String.capitalize(dimension);
31605         var me = this,
31606             child = me,
31607             managed = me['managed' + dimension],
31608             ancestor = me.owner.ownerCt;
31609
31610         if (ancestor && ancestor.layout) {
31611             while (ancestor && ancestor.layout) {
31612                 if (managed === false || ancestor.layout['managed' + dimension] === false) {
31613                     managed = false;
31614                     break;
31615                 }
31616                 ancestor = ancestor.ownerCt;
31617             }
31618         }
31619         return managed;
31620     },
31621
31622     layout: function() {
31623         var me = this,
31624             owner = me.owner;
31625         if (Ext.isNumber(owner.height) || owner.isViewport) {
31626             me.managedHeight = false;
31627         }
31628         if (Ext.isNumber(owner.width) || owner.isViewport) {
31629             me.managedWidth = false;
31630         }
31631         me.callParent(arguments);
31632     },
31633
31634     /**
31635     * Set the size of an item within the Container.  We should always use setCalculatedSize.
31636     * @private
31637     */
31638     setItemSize: function(item, width, height) {
31639         if (Ext.isObject(width)) {
31640             height = width.height;
31641             width = width.width;
31642         }
31643         item.setCalculatedSize(width, height, this.owner);
31644     },
31645
31646     /**
31647      * <p>Returns an array of child components either for a render phase (Performed in the beforeLayout method of the layout's
31648      * base class), or the layout phase (onLayout).</p>
31649      * @return {Array} of child components
31650      */
31651     getLayoutItems: function() {
31652         return this.owner && this.owner.items && this.owner.items.items || [];
31653     },
31654
31655     afterLayout: function() {
31656         this.owner.afterLayout(this);
31657     },
31658     /**
31659      * Returns the owner component's resize element.
31660      * @return {Ext.core.Element}
31661      */
31662      getTarget: function() {
31663          return this.owner.getTargetEl();
31664      },
31665     /**
31666      * <p>Returns the element into which rendering must take place. Defaults to the owner Container's {@link Ext.AbstractComponent#targetEl}.</p>
31667      * May be overridden in layout managers which implement an inner element.
31668      * @return {Ext.core.Element}
31669      */
31670      getRenderTarget: function() {
31671          return this.owner.getTargetEl();
31672      }
31673 });
31674
31675 /**
31676  * @class Ext.ZIndexManager
31677  * <p>A class that manages a group of {@link Ext.Component#floating} Components and provides z-order management,
31678  * and Component activation behavior, including masking below the active (topmost) Component.</p>
31679  * <p>{@link Ext.Component#floating Floating} Components which are rendered directly into the document (Such as {@link Ext.window.Window Window}s which are
31680  * {@link Ext.Component#show show}n are managed by a {@link Ext.WindowManager global instance}.</p>
31681  * <p>{@link Ext.Component#floating Floating} Components which are descendants of {@link Ext.Component#floating floating} <i>Containers</i>
31682  * (For example a {Ext.view.BoundList BoundList} within an {@link Ext.window.Window Window}, or a {@link Ext.menu.Menu Menu}),
31683  * are managed by a ZIndexManager owned by that floating Container. So ComboBox dropdowns within Windows will have managed z-indices
31684  * guaranteed to be correct, relative to the Window.</p>
31685  * @constructor
31686  */
31687 Ext.define('Ext.ZIndexManager', {
31688
31689     alternateClassName: 'Ext.WindowGroup',
31690
31691     statics: {
31692         zBase : 9000
31693     },
31694
31695     constructor: function(container) {
31696         var me = this;
31697
31698         me.list = {};
31699         me.zIndexStack = [];
31700         me.front = null;
31701
31702         if (container) {
31703
31704             // This is the ZIndexManager for an Ext.container.Container, base its zseed on the zIndex of the Container's element
31705             if (container.isContainer) {
31706                 container.on('resize', me._onContainerResize, me);
31707                 me.zseed = Ext.Number.from(container.getEl().getStyle('zIndex'), me.getNextZSeed());
31708                 // The containing element we will be dealing with (eg masking) is the content target
31709                 me.targetEl = container.getTargetEl();
31710                 me.container = container;
31711             }
31712             // This is the ZIndexManager for a DOM element
31713             else {
31714                 Ext.EventManager.onWindowResize(me._onContainerResize, me);
31715                 me.zseed = me.getNextZSeed();
31716                 me.targetEl = Ext.get(container);
31717             }
31718         }
31719         // No container passed means we are the global WindowManager. Our target is the doc body.
31720         // DOM must be ready to collect that ref.
31721         else {
31722             Ext.EventManager.onWindowResize(me._onContainerResize, me);
31723             me.zseed = me.getNextZSeed();
31724             Ext.onDocumentReady(function() {
31725                 me.targetEl = Ext.getBody();
31726             });
31727         }
31728     },
31729
31730     getNextZSeed: function() {
31731         return (Ext.ZIndexManager.zBase += 10000);
31732     },
31733
31734     setBase: function(baseZIndex) {
31735         this.zseed = baseZIndex;
31736         return this.assignZIndices();
31737     },
31738
31739     // private
31740     assignZIndices: function() {
31741         var a = this.zIndexStack,
31742             len = a.length,
31743             i = 0,
31744             zIndex = this.zseed,
31745             comp;
31746
31747         for (; i < len; i++) {
31748             comp = a[i];
31749             if (comp && !comp.hidden) {
31750
31751                 // Setting the zIndex of a Component returns the topmost zIndex consumed by
31752                 // that Component.
31753                 // If it's just a plain floating Component such as a BoundList, then the
31754                 // return value is the passed value plus 10, ready for the next item.
31755                 // If a floating *Container* has its zIndex set, it re-orders its managed
31756                 // floating children, starting from that new base, and returns a value 10000 above
31757                 // the highest zIndex which it allocates.
31758                 zIndex = comp.setZIndex(zIndex);
31759             }
31760         }
31761         this._activateLast();
31762         return zIndex;
31763     },
31764
31765     // private
31766     _setActiveChild: function(comp) {
31767         if (comp != this.front) {
31768
31769             if (this.front) {
31770                 this.front.setActive(false, comp);
31771             }
31772             this.front = comp;
31773             if (comp) {
31774                 comp.setActive(true);
31775                 if (comp.modal) {
31776                     this._showModalMask(comp.el.getStyle('zIndex') - 4);
31777                 }
31778             }
31779         }
31780     },
31781
31782     // private
31783     _activateLast: function(justHidden) {
31784         var comp,
31785             lastActivated = false,
31786             i;
31787
31788         // Go down through the z-index stack.
31789         // Activate the next visible one down.
31790         // Keep going down to find the next visible modal one to shift the modal mask down under
31791         for (i = this.zIndexStack.length-1; i >= 0; --i) {
31792             comp = this.zIndexStack[i];
31793             if (!comp.hidden) {
31794                 if (!lastActivated) {
31795                     this._setActiveChild(comp);
31796                     lastActivated = true;
31797                 }
31798
31799                 // Move any modal mask down to just under the next modal floater down the stack
31800                 if (comp.modal) {
31801                     this._showModalMask(comp.el.getStyle('zIndex') - 4);
31802                     return;
31803                 }
31804             }
31805         }
31806
31807         // none to activate, so there must be no modal mask.
31808         // And clear the currently active property
31809         this._hideModalMask();
31810         if (!lastActivated) {
31811             this._setActiveChild(null);
31812         }
31813     },
31814
31815     _showModalMask: function(zIndex) {
31816         if (!this.mask) {
31817             this.mask = this.targetEl.createChild({
31818                 cls: Ext.baseCSSPrefix + 'mask'
31819             });
31820             this.mask.setVisibilityMode(Ext.core.Element.DISPLAY);
31821             this.mask.on('click', this._onMaskClick, this);
31822         }
31823         Ext.getBody().addCls(Ext.baseCSSPrefix + 'body-masked');
31824         this.mask.setSize(this.targetEl.getViewSize(true));
31825         this.mask.setStyle('zIndex', zIndex);
31826         this.mask.show();
31827     },
31828
31829     _hideModalMask: function() {
31830         if (this.mask) {
31831             Ext.getBody().removeCls(Ext.baseCSSPrefix + 'body-masked');
31832             this.mask.hide();
31833         }
31834     },
31835
31836     _onMaskClick: function() {
31837         if (this.front) {
31838             this.front.focus();
31839         }
31840     },
31841
31842     _onContainerResize: function() {
31843         if (this.mask && this.mask.isVisible()) {
31844             this.mask.setSize(this.targetEl.getViewSize(true));
31845         }
31846     },
31847
31848     /**
31849      * <p>Registers a floating {@link Ext.Component} with this ZIndexManager. This should not
31850      * need to be called under normal circumstances. Floating Components (such as Windows, BoundLists and Menus) are automatically registered
31851      * with a {@link Ext.Component#zIndexManager zIndexManager} at render time.</p>
31852      * <p>Where this may be useful is moving Windows between two ZIndexManagers. For example,
31853      * to bring the Ext.MessageBox dialog under the same manager as the Desktop's
31854      * ZIndexManager in the desktop sample app:</p><code><pre>
31855 MyDesktop.getDesktop().getManager().register(Ext.MessageBox);
31856 </pre></code>
31857      * @param {Component} comp The Component to register.
31858      */
31859     register : function(comp) {
31860         if (comp.zIndexManager) {
31861             comp.zIndexManager.unregister(comp);
31862         }
31863         comp.zIndexManager = this;
31864
31865         this.list[comp.id] = comp;
31866         this.zIndexStack.push(comp);
31867         comp.on('hide', this._activateLast, this);
31868     },
31869
31870     /**
31871      * <p>Unregisters a {@link Ext.Component} from this ZIndexManager. This should not
31872      * need to be called. Components are automatically unregistered upon destruction.
31873      * See {@link #register}.</p>
31874      * @param {Component} comp The Component to unregister.
31875      */
31876     unregister : function(comp) {
31877         delete comp.zIndexManager;
31878         if (this.list && this.list[comp.id]) {
31879             delete this.list[comp.id];
31880             comp.un('hide', this._activateLast);
31881             Ext.Array.remove(this.zIndexStack, comp);
31882
31883             // Destruction requires that the topmost visible floater be activated. Same as hiding.
31884             this._activateLast(comp);
31885         }
31886     },
31887
31888     /**
31889      * Gets a registered Component by id.
31890      * @param {String/Object} id The id of the Component or a {@link Ext.Component} instance
31891      * @return {Ext.Component}
31892      */
31893     get : function(id) {
31894         return typeof id == "object" ? id : this.list[id];
31895     },
31896
31897    /**
31898      * Brings the specified Component to the front of any other active Components in this ZIndexManager.
31899      * @param {String/Object} comp The id of the Component or a {@link Ext.Component} instance
31900      * @return {Boolean} True if the dialog was brought to the front, else false
31901      * if it was already in front
31902      */
31903     bringToFront : function(comp) {
31904         comp = this.get(comp);
31905         if (comp != this.front) {
31906             Ext.Array.remove(this.zIndexStack, comp);
31907             this.zIndexStack.push(comp);
31908             this.assignZIndices();
31909             return true;
31910         }
31911         if (comp.modal) {
31912             Ext.getBody().addCls(Ext.baseCSSPrefix + 'body-masked');
31913             this.mask.setSize(Ext.core.Element.getViewWidth(true), Ext.core.Element.getViewHeight(true));
31914             this.mask.show();
31915         }
31916         return false;
31917     },
31918
31919     /**
31920      * Sends the specified Component to the back of other active Components in this ZIndexManager.
31921      * @param {String/Object} comp The id of the Component or a {@link Ext.Component} instance
31922      * @return {Ext.Component} The Component
31923      */
31924     sendToBack : function(comp) {
31925         comp = this.get(comp);
31926         Ext.Array.remove(this.zIndexStack, comp);
31927         this.zIndexStack.unshift(comp);
31928         this.assignZIndices();
31929         return comp;
31930     },
31931
31932     /**
31933      * Hides all Components managed by this ZIndexManager.
31934      */
31935     hideAll : function() {
31936         for (var id in this.list) {
31937             if (this.list[id].isComponent && this.list[id].isVisible()) {
31938                 this.list[id].hide();
31939             }
31940         }
31941     },
31942
31943     /**
31944      * @private
31945      * Temporarily hides all currently visible managed Components. This is for when
31946      * dragging a Window which may manage a set of floating descendants in its ZIndexManager;
31947      * they should all be hidden just for the duration of the drag.
31948      */
31949     hide: function() {
31950         var i = 0,
31951             ln = this.zIndexStack.length,
31952             comp;
31953
31954         this.tempHidden = [];
31955         for (; i < ln; i++) {
31956             comp = this.zIndexStack[i];
31957             if (comp.isVisible()) {
31958                 this.tempHidden.push(comp);
31959                 comp.hide();
31960             }
31961         }
31962     },
31963
31964     /**
31965      * @private
31966      * Restores temporarily hidden managed Components to visibility.
31967      */
31968     show: function() {
31969         var i = 0,
31970             ln = this.tempHidden.length,
31971             comp,
31972             x,
31973             y;
31974
31975         for (; i < ln; i++) {
31976             comp = this.tempHidden[i];
31977             x = comp.x;
31978             y = comp.y;
31979             comp.show();
31980             comp.setPosition(x, y);
31981         }
31982         delete this.tempHidden;
31983     },
31984
31985     /**
31986      * Gets the currently-active Component in this ZIndexManager.
31987      * @return {Ext.Component} The active Component
31988      */
31989     getActive : function() {
31990         return this.front;
31991     },
31992
31993     /**
31994      * Returns zero or more Components in this ZIndexManager using the custom search function passed to this method.
31995      * The function should accept a single {@link Ext.Component} reference as its only argument and should
31996      * return true if the Component matches the search criteria, otherwise it should return false.
31997      * @param {Function} fn The search function
31998      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Component being tested.
31999      * that gets passed to the function if not specified)
32000      * @return {Array} An array of zero or more matching windows
32001      */
32002     getBy : function(fn, scope) {
32003         var r = [],
32004             i = 0,
32005             len = this.zIndexStack.length,
32006             comp;
32007
32008         for (; i < len; i++) {
32009             comp = this.zIndexStack[i];
32010             if (fn.call(scope||comp, comp) !== false) {
32011                 r.push(comp);
32012             }
32013         }
32014         return r;
32015     },
32016
32017     /**
32018      * Executes the specified function once for every Component in this ZIndexManager, passing each
32019      * Component as the only parameter. Returning false from the function will stop the iteration.
32020      * @param {Function} fn The function to execute for each item
32021      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current Component in the iteration.
32022      */
32023     each : function(fn, scope) {
32024         var comp;
32025         for (var id in this.list) {
32026             comp = this.list[id];
32027             if (comp.isComponent && fn.call(scope || comp, comp) === false) {
32028                 return;
32029             }
32030         }
32031     },
32032
32033     /**
32034      * Executes the specified function once for every Component in this ZIndexManager, passing each
32035      * Component as the only parameter. Returning false from the function will stop the iteration.
32036      * The components are passed to the function starting at the bottom and proceeding to the top.
32037      * @param {Function} fn The function to execute for each item
32038      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function
32039      * is executed. Defaults to the current Component in the iteration.
32040      */
32041     eachBottomUp: function (fn, scope) {
32042         var comp,
32043             stack = this.zIndexStack,
32044             i, n;
32045
32046         for (i = 0, n = stack.length ; i < n; i++) {
32047             comp = stack[i];
32048             if (comp.isComponent && fn.call(scope || comp, comp) === false) {
32049                 return;
32050             }
32051         }
32052     },
32053
32054     /**
32055      * Executes the specified function once for every Component in this ZIndexManager, passing each
32056      * Component as the only parameter. Returning false from the function will stop the iteration.
32057      * The components are passed to the function starting at the top and proceeding to the bottom.
32058      * @param {Function} fn The function to execute for each item
32059      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function
32060      * is executed. Defaults to the current Component in the iteration.
32061      */
32062     eachTopDown: function (fn, scope) {
32063         var comp,
32064             stack = this.zIndexStack,
32065             i;
32066
32067         for (i = stack.length ; i-- > 0; ) {
32068             comp = stack[i];
32069             if (comp.isComponent && fn.call(scope || comp, comp) === false) {
32070                 return;
32071             }
32072         }
32073     },
32074
32075     destroy: function() {
32076         delete this.zIndexStack;
32077         delete this.list;
32078         delete this.container;
32079         delete this.targetEl;
32080     }
32081 }, function() {
32082     /**
32083      * @class Ext.WindowManager
32084      * @extends Ext.ZIndexManager
32085      * <p>The default global floating Component group that is available automatically.</p>
32086      * <p>This manages instances of floating Components which were rendered programatically without
32087      * being added to a {@link Ext.container.Container Container}, and for floating Components which were added into non-floating Containers.</p>
32088      * <p><i>Floating</i> Containers create their own instance of ZIndexManager, and floating Components added at any depth below
32089      * there are managed by that ZIndexManager.</p>
32090      * @singleton
32091      */
32092     Ext.WindowManager = Ext.WindowMgr = new this();
32093 });
32094
32095 /**
32096  * @class Ext.layout.container.boxOverflow.None
32097  * @extends Object
32098  * @private
32099  * Base class for Box Layout overflow handlers. These specialized classes are invoked when a Box Layout
32100  * (either an HBox or a VBox) has child items that are either too wide (for HBox) or too tall (for VBox)
32101  * for its container.
32102  */
32103 Ext.define('Ext.layout.container.boxOverflow.None', {
32104     
32105     alternateClassName: 'Ext.layout.boxOverflow.None',
32106     
32107     constructor: function(layout, config) {
32108         this.layout = layout;
32109         Ext.apply(this, config || {});
32110     },
32111
32112     handleOverflow: Ext.emptyFn,
32113
32114     clearOverflow: Ext.emptyFn,
32115
32116     /**
32117      * @private
32118      * Normalizes an item reference, string id or numerical index into a reference to the item
32119      * @param {Ext.Component|String|Number} item The item reference, id or index
32120      * @return {Ext.Component} The item
32121      */
32122     getItem: function(item) {
32123         return this.layout.owner.getComponent(item);
32124     }
32125 });
32126 /**
32127  * @class Ext.util.KeyMap
32128  * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
32129  * The constructor accepts the same config object as defined by {@link #addBinding}.
32130  * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
32131  * combination it will call the function with this signature (if the match is a multi-key
32132  * combination the callback will still be called only once): (String key, Ext.EventObject e)
32133  * A KeyMap can also handle a string representation of keys.<br />
32134  * Usage:
32135  <pre><code>
32136 // map one key by key code
32137 var map = new Ext.util.KeyMap("my-element", {
32138     key: 13, // or Ext.EventObject.ENTER
32139     fn: myHandler,
32140     scope: myObject
32141 });
32142
32143 // map multiple keys to one action by string
32144 var map = new Ext.util.KeyMap("my-element", {
32145     key: "a\r\n\t",
32146     fn: myHandler,
32147     scope: myObject
32148 });
32149
32150 // map multiple keys to multiple actions by strings and array of codes
32151 var map = new Ext.util.KeyMap("my-element", [
32152     {
32153         key: [10,13],
32154         fn: function(){ alert("Return was pressed"); }
32155     }, {
32156         key: "abc",
32157         fn: function(){ alert('a, b or c was pressed'); }
32158     }, {
32159         key: "\t",
32160         ctrl:true,
32161         shift:true,
32162         fn: function(){ alert('Control + shift + tab was pressed.'); }
32163     }
32164 ]);
32165 </code></pre>
32166  * <b>Note: A KeyMap starts enabled</b>
32167  * @constructor
32168  * @param {Mixed} el The element to bind to
32169  * @param {Object} binding The binding (see {@link #addBinding})
32170  * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
32171  */
32172 Ext.define('Ext.util.KeyMap', {
32173     alternateClassName: 'Ext.KeyMap',
32174     
32175     constructor: function(el, binding, eventName){
32176         var me = this;
32177         
32178         Ext.apply(me, {
32179             el: Ext.get(el),
32180             eventName: eventName || me.eventName,
32181             bindings: []
32182         });
32183         if (binding) {
32184             me.addBinding(binding);
32185         }
32186         me.enable();
32187     },
32188     
32189     eventName: 'keydown',
32190
32191     /**
32192      * Add a new binding to this KeyMap. The following config object properties are supported:
32193      * <pre>
32194 Property            Type             Description
32195 ----------          ---------------  ----------------------------------------------------------------------
32196 key                 String/Array     A single keycode or an array of keycodes to handle
32197 shift               Boolean          True to handle key only when shift is pressed, False to handle the key only when shift is not pressed (defaults to undefined)
32198 ctrl                Boolean          True to handle key only when ctrl is pressed, False to handle the key only when ctrl is not pressed (defaults to undefined)
32199 alt                 Boolean          True to handle key only when alt is pressed, False to handle the key only when alt is not pressed (defaults to undefined)
32200 handler             Function         The function to call when KeyMap finds the expected key combination
32201 fn                  Function         Alias of handler (for backwards-compatibility)
32202 scope               Object           The scope of the callback function
32203 defaultEventAction  String           A default action to apply to the event. Possible values are: stopEvent, stopPropagation, preventDefault. If no value is set no action is performed. 
32204 </pre>
32205      *
32206      * Usage:
32207      * <pre><code>
32208 // Create a KeyMap
32209 var map = new Ext.util.KeyMap(document, {
32210     key: Ext.EventObject.ENTER,
32211     fn: handleKey,
32212     scope: this
32213 });
32214
32215 //Add a new binding to the existing KeyMap later
32216 map.addBinding({
32217     key: 'abc',
32218     shift: true,
32219     fn: handleKey,
32220     scope: this
32221 });
32222 </code></pre>
32223      * @param {Object/Array} binding A single KeyMap config or an array of configs
32224      */
32225     addBinding : function(binding){
32226         if (Ext.isArray(binding)) {
32227             Ext.each(binding, this.addBinding, this);
32228             return;
32229         }
32230         
32231         var keyCode = binding.key,
32232             processed = false,
32233             key,
32234             keys,
32235             keyString,
32236             i,
32237             len;
32238
32239         if (Ext.isString(keyCode)) {
32240             keys = [];
32241             keyString = keyCode.toLowerCase();
32242             
32243             for (i = 0, len = keyString.length; i < len; ++i){
32244                 keys.push(keyString.charCodeAt(i));
32245             }
32246             keyCode = keys;
32247             processed = true;
32248         }
32249         
32250         if (!Ext.isArray(keyCode)) {
32251             keyCode = [keyCode];
32252         }
32253         
32254         if (!processed) {
32255             for (i = 0, len = keyCode.length; i < len; ++i) {
32256                 key = keyCode[i];
32257                 if (Ext.isString(key)) {
32258                     keyCode[i] = key.toLowerCase().charCodeAt(0);
32259                 }
32260             }
32261         }
32262         
32263         this.bindings.push(Ext.apply({
32264             keyCode: keyCode
32265         }, binding));
32266     },
32267     
32268     /**
32269      * Process any keydown events on the element
32270      * @private
32271      * @param {Ext.EventObject} event
32272      */
32273     handleKeyDown: function(event) {
32274         if (this.enabled) { //just in case
32275             var bindings = this.bindings,
32276                 i = 0,
32277                 len = bindings.length;
32278                 
32279             event = this.processEvent(event);
32280             for(; i < len; ++i){
32281                 this.processBinding(bindings[i], event);
32282             }
32283         }
32284     },
32285     
32286     /**
32287      * Ugly hack to allow this class to be tested. Currently WebKit gives
32288      * no way to raise a key event properly with both
32289      * a) A keycode
32290      * b) The alt/ctrl/shift modifiers
32291      * So we have to simulate them here. Yuk! 
32292      * This is a stub method intended to be overridden by tests.
32293      * More info: https://bugs.webkit.org/show_bug.cgi?id=16735
32294      * @private
32295      */
32296     processEvent: function(event){
32297         return event;
32298     },
32299     
32300     /**
32301      * Process a particular binding and fire the handler if necessary.
32302      * @private
32303      * @param {Object} binding The binding information
32304      * @param {Ext.EventObject} event
32305      */
32306     processBinding: function(binding, event){
32307         if (this.checkModifiers(binding, event)) {
32308             var key = event.getKey(),
32309                 handler = binding.fn || binding.handler,
32310                 scope = binding.scope || this,
32311                 keyCode = binding.keyCode,
32312                 defaultEventAction = binding.defaultEventAction,
32313                 i,
32314                 len,
32315                 keydownEvent = new Ext.EventObjectImpl(event);
32316                 
32317             
32318             for (i = 0, len = keyCode.length; i < len; ++i) {
32319                 if (key === keyCode[i]) {
32320                     if (handler.call(scope, key, event) !== true && defaultEventAction) {
32321                         keydownEvent[defaultEventAction]();
32322                     }
32323                     break;
32324                 }
32325             }
32326         }
32327     },
32328     
32329     /**
32330      * Check if the modifiers on the event match those on the binding
32331      * @private
32332      * @param {Object} binding
32333      * @param {Ext.EventObject} event
32334      * @return {Boolean} True if the event matches the binding
32335      */
32336     checkModifiers: function(binding, e){
32337         var keys = ['shift', 'ctrl', 'alt'],
32338             i = 0,
32339             len = keys.length,
32340             val, key;
32341             
32342         for (; i < len; ++i){
32343             key = keys[i];
32344             val = binding[key];
32345             if (!(val === undefined || (val === e[key + 'Key']))) {
32346                 return false;
32347             }
32348         }
32349         return true;
32350     },
32351
32352     /**
32353      * Shorthand for adding a single key listener
32354      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
32355      * following options:
32356      * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
32357      * @param {Function} fn The function to call
32358      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.
32359      */
32360     on: function(key, fn, scope) {
32361         var keyCode, shift, ctrl, alt;
32362         if (Ext.isObject(key) && !Ext.isArray(key)) {
32363             keyCode = key.key;
32364             shift = key.shift;
32365             ctrl = key.ctrl;
32366             alt = key.alt;
32367         } else {
32368             keyCode = key;
32369         }
32370         this.addBinding({
32371             key: keyCode,
32372             shift: shift,
32373             ctrl: ctrl,
32374             alt: alt,
32375             fn: fn,
32376             scope: scope
32377         });
32378     },
32379
32380     /**
32381      * Returns true if this KeyMap is enabled
32382      * @return {Boolean}
32383      */
32384     isEnabled : function(){
32385         return this.enabled;
32386     },
32387
32388     /**
32389      * Enables this KeyMap
32390      */
32391     enable: function(){
32392         if(!this.enabled){
32393             this.el.on(this.eventName, this.handleKeyDown, this);
32394             this.enabled = true;
32395         }
32396     },
32397
32398     /**
32399      * Disable this KeyMap
32400      */
32401     disable: function(){
32402         if(this.enabled){
32403             this.el.removeListener(this.eventName, this.handleKeyDown, this);
32404             this.enabled = false;
32405         }
32406     },
32407
32408     /**
32409      * Convenience function for setting disabled/enabled by boolean.
32410      * @param {Boolean} disabled
32411      */
32412     setDisabled : function(disabled){
32413         if (disabled) {
32414             this.disable();
32415         } else {
32416             this.enable();
32417         }
32418     },
32419     
32420     /**
32421      * Destroys the KeyMap instance and removes all handlers.
32422      * @param {Boolean} removeEl True to also remove the attached element
32423      */
32424     destroy: function(removeEl){
32425         var me = this;
32426         
32427         me.bindings = [];
32428         me.disable();
32429         if (removeEl === true) {
32430             me.el.remove();
32431         }
32432         delete me.el;
32433     }
32434 });
32435 /**
32436  * @class Ext.util.ClickRepeater
32437  * @extends Ext.util.Observable
32438  *
32439  * A wrapper class which can be applied to any element. Fires a "click" event while the
32440  * mouse is pressed. The interval between firings may be specified in the config but
32441  * defaults to 20 milliseconds.
32442  *
32443  * Optionally, a CSS class may be applied to the element during the time it is pressed.
32444  *
32445  * @constructor
32446  * @param {Mixed} el The element to listen on
32447  * @param {Object} config
32448  */
32449
32450 Ext.define('Ext.util.ClickRepeater', {
32451     extend: 'Ext.util.Observable',
32452
32453     constructor : function(el, config){
32454         this.el = Ext.get(el);
32455         this.el.unselectable();
32456
32457         Ext.apply(this, config);
32458
32459         this.addEvents(
32460         /**
32461          * @event mousedown
32462          * Fires when the mouse button is depressed.
32463          * @param {Ext.util.ClickRepeater} this
32464          * @param {Ext.EventObject} e
32465          */
32466         "mousedown",
32467         /**
32468          * @event click
32469          * Fires on a specified interval during the time the element is pressed.
32470          * @param {Ext.util.ClickRepeater} this
32471          * @param {Ext.EventObject} e
32472          */
32473         "click",
32474         /**
32475          * @event mouseup
32476          * Fires when the mouse key is released.
32477          * @param {Ext.util.ClickRepeater} this
32478          * @param {Ext.EventObject} e
32479          */
32480         "mouseup"
32481         );
32482
32483         if(!this.disabled){
32484             this.disabled = true;
32485             this.enable();
32486         }
32487
32488         // allow inline handler
32489         if(this.handler){
32490             this.on("click", this.handler,  this.scope || this);
32491         }
32492
32493         this.callParent();
32494     },
32495
32496     /**
32497      * @cfg {Mixed} el The element to act as a button.
32498      */
32499
32500     /**
32501      * @cfg {String} pressedCls A CSS class name to be applied to the element while pressed.
32502      */
32503
32504     /**
32505      * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
32506      * "interval" and "delay" are ignored.
32507      */
32508
32509     /**
32510      * @cfg {Number} interval The interval between firings of the "click" event. Default 20 ms.
32511      */
32512     interval : 20,
32513
32514     /**
32515      * @cfg {Number} delay The initial delay before the repeating event begins firing.
32516      * Similar to an autorepeat key delay.
32517      */
32518     delay: 250,
32519
32520     /**
32521      * @cfg {Boolean} preventDefault True to prevent the default click event
32522      */
32523     preventDefault : true,
32524     /**
32525      * @cfg {Boolean} stopDefault True to stop the default click event
32526      */
32527     stopDefault : false,
32528
32529     timer : 0,
32530
32531     /**
32532      * Enables the repeater and allows events to fire.
32533      */
32534     enable: function(){
32535         if(this.disabled){
32536             this.el.on('mousedown', this.handleMouseDown, this);
32537             if (Ext.isIE){
32538                 this.el.on('dblclick', this.handleDblClick, this);
32539             }
32540             if(this.preventDefault || this.stopDefault){
32541                 this.el.on('click', this.eventOptions, this);
32542             }
32543         }
32544         this.disabled = false;
32545     },
32546
32547     /**
32548      * Disables the repeater and stops events from firing.
32549      */
32550     disable: function(/* private */ force){
32551         if(force || !this.disabled){
32552             clearTimeout(this.timer);
32553             if(this.pressedCls){
32554                 this.el.removeCls(this.pressedCls);
32555             }
32556             Ext.getDoc().un('mouseup', this.handleMouseUp, this);
32557             this.el.removeAllListeners();
32558         }
32559         this.disabled = true;
32560     },
32561
32562     /**
32563      * Convenience function for setting disabled/enabled by boolean.
32564      * @param {Boolean} disabled
32565      */
32566     setDisabled: function(disabled){
32567         this[disabled ? 'disable' : 'enable']();
32568     },
32569
32570     eventOptions: function(e){
32571         if(this.preventDefault){
32572             e.preventDefault();
32573         }
32574         if(this.stopDefault){
32575             e.stopEvent();
32576         }
32577     },
32578
32579     // private
32580     destroy : function() {
32581         this.disable(true);
32582         Ext.destroy(this.el);
32583         this.clearListeners();
32584     },
32585
32586     handleDblClick : function(e){
32587         clearTimeout(this.timer);
32588         this.el.blur();
32589
32590         this.fireEvent("mousedown", this, e);
32591         this.fireEvent("click", this, e);
32592     },
32593
32594     // private
32595     handleMouseDown : function(e){
32596         clearTimeout(this.timer);
32597         this.el.blur();
32598         if(this.pressedCls){
32599             this.el.addCls(this.pressedCls);
32600         }
32601         this.mousedownTime = new Date();
32602
32603         Ext.getDoc().on("mouseup", this.handleMouseUp, this);
32604         this.el.on("mouseout", this.handleMouseOut, this);
32605
32606         this.fireEvent("mousedown", this, e);
32607         this.fireEvent("click", this, e);
32608
32609         // Do not honor delay or interval if acceleration wanted.
32610         if (this.accelerate) {
32611             this.delay = 400;
32612         }
32613
32614         // Re-wrap the event object in a non-shared object, so it doesn't lose its context if
32615         // the global shared EventObject gets a new Event put into it before the timer fires.
32616         e = new Ext.EventObjectImpl(e);
32617
32618         this.timer =  Ext.defer(this.click, this.delay || this.interval, this, [e]);
32619     },
32620
32621     // private
32622     click : function(e){
32623         this.fireEvent("click", this, e);
32624         this.timer =  Ext.defer(this.click, this.accelerate ?
32625             this.easeOutExpo(Ext.Date.getElapsed(this.mousedownTime),
32626                 400,
32627                 -390,
32628                 12000) :
32629             this.interval, this, [e]);
32630     },
32631
32632     easeOutExpo : function (t, b, c, d) {
32633         return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
32634     },
32635
32636     // private
32637     handleMouseOut : function(){
32638         clearTimeout(this.timer);
32639         if(this.pressedCls){
32640             this.el.removeCls(this.pressedCls);
32641         }
32642         this.el.on("mouseover", this.handleMouseReturn, this);
32643     },
32644
32645     // private
32646     handleMouseReturn : function(){
32647         this.el.un("mouseover", this.handleMouseReturn, this);
32648         if(this.pressedCls){
32649             this.el.addCls(this.pressedCls);
32650         }
32651         this.click();
32652     },
32653
32654     // private
32655     handleMouseUp : function(e){
32656         clearTimeout(this.timer);
32657         this.el.un("mouseover", this.handleMouseReturn, this);
32658         this.el.un("mouseout", this.handleMouseOut, this);
32659         Ext.getDoc().un("mouseup", this.handleMouseUp, this);
32660         if(this.pressedCls){
32661             this.el.removeCls(this.pressedCls);
32662         }
32663         this.fireEvent("mouseup", this, e);
32664     }
32665 });
32666
32667 /**
32668  * Component layout for buttons
32669  * @class Ext.layout.component.Button
32670  * @extends Ext.layout.component.Component
32671  * @private
32672  */
32673 Ext.define('Ext.layout.component.Button', {
32674
32675     /* Begin Definitions */
32676
32677     alias: ['layout.button'],
32678
32679     extend: 'Ext.layout.component.Component',
32680
32681     /* End Definitions */
32682
32683     type: 'button',
32684
32685     cellClsRE: /-btn-(tl|br)\b/,
32686     htmlRE: /<.*>/,
32687
32688     beforeLayout: function() {
32689         return this.callParent(arguments) || this.lastText !== this.owner.text;
32690     },
32691
32692     /**
32693      * Set the dimensions of the inner &lt;button&gt; element to match the
32694      * component dimensions.
32695      */
32696     onLayout: function(width, height) {
32697         var me = this,
32698             isNum = Ext.isNumber,
32699             owner = me.owner,
32700             ownerEl = owner.el,
32701             btnEl = owner.btnEl,
32702             btnInnerEl = owner.btnInnerEl,
32703             minWidth = owner.minWidth,
32704             maxWidth = owner.maxWidth,
32705             ownerWidth, btnFrameWidth, metrics;
32706
32707         me.getTargetInfo();
32708         me.callParent(arguments);
32709
32710         btnInnerEl.unclip();
32711         me.setTargetSize(width, height);
32712
32713         if (!isNum(width)) {
32714             // In IE7 strict mode button elements with width:auto get strange extra side margins within
32715             // the wrapping table cell, but they go away if the width is explicitly set. So we measure
32716             // the size of the text and set the width to match.
32717             if (owner.text && Ext.isIE7 && Ext.isStrict && btnEl && btnEl.getWidth() > 20) {
32718                 btnFrameWidth = me.btnFrameWidth;
32719                 metrics = Ext.util.TextMetrics.measure(btnInnerEl, owner.text);
32720                 ownerEl.setWidth(metrics.width + btnFrameWidth + me.adjWidth);
32721                 btnEl.setWidth(metrics.width + btnFrameWidth);
32722                 btnInnerEl.setWidth(metrics.width + btnFrameWidth);
32723             } else {
32724                 // Remove any previous fixed widths
32725                 ownerEl.setWidth(null);
32726                 btnEl.setWidth(null);
32727                 btnInnerEl.setWidth(null);
32728             }
32729
32730             // Handle maxWidth/minWidth config
32731             if (minWidth || maxWidth) {
32732                 ownerWidth = ownerEl.getWidth();
32733                 if (minWidth && (ownerWidth < minWidth)) {
32734                     me.setTargetSize(minWidth, height);
32735                 }
32736                 else if (maxWidth && (ownerWidth > maxWidth)) {
32737                     btnInnerEl.clip();
32738                     me.setTargetSize(maxWidth, height);
32739                 }
32740             }
32741         }
32742
32743         this.lastText = owner.text;
32744     },
32745
32746     setTargetSize: function(width, height) {
32747         var me = this,
32748             owner = me.owner,
32749             isNum = Ext.isNumber,
32750             btnInnerEl = owner.btnInnerEl,
32751             btnWidth = (isNum(width) ? width - me.adjWidth : width),
32752             btnHeight = (isNum(height) ? height - me.adjHeight : height),
32753             btnFrameHeight = me.btnFrameHeight,
32754             text = owner.getText(),
32755             textHeight;
32756
32757         me.callParent(arguments);
32758         me.setElementSize(owner.btnEl, btnWidth, btnHeight);
32759         me.setElementSize(btnInnerEl, btnWidth, btnHeight);
32760         if (isNum(btnHeight)) {
32761             btnInnerEl.setStyle('line-height', btnHeight - btnFrameHeight + 'px');
32762         }
32763
32764         // Button text may contain markup that would force it to wrap to more than one line (e.g. 'Button<br>Label').
32765         // When this happens, we cannot use the line-height set above for vertical centering; we instead reset the
32766         // line-height to normal, measure the rendered text height, and add padding-top to center the text block
32767         // vertically within the button's height. This is more expensive than the basic line-height approach so
32768         // we only do it if the text contains markup.
32769         if (text && this.htmlRE.test(text)) {
32770             btnInnerEl.setStyle('line-height', 'normal');
32771             textHeight = Ext.util.TextMetrics.measure(btnInnerEl, text).height;
32772             btnInnerEl.setStyle('padding-top', me.btnFrameTop + Math.max(btnInnerEl.getHeight() - btnFrameHeight - textHeight, 0) / 2 + 'px');
32773             me.setElementSize(btnInnerEl, btnWidth, btnHeight);
32774         }
32775     },
32776
32777     getTargetInfo: function() {
32778         var me = this,
32779             owner = me.owner,
32780             ownerEl = owner.el,
32781             frameSize = me.frameSize,
32782             frameBody = owner.frameBody,
32783             btnWrap = owner.btnWrap,
32784             innerEl = owner.btnInnerEl;
32785
32786         if (!('adjWidth' in me)) {
32787             Ext.apply(me, {
32788                 // Width adjustment must take into account the arrow area. The btnWrap is the <em> which has padding to accommodate the arrow.
32789                 adjWidth: frameSize.left + frameSize.right + ownerEl.getBorderWidth('lr') + ownerEl.getPadding('lr') +
32790                           btnWrap.getPadding('lr') + (frameBody ? frameBody.getFrameWidth('lr') : 0),
32791                 adjHeight: frameSize.top + frameSize.bottom + ownerEl.getBorderWidth('tb') + ownerEl.getPadding('tb') +
32792                            btnWrap.getPadding('tb') + (frameBody ? frameBody.getFrameWidth('tb') : 0),
32793                 btnFrameWidth: innerEl.getFrameWidth('lr'),
32794                 btnFrameHeight: innerEl.getFrameWidth('tb'),
32795                 btnFrameTop: innerEl.getFrameWidth('t')
32796             });
32797         }
32798
32799         return me.callParent();
32800     }
32801 });
32802 /**
32803  * @class Ext.util.TextMetrics
32804  * <p>
32805  * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
32806  * wide, in pixels, a given block of text will be. Note that when measuring text, it should be plain text and
32807  * should not contain any HTML, otherwise it may not be measured correctly.</p> 
32808  * <p>The measurement works by copying the relevant CSS styles that can affect the font related display, 
32809  * then checking the size of an element that is auto-sized. Note that if the text is multi-lined, you must 
32810  * provide a <b>fixed width</b> when doing the measurement.</p>
32811  * 
32812  * <p>
32813  * If multiple measurements are being done on the same element, you create a new instance to initialize 
32814  * to avoid the overhead of copying the styles to the element repeatedly.
32815  * </p>
32816  */
32817 Ext.define('Ext.util.TextMetrics', {
32818     statics: {
32819         shared: null,
32820         /**
32821          * Measures the size of the specified text
32822          * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
32823          * that can affect the size of the rendered text
32824          * @param {String} text The text to measure
32825          * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
32826          * in order to accurately measure the text height
32827          * @return {Object} An object containing the text's size {width: (width), height: (height)}
32828          */
32829         measure: function(el, text, fixedWidth){
32830             var me = this,
32831                 shared = me.shared;
32832             
32833             if(!shared){
32834                 shared = me.shared = new me(el, fixedWidth);
32835             }
32836             shared.bind(el);
32837             shared.setFixedWidth(fixedWidth || 'auto');
32838             return shared.getSize(text);
32839         },
32840         
32841         /**
32842           * Destroy the TextMetrics instance created by {@link #measure}.
32843           */
32844          destroy: function(){
32845              var me = this;
32846              Ext.destroy(me.shared);
32847              me.shared = null;
32848          }
32849     },
32850     
32851     /**
32852      * @constructor
32853      * @param {Mixed} bindTo The element to bind to.
32854      * @param {Number} fixedWidth A fixed width to apply to the measuring element.
32855      */
32856     constructor: function(bindTo, fixedWidth){
32857         var measure = this.measure = Ext.getBody().createChild({
32858             cls: 'x-textmetrics'
32859         });
32860         this.el = Ext.get(bindTo);
32861         
32862         measure.position('absolute');
32863         measure.setLeftTop(-1000, -1000);
32864         measure.hide();
32865
32866         if (fixedWidth) {
32867            measure.setWidth(fixedWidth);
32868         }
32869     },
32870     
32871     /**
32872      * <p><b>Only available on the instance returned from {@link #createInstance}, <u>not</u> on the singleton.</b></p>
32873      * Returns the size of the specified text based on the internal element's style and width properties
32874      * @param {String} text The text to measure
32875      * @return {Object} An object containing the text's size {width: (width), height: (height)}
32876      */
32877     getSize: function(text){
32878         var measure = this.measure,
32879             size;
32880         
32881         measure.update(text);
32882         size = measure.getSize();
32883         measure.update('');
32884         return size;
32885     },
32886     
32887     /**
32888      * Binds this TextMetrics instance to a new element
32889      * @param {Mixed} el The element
32890      */
32891     bind: function(el){
32892         var me = this;
32893         
32894         me.el = Ext.get(el);
32895         me.measure.setStyle(
32896             me.el.getStyles('font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing')
32897         );
32898     },
32899     
32900     /**
32901      * Sets a fixed width on the internal measurement element.  If the text will be multiline, you have
32902      * to set a fixed width in order to accurately measure the text height.
32903      * @param {Number} width The width to set on the element
32904      */
32905      setFixedWidth : function(width){
32906          this.measure.setWidth(width);
32907      },
32908      
32909      /**
32910       * Returns the measured width of the specified text
32911       * @param {String} text The text to measure
32912       * @return {Number} width The width in pixels
32913       */
32914      getWidth : function(text){
32915          this.measure.dom.style.width = 'auto';
32916          return this.getSize(text).width;
32917      },
32918      
32919      /**
32920       * Returns the measured height of the specified text
32921       * @param {String} text The text to measure
32922       * @return {Number} height The height in pixels
32923       */
32924      getHeight : function(text){
32925          return this.getSize(text).height;
32926      },
32927      
32928      /**
32929       * Destroy this instance
32930       */
32931      destroy: function(){
32932          var me = this;
32933          me.measure.remove();
32934          delete me.el;
32935          delete me.measure;
32936      }
32937 }, function(){
32938     Ext.core.Element.addMethods({
32939         /**
32940          * Returns the width in pixels of the passed text, or the width of the text in this Element.
32941          * @param {String} text The text to measure. Defaults to the innerHTML of the element.
32942          * @param {Number} min (Optional) The minumum value to return.
32943          * @param {Number} max (Optional) The maximum value to return.
32944          * @return {Number} The text width in pixels.
32945          * @member Ext.core.Element getTextWidth
32946          */
32947         getTextWidth : function(text, min, max){
32948             return Ext.Number.constrain(Ext.util.TextMetrics.measure(this.dom, Ext.value(text, this.dom.innerHTML, true)).width, min || 0, max || 1000000);
32949         }
32950     });
32951 });
32952
32953 /**
32954  * @class Ext.layout.container.boxOverflow.Scroller
32955  * @extends Ext.layout.container.boxOverflow.None
32956  * @private
32957  */
32958 Ext.define('Ext.layout.container.boxOverflow.Scroller', {
32959
32960     /* Begin Definitions */
32961
32962     extend: 'Ext.layout.container.boxOverflow.None',
32963     requires: ['Ext.util.ClickRepeater', 'Ext.core.Element'],
32964     alternateClassName: 'Ext.layout.boxOverflow.Scroller',
32965     mixins: {
32966         observable: 'Ext.util.Observable'
32967     },
32968     
32969     /* End Definitions */
32970
32971     /**
32972      * @cfg {Boolean} animateScroll
32973      * True to animate the scrolling of items within the layout (defaults to true, ignored if enableScroll is false)
32974      */
32975     animateScroll: false,
32976
32977     /**
32978      * @cfg {Number} scrollIncrement
32979      * The number of pixels to scroll by on scroller click (defaults to 24)
32980      */
32981     scrollIncrement: 20,
32982
32983     /**
32984      * @cfg {Number} wheelIncrement
32985      * The number of pixels to increment on mouse wheel scrolling (defaults to <tt>3</tt>).
32986      */
32987     wheelIncrement: 10,
32988
32989     /**
32990      * @cfg {Number} scrollRepeatInterval
32991      * Number of milliseconds between each scroll while a scroller button is held down (defaults to 20)
32992      */
32993     scrollRepeatInterval: 60,
32994
32995     /**
32996      * @cfg {Number} scrollDuration
32997      * Number of milliseconds that each scroll animation lasts (defaults to 400)
32998      */
32999     scrollDuration: 400,
33000
33001     /**
33002      * @cfg {String} beforeCtCls
33003      * CSS class added to the beforeCt element. This is the element that holds any special items such as scrollers,
33004      * which must always be present at the leftmost edge of the Container
33005      */
33006
33007     /**
33008      * @cfg {String} afterCtCls
33009      * CSS class added to the afterCt element. This is the element that holds any special items such as scrollers,
33010      * which must always be present at the rightmost edge of the Container
33011      */
33012
33013     /**
33014      * @cfg {String} scrollerCls
33015      * CSS class added to both scroller elements if enableScroll is used
33016      */
33017     scrollerCls: Ext.baseCSSPrefix + 'box-scroller',
33018
33019     /**
33020      * @cfg {String} beforeScrollerCls
33021      * CSS class added to the left scroller element if enableScroll is used
33022      */
33023
33024     /**
33025      * @cfg {String} afterScrollerCls
33026      * CSS class added to the right scroller element if enableScroll is used
33027      */
33028     
33029     constructor: function(layout, config) {
33030         this.layout = layout;
33031         Ext.apply(this, config || {});
33032         
33033         this.addEvents(
33034             /**
33035              * @event scroll
33036              * @param {Ext.layout.container.boxOverflow.Scroller} scroller The layout scroller
33037              * @param {Number} newPosition The new position of the scroller
33038              * @param {Boolean/Object} animate If animating or not. If true, it will be a animation configuration, else it will be false
33039              */
33040             'scroll'
33041         );
33042     },
33043     
33044     initCSSClasses: function() {
33045         var me = this,
33046         layout = me.layout;
33047
33048         if (!me.CSSinitialized) {
33049             me.beforeCtCls = me.beforeCtCls || Ext.baseCSSPrefix + 'box-scroller-' + layout.parallelBefore;
33050             me.afterCtCls  = me.afterCtCls  || Ext.baseCSSPrefix + 'box-scroller-' + layout.parallelAfter;
33051             me.beforeScrollerCls = me.beforeScrollerCls || Ext.baseCSSPrefix + layout.owner.getXType() + '-scroll-' + layout.parallelBefore;
33052             me.afterScrollerCls  = me.afterScrollerCls  || Ext.baseCSSPrefix + layout.owner.getXType() + '-scroll-' + layout.parallelAfter;
33053             me.CSSinitializes = true;
33054         }
33055     },
33056
33057     handleOverflow: function(calculations, targetSize) {
33058         var me = this,
33059             layout = me.layout,
33060             methodName = 'get' + layout.parallelPrefixCap,
33061             newSize = {};
33062
33063         me.initCSSClasses();
33064         me.callParent(arguments);
33065         this.createInnerElements();
33066         this.showScrollers();
33067         newSize[layout.perpendicularPrefix] = targetSize[layout.perpendicularPrefix];
33068         newSize[layout.parallelPrefix] = targetSize[layout.parallelPrefix] - (me.beforeCt[methodName]() + me.afterCt[methodName]());
33069         return { targetSize: newSize };
33070     },
33071
33072     /**
33073      * @private
33074      * Creates the beforeCt and afterCt elements if they have not already been created
33075      */
33076     createInnerElements: function() {
33077         var me = this,
33078             target = me.layout.getRenderTarget();
33079
33080         //normal items will be rendered to the innerCt. beforeCt and afterCt allow for fixed positioning of
33081         //special items such as scrollers or dropdown menu triggers
33082         if (!me.beforeCt) {
33083             target.addCls(Ext.baseCSSPrefix + me.layout.direction + '-box-overflow-body');
33084             me.beforeCt = target.insertSibling({cls: Ext.layout.container.Box.prototype.innerCls + ' ' + me.beforeCtCls}, 'before');
33085             me.afterCt  = target.insertSibling({cls: Ext.layout.container.Box.prototype.innerCls + ' ' + me.afterCtCls},  'after');
33086             me.createWheelListener();
33087         }
33088     },
33089
33090     /**
33091      * @private
33092      * Sets up an listener to scroll on the layout's innerCt mousewheel event
33093      */
33094     createWheelListener: function() {
33095         this.layout.innerCt.on({
33096             scope     : this,
33097             mousewheel: function(e) {
33098                 e.stopEvent();
33099
33100                 this.scrollBy(e.getWheelDelta() * this.wheelIncrement * -1, false);
33101             }
33102         });
33103     },
33104
33105     /**
33106      * @private
33107      */
33108     clearOverflow: function() {
33109         this.hideScrollers();
33110     },
33111
33112     /**
33113      * @private
33114      * Shows the scroller elements in the beforeCt and afterCt. Creates the scrollers first if they are not already
33115      * present. 
33116      */
33117     showScrollers: function() {
33118         this.createScrollers();
33119         this.beforeScroller.show();
33120         this.afterScroller.show();
33121         this.updateScrollButtons();
33122         
33123         this.layout.owner.addClsWithUI('scroller');
33124     },
33125
33126     /**
33127      * @private
33128      * Hides the scroller elements in the beforeCt and afterCt
33129      */
33130     hideScrollers: function() {
33131         if (this.beforeScroller != undefined) {
33132             this.beforeScroller.hide();
33133             this.afterScroller.hide();
33134             
33135             this.layout.owner.removeClsWithUI('scroller');
33136         }
33137     },
33138
33139     /**
33140      * @private
33141      * Creates the clickable scroller elements and places them into the beforeCt and afterCt
33142      */
33143     createScrollers: function() {
33144         if (!this.beforeScroller && !this.afterScroller) {
33145             var before = this.beforeCt.createChild({
33146                 cls: Ext.String.format("{0} {1} ", this.scrollerCls, this.beforeScrollerCls)
33147             });
33148
33149             var after = this.afterCt.createChild({
33150                 cls: Ext.String.format("{0} {1}", this.scrollerCls, this.afterScrollerCls)
33151             });
33152
33153             before.addClsOnOver(this.beforeScrollerCls + '-hover');
33154             after.addClsOnOver(this.afterScrollerCls + '-hover');
33155
33156             before.setVisibilityMode(Ext.core.Element.DISPLAY);
33157             after.setVisibilityMode(Ext.core.Element.DISPLAY);
33158
33159             this.beforeRepeater = Ext.create('Ext.util.ClickRepeater', before, {
33160                 interval: this.scrollRepeatInterval,
33161                 handler : this.scrollLeft,
33162                 scope   : this
33163             });
33164
33165             this.afterRepeater = Ext.create('Ext.util.ClickRepeater', after, {
33166                 interval: this.scrollRepeatInterval,
33167                 handler : this.scrollRight,
33168                 scope   : this
33169             });
33170
33171             /**
33172              * @property beforeScroller
33173              * @type Ext.core.Element
33174              * The left scroller element. Only created when needed.
33175              */
33176             this.beforeScroller = before;
33177
33178             /**
33179              * @property afterScroller
33180              * @type Ext.core.Element
33181              * The left scroller element. Only created when needed.
33182              */
33183             this.afterScroller = after;
33184         }
33185     },
33186
33187     /**
33188      * @private
33189      */
33190     destroy: function() {
33191         Ext.destroy(this.beforeRepeater, this.afterRepeater, this.beforeScroller, this.afterScroller, this.beforeCt, this.afterCt);
33192     },
33193
33194     /**
33195      * @private
33196      * Scrolls left or right by the number of pixels specified
33197      * @param {Number} delta Number of pixels to scroll to the right by. Use a negative number to scroll left
33198      */
33199     scrollBy: function(delta, animate) {
33200         this.scrollTo(this.getScrollPosition() + delta, animate);
33201     },
33202
33203     /**
33204      * @private
33205      * @return {Object} Object passed to scrollTo when scrolling
33206      */
33207     getScrollAnim: function() {
33208         return {
33209             duration: this.scrollDuration, 
33210             callback: this.updateScrollButtons, 
33211             scope   : this
33212         };
33213     },
33214
33215     /**
33216      * @private
33217      * Enables or disables each scroller button based on the current scroll position
33218      */
33219     updateScrollButtons: function() {
33220         if (this.beforeScroller == undefined || this.afterScroller == undefined) {
33221             return;
33222         }
33223
33224         var beforeMeth = this.atExtremeBefore()  ? 'addCls' : 'removeCls',
33225             afterMeth  = this.atExtremeAfter() ? 'addCls' : 'removeCls',
33226             beforeCls  = this.beforeScrollerCls + '-disabled',
33227             afterCls   = this.afterScrollerCls  + '-disabled';
33228         
33229         this.beforeScroller[beforeMeth](beforeCls);
33230         this.afterScroller[afterMeth](afterCls);
33231         this.scrolling = false;
33232     },
33233
33234     /**
33235      * @private
33236      * Returns true if the innerCt scroll is already at its left-most point
33237      * @return {Boolean} True if already at furthest left point
33238      */
33239     atExtremeBefore: function() {
33240         return this.getScrollPosition() === 0;
33241     },
33242
33243     /**
33244      * @private
33245      * Scrolls to the left by the configured amount
33246      */
33247     scrollLeft: function() {
33248         this.scrollBy(-this.scrollIncrement, false);
33249     },
33250
33251     /**
33252      * @private
33253      * Scrolls to the right by the configured amount
33254      */
33255     scrollRight: function() {
33256         this.scrollBy(this.scrollIncrement, false);
33257     },
33258
33259     /**
33260      * Returns the current scroll position of the innerCt element
33261      * @return {Number} The current scroll position
33262      */
33263     getScrollPosition: function(){
33264         var layout = this.layout;
33265         return parseInt(layout.innerCt.dom['scroll' + layout.parallelBeforeCap], 10) || 0;
33266     },
33267
33268     /**
33269      * @private
33270      * Returns the maximum value we can scrollTo
33271      * @return {Number} The max scroll value
33272      */
33273     getMaxScrollPosition: function() {
33274         var layout = this.layout;
33275         return layout.innerCt.dom['scroll' + layout.parallelPrefixCap] - this.layout.innerCt['get' + layout.parallelPrefixCap]();
33276     },
33277
33278     /**
33279      * @private
33280      * Returns true if the innerCt scroll is already at its right-most point
33281      * @return {Boolean} True if already at furthest right point
33282      */
33283     atExtremeAfter: function() {
33284         return this.getScrollPosition() >= this.getMaxScrollPosition();
33285     },
33286
33287     /**
33288      * @private
33289      * Scrolls to the given position. Performs bounds checking.
33290      * @param {Number} position The position to scroll to. This is constrained.
33291      * @param {Boolean} animate True to animate. If undefined, falls back to value of this.animateScroll
33292      */
33293     scrollTo: function(position, animate) {
33294         var me = this,
33295             layout = me.layout,
33296             oldPosition = me.getScrollPosition(),
33297             newPosition = Ext.Number.constrain(position, 0, me.getMaxScrollPosition());
33298
33299         if (newPosition != oldPosition && !me.scrolling) {
33300             if (animate == undefined) {
33301                 animate = me.animateScroll;
33302             }
33303
33304             layout.innerCt.scrollTo(layout.parallelBefore, newPosition, animate ? me.getScrollAnim() : false);
33305             if (animate) {
33306                 me.scrolling = true;
33307             } else {
33308                 me.scrolling = false;
33309                 me.updateScrollButtons();
33310             }
33311             
33312             me.fireEvent('scroll', me, newPosition, animate ? me.getScrollAnim() : false);
33313         }
33314     },
33315
33316     /**
33317      * Scrolls to the given component.
33318      * @param {String|Number|Ext.Component} item The item to scroll to. Can be a numerical index, component id 
33319      * or a reference to the component itself.
33320      * @param {Boolean} animate True to animate the scrolling
33321      */
33322     scrollToItem: function(item, animate) {
33323         var me = this,
33324             layout = me.layout,
33325             visibility,
33326             box,
33327             newPos;
33328
33329         item = me.getItem(item);
33330         if (item != undefined) {
33331             visibility = this.getItemVisibility(item);
33332             if (!visibility.fullyVisible) {
33333                 box  = item.getBox(true, true);
33334                 newPos = box[layout.parallelPosition];
33335                 if (visibility.hiddenEnd) {
33336                     newPos -= (this.layout.innerCt['get' + layout.parallelPrefixCap]() - box[layout.parallelPrefix]);
33337                 }
33338                 this.scrollTo(newPos, animate);
33339             }
33340         }
33341     },
33342
33343     /**
33344      * @private
33345      * For a given item in the container, return an object with information on whether the item is visible
33346      * with the current innerCt scroll value.
33347      * @param {Ext.Component} item The item
33348      * @return {Object} Values for fullyVisible, hiddenStart and hiddenEnd
33349      */
33350     getItemVisibility: function(item) {
33351         var me          = this,
33352             box         = me.getItem(item).getBox(true, true),
33353             layout      = me.layout,
33354             itemStart   = box[layout.parallelPosition],
33355             itemEnd     = itemStart + box[layout.parallelPrefix],
33356             scrollStart = me.getScrollPosition(),
33357             scrollEnd   = scrollStart + layout.innerCt['get' + layout.parallelPrefixCap]();
33358
33359         return {
33360             hiddenStart : itemStart < scrollStart,
33361             hiddenEnd   : itemEnd > scrollEnd,
33362             fullyVisible: itemStart > scrollStart && itemEnd < scrollEnd
33363         };
33364     }
33365 });
33366 /**
33367  * @class Ext.util.Offset
33368  * @ignore
33369  */
33370 Ext.define('Ext.util.Offset', {
33371
33372     /* Begin Definitions */
33373
33374     statics: {
33375         fromObject: function(obj) {
33376             return new this(obj.x, obj.y);
33377         }
33378     },
33379
33380     /* End Definitions */
33381
33382     constructor: function(x, y) {
33383         this.x = (x != null && !isNaN(x)) ? x : 0;
33384         this.y = (y != null && !isNaN(y)) ? y : 0;
33385
33386         return this;
33387     },
33388
33389     copy: function() {
33390         return new Ext.util.Offset(this.x, this.y);
33391     },
33392
33393     copyFrom: function(p) {
33394         this.x = p.x;
33395         this.y = p.y;
33396     },
33397
33398     toString: function() {
33399         return "Offset[" + this.x + "," + this.y + "]";
33400     },
33401
33402     equals: function(offset) {
33403         if(!(offset instanceof this.statics())) {
33404             Ext.Error.raise('Offset must be an instance of Ext.util.Offset');
33405         }
33406
33407         return (this.x == offset.x && this.y == offset.y);
33408     },
33409
33410     round: function(to) {
33411         if (!isNaN(to)) {
33412             var factor = Math.pow(10, to);
33413             this.x = Math.round(this.x * factor) / factor;
33414             this.y = Math.round(this.y * factor) / factor;
33415         } else {
33416             this.x = Math.round(this.x);
33417             this.y = Math.round(this.y);
33418         }
33419     },
33420
33421     isZero: function() {
33422         return this.x == 0 && this.y == 0;
33423     }
33424 });
33425
33426 /**
33427  * @class Ext.util.KeyNav
33428  * <p>Provides a convenient wrapper for normalized keyboard navigation.  KeyNav allows you to bind
33429  * navigation keys to function calls that will get called when the keys are pressed, providing an easy
33430  * way to implement custom navigation schemes for any UI component.</p>
33431  * <p>The following are all of the possible keys that can be implemented: enter, space, left, right, up, down, tab, esc,
33432  * pageUp, pageDown, del, backspace, home, end.  Usage:</p>
33433  <pre><code>
33434 var nav = new Ext.util.KeyNav("my-element", {
33435     "left" : function(e){
33436         this.moveLeft(e.ctrlKey);
33437     },
33438     "right" : function(e){
33439         this.moveRight(e.ctrlKey);
33440     },
33441     "enter" : function(e){
33442         this.save();
33443     },
33444     scope : this
33445 });
33446 </code></pre>
33447  * @constructor
33448  * @param {Mixed} el The element to bind to
33449  * @param {Object} config The config
33450  */
33451 Ext.define('Ext.util.KeyNav', {
33452     
33453     alternateClassName: 'Ext.KeyNav',
33454     
33455     requires: ['Ext.util.KeyMap'],
33456     
33457     statics: {
33458         keyOptions: {
33459             left: 37,
33460             right: 39,
33461             up: 38,
33462             down: 40,
33463             space: 32,
33464             pageUp: 33,
33465             pageDown: 34,
33466             del: 46,
33467             backspace: 8,
33468             home: 36,
33469             end: 35,
33470             enter: 13,
33471             esc: 27,
33472             tab: 9
33473         }
33474     },
33475     
33476     constructor: function(el, config){
33477         this.setConfig(el, config || {});
33478     },
33479     
33480     /**
33481      * Sets up a configuration for the KeyNav.
33482      * @private
33483      * @param {Mixed} el The element to bind to
33484      * @param {Object}A configuration object as specified in the constructor.
33485      */
33486     setConfig: function(el, config) {
33487         if (this.map) {
33488             this.map.destroy();
33489         }
33490         
33491         var map = Ext.create('Ext.util.KeyMap', el, null, this.getKeyEvent('forceKeyDown' in config ? config.forceKeyDown : this.forceKeyDown)),
33492             keys = Ext.util.KeyNav.keyOptions,
33493             scope = config.scope || this,
33494             key;
33495         
33496         this.map = map;
33497         for (key in keys) {
33498             if (keys.hasOwnProperty(key)) {
33499                 if (config[key]) {
33500                     map.addBinding({
33501                         scope: scope,
33502                         key: keys[key],
33503                         handler: Ext.Function.bind(this.handleEvent, scope, [config[key]], true),
33504                         defaultEventAction: config.defaultEventAction || this.defaultEventAction
33505                     });
33506                 }
33507             }
33508         }
33509         
33510         map.disable();
33511         if (!config.disabled) {
33512             map.enable();
33513         }
33514     },
33515     
33516     /**
33517      * Method for filtering out the map argument
33518      * @private
33519      * @param {Ext.util.KeyMap} map
33520      * @param {Ext.EventObject} event
33521      * @param {Object} options Contains the handler to call
33522      */
33523     handleEvent: function(map, event, handler){
33524         return handler.call(this, event);
33525     },
33526     
33527     /**
33528      * @cfg {Boolean} disabled
33529      * True to disable this KeyNav instance (defaults to false)
33530      */
33531     disabled: false,
33532     
33533     /**
33534      * @cfg {String} defaultEventAction
33535      * The method to call on the {@link Ext.EventObject} after this KeyNav intercepts a key.  Valid values are
33536      * {@link Ext.EventObject#stopEvent}, {@link Ext.EventObject#preventDefault} and
33537      * {@link Ext.EventObject#stopPropagation} (defaults to 'stopEvent')
33538      */
33539     defaultEventAction: "stopEvent",
33540     
33541     /**
33542      * @cfg {Boolean} forceKeyDown
33543      * Handle the keydown event instead of keypress (defaults to false).  KeyNav automatically does this for IE since
33544      * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
33545      * handle keydown instead of keypress.
33546      */
33547     forceKeyDown: false,
33548     
33549     /**
33550      * Destroy this KeyNav (this is the same as calling disable).
33551      * @param {Boolean} removeEl True to remove the element associated with this KeyNav.
33552      */
33553     destroy: function(removeEl){
33554         this.map.destroy(removeEl);
33555         delete this.map;
33556     },
33557
33558     /**
33559      * Enable this KeyNav
33560      */
33561     enable: function() {
33562         this.map.enable();
33563         this.disabled = false;
33564     },
33565
33566     /**
33567      * Disable this KeyNav
33568      */
33569     disable: function() {
33570         this.map.disable();
33571         this.disabled = true;
33572     },
33573     
33574     /**
33575      * Convenience function for setting disabled/enabled by boolean.
33576      * @param {Boolean} disabled
33577      */
33578     setDisabled : function(disabled){
33579         this.map.setDisabled(disabled);
33580         this.disabled = disabled;
33581     },
33582     
33583     /**
33584      * Determines the event to bind to listen for keys. Depends on the {@link #forceKeyDown} setting,
33585      * as well as the useKeyDown option on the EventManager.
33586      * @return {String} The type of event to listen for.
33587      */
33588     getKeyEvent: function(forceKeyDown){
33589         return (forceKeyDown || Ext.EventManager.useKeyDown) ? 'keydown' : 'keypress';
33590     }
33591 });
33592
33593 /**
33594  * @class Ext.fx.Queue
33595  * Animation Queue mixin to handle chaining and queueing by target.
33596  * @private
33597  */
33598
33599 Ext.define('Ext.fx.Queue', {
33600
33601     requires: ['Ext.util.HashMap'],
33602
33603     constructor: function() {
33604         this.targets = Ext.create('Ext.util.HashMap');
33605         this.fxQueue = {};
33606     },
33607
33608     // @private
33609     getFxDefaults: function(targetId) {
33610         var target = this.targets.get(targetId);
33611         if (target) {
33612             return target.fxDefaults;
33613         }
33614         return {};
33615     },
33616
33617     // @private
33618     setFxDefaults: function(targetId, obj) {
33619         var target = this.targets.get(targetId);
33620         if (target) {
33621             target.fxDefaults = Ext.apply(target.fxDefaults || {}, obj);
33622         }
33623     },
33624
33625     // @private
33626     stopAnimation: function(targetId) {
33627         var me = this,
33628             queue = me.getFxQueue(targetId),
33629             ln = queue.length;
33630         while (ln) {
33631             queue[ln - 1].end();
33632             ln--;
33633         }
33634     },
33635
33636     /**
33637      * @private
33638      * Returns current animation object if the element has any effects actively running or queued, else returns false.
33639      */
33640     getActiveAnimation: function(targetId) {
33641         var queue = this.getFxQueue(targetId);
33642         return (queue && !!queue.length) ? queue[0] : false;
33643     },
33644
33645     // @private
33646     hasFxBlock: function(targetId) {
33647         var queue = this.getFxQueue(targetId);
33648         return queue && queue[0] && queue[0].block;
33649     },
33650
33651     // @private get fx queue for passed target, create if needed.
33652     getFxQueue: function(targetId) {
33653         if (!targetId) {
33654             return false;
33655         }
33656         var me = this,
33657             queue = me.fxQueue[targetId],
33658             target = me.targets.get(targetId);
33659
33660         if (!target) {
33661             return false;
33662         }
33663
33664         if (!queue) {
33665             me.fxQueue[targetId] = [];
33666             // GarbageCollector will need to clean up Elements since they aren't currently observable
33667             if (target.type != 'element') {
33668                 target.target.on('destroy', function() {
33669                     me.fxQueue[targetId] = [];
33670                 });
33671             }
33672         }
33673         return me.fxQueue[targetId];
33674     },
33675
33676     // @private
33677     queueFx: function(anim) {
33678         var me = this,
33679             target = anim.target,
33680             queue, ln;
33681
33682         if (!target) {
33683             return;
33684         }
33685
33686         queue = me.getFxQueue(target.getId());
33687         ln = queue.length;
33688
33689         if (ln) {
33690             if (anim.concurrent) {
33691                 anim.paused = false;
33692             }
33693             else {
33694                 queue[ln - 1].on('afteranimate', function() {
33695                     anim.paused = false;
33696                 });
33697             }
33698         }
33699         else {
33700             anim.paused = false;
33701         }
33702         anim.on('afteranimate', function() {
33703             Ext.Array.remove(queue, anim);
33704             if (anim.remove) {
33705                 if (target.type == 'element') {
33706                     var el = Ext.get(target.id);
33707                     if (el) {
33708                         el.remove();
33709                     }
33710                 }
33711             }
33712         }, this);
33713         queue.push(anim);
33714     }
33715 });
33716 /**
33717  * @class Ext.fx.target.Target
33718
33719 This class specifies a generic target for an animation. It provides a wrapper around a
33720 series of different types of objects to allow for a generic animation API.
33721 A target can be a single object or a Composite object containing other objects that are 
33722 to be animated. This class and it's subclasses are generally not created directly, the 
33723 underlying animation will create the appropriate Ext.fx.target.Target object by passing 
33724 the instance to be animated.
33725
33726 The following types of objects can be animated:
33727 - {@link #Ext.fx.target.Component Components}
33728 - {@link #Ext.fx.target.Element Elements}
33729 - {@link #Ext.fx.target.Sprite Sprites}
33730
33731  * @markdown
33732  * @abstract
33733  * @constructor
33734  * @param {Mixed} target The object to be animated
33735  */
33736
33737 Ext.define('Ext.fx.target.Target', {
33738
33739     isAnimTarget: true,
33740
33741     constructor: function(target) {
33742         this.target = target;
33743         this.id = this.getId();
33744     },
33745     
33746     getId: function() {
33747         return this.target.id;
33748     }
33749 });
33750
33751 /**
33752  * @class Ext.fx.target.Sprite
33753  * @extends Ext.fx.target.Target
33754
33755 This class represents a animation target for a {@link Ext.draw.Sprite}. In general this class will not be
33756 created directly, the {@link Ext.draw.Sprite} will be passed to the animation and
33757 and the appropriate target will be created.
33758
33759  * @markdown
33760  */
33761
33762 Ext.define('Ext.fx.target.Sprite', {
33763
33764     /* Begin Definitions */
33765
33766     extend: 'Ext.fx.target.Target',
33767
33768     /* End Definitions */
33769
33770     type: 'draw',
33771
33772     getFromPrim: function(sprite, attr) {
33773         var o;
33774         if (attr == 'translate') {
33775             o = {
33776                 x: sprite.attr.translation.x || 0,
33777                 y: sprite.attr.translation.y || 0
33778             };
33779         }
33780         else if (attr == 'rotate') {
33781             o = {
33782                 degrees: sprite.attr.rotation.degrees || 0,
33783                 x: sprite.attr.rotation.x,
33784                 y: sprite.attr.rotation.y
33785             };
33786         }
33787         else {
33788             o = sprite.attr[attr];
33789         }
33790         return o;
33791     },
33792
33793     getAttr: function(attr, val) {
33794         return [[this.target, val != undefined ? val : this.getFromPrim(this.target, attr)]];
33795     },
33796
33797     setAttr: function(targetData) {
33798         var ln = targetData.length,
33799             spriteArr = [],
33800             attrs, attr, attrArr, attPtr, spritePtr, idx, value, i, j, x, y, ln2;
33801         for (i = 0; i < ln; i++) {
33802             attrs = targetData[i].attrs;
33803             for (attr in attrs) {
33804                 attrArr = attrs[attr];
33805                 ln2 = attrArr.length;
33806                 for (j = 0; j < ln2; j++) {
33807                     spritePtr = attrArr[j][0];
33808                     attPtr = attrArr[j][1];
33809                     if (attr === 'translate') {
33810                         value = {
33811                             x: attPtr.x,
33812                             y: attPtr.y
33813                         };
33814                     }
33815                     else if (attr === 'rotate') {
33816                         x = attPtr.x;
33817                         if (isNaN(x)) {
33818                             x = null;
33819                         }
33820                         y = attPtr.y;
33821                         if (isNaN(y)) {
33822                             y = null;
33823                         }
33824                         value = {
33825                             degrees: attPtr.degrees,
33826                             x: x,
33827                             y: y
33828                         };
33829                     }
33830                     else if (attr === 'width' || attr === 'height' || attr === 'x' || attr === 'y') {
33831                         value = parseFloat(attPtr);
33832                     }
33833                     else {
33834                         value = attPtr;
33835                     }
33836                     idx = Ext.Array.indexOf(spriteArr, spritePtr);
33837                     if (idx == -1) {
33838                         spriteArr.push([spritePtr, {}]);
33839                         idx = spriteArr.length - 1;
33840                     }
33841                     spriteArr[idx][1][attr] = value;
33842                 }
33843             }
33844         }
33845         ln = spriteArr.length;
33846         for (i = 0; i < ln; i++) {
33847             spritePtr = spriteArr[i];
33848             spritePtr[0].setAttributes(spritePtr[1]);
33849         }
33850         this.target.redraw();
33851     }
33852 });
33853
33854 /**
33855  * @class Ext.fx.target.CompositeSprite
33856  * @extends Ext.fx.target.Sprite
33857
33858 This class represents a animation target for a {@link Ext.draw.CompositeSprite}. It allows
33859 each {@link Ext.draw.Sprite} in the group to be animated as a whole. In general this class will not be
33860 created directly, the {@link Ext.draw.CompositeSprite} will be passed to the animation and
33861 and the appropriate target will be created.
33862
33863  * @markdown
33864  */
33865
33866 Ext.define('Ext.fx.target.CompositeSprite', {
33867
33868     /* Begin Definitions */
33869
33870     extend: 'Ext.fx.target.Sprite',
33871
33872     /* End Definitions */
33873
33874     getAttr: function(attr, val) {
33875         var out = [],
33876             target = this.target;
33877         target.each(function(sprite) {
33878             out.push([sprite, val != undefined ? val : this.getFromPrim(sprite, attr)]);
33879         }, this);
33880         return out;
33881     }
33882 });
33883
33884 /**
33885  * @class Ext.fx.target.Component
33886  * @extends Ext.fx.target.Target
33887  * 
33888  * This class represents a animation target for a {@link Ext.Component}. In general this class will not be
33889  * created directly, the {@link Ext.Component} will be passed to the animation and
33890  * and the appropriate target will be created.
33891  */
33892 Ext.define('Ext.fx.target.Component', {
33893
33894     /* Begin Definitions */
33895    
33896     extend: 'Ext.fx.target.Target',
33897     
33898     /* End Definitions */
33899
33900     type: 'component',
33901
33902     // Methods to call to retrieve unspecified "from" values from a target Component
33903     getPropMethod: {
33904         top: function() {
33905             return this.getPosition(true)[1];
33906         },
33907         left: function() {
33908             return this.getPosition(true)[0];
33909         },
33910         x: function() {
33911             return this.getPosition()[0];
33912         },
33913         y: function() {
33914             return this.getPosition()[1];
33915         },
33916         height: function() {
33917             return this.getHeight();
33918         },
33919         width: function() {
33920             return this.getWidth();
33921         },
33922         opacity: function() {
33923             return this.el.getStyle('opacity');
33924         }
33925     },
33926
33927     compMethod: {
33928         top: 'setPosition',
33929         left: 'setPosition',
33930         x: 'setPagePosition',
33931         y: 'setPagePosition',
33932         height: 'setSize',
33933         width: 'setSize',
33934         opacity: 'setOpacity'
33935     },
33936
33937     // Read the named attribute from the target Component. Use the defined getter for the attribute
33938     getAttr: function(attr, val) {
33939         return [[this.target, val !== undefined ? val : this.getPropMethod[attr].call(this.target)]];
33940     },
33941
33942     setAttr: function(targetData, isFirstFrame, isLastFrame) {
33943         var me = this,
33944             target = me.target,
33945             ln = targetData.length,
33946             attrs, attr, o, i, j, meth, targets, left, top, w, h;
33947         for (i = 0; i < ln; i++) {
33948             attrs = targetData[i].attrs;
33949             for (attr in attrs) {
33950                 targets = attrs[attr].length;
33951                 meth = {
33952                     setPosition: {},
33953                     setPagePosition: {},
33954                     setSize: {},
33955                     setOpacity: {}
33956                 };
33957                 for (j = 0; j < targets; j++) {
33958                     o = attrs[attr][j];
33959                     // We REALLY want a single function call, so push these down to merge them: eg
33960                     // meth.setPagePosition.target = <targetComponent>
33961                     // meth.setPagePosition['x'] = 100
33962                     // meth.setPagePosition['y'] = 100
33963                     meth[me.compMethod[attr]].target = o[0];
33964                     meth[me.compMethod[attr]][attr] = o[1];
33965                 }
33966                 if (meth.setPosition.target) {
33967                     o = meth.setPosition;
33968                     left = (o.left === undefined) ? undefined : parseInt(o.left, 10);
33969                     top = (o.top === undefined) ? undefined : parseInt(o.top, 10);
33970                     o.target.setPosition(left, top);
33971                 }
33972                 if (meth.setPagePosition.target) {
33973                     o = meth.setPagePosition;
33974                     o.target.setPagePosition(o.x, o.y);
33975                 }
33976                 if (meth.setSize.target) {
33977                     o = meth.setSize;
33978                     // Dimensions not being animated MUST NOT be autosized. They must remain at current value.
33979                     w = (o.width === undefined) ? o.target.getWidth() : parseInt(o.width, 10);
33980                     h = (o.height === undefined) ? o.target.getHeight() : parseInt(o.height, 10);
33981
33982                     // Only set the size of the Component on the last frame, or if the animation was
33983                     // configured with dynamic: true.
33984                     // In other cases, we just set the target element size.
33985                     // This will result in either clipping if animating a reduction in size, or the revealing of
33986                     // the inner elements of the Component if animating an increase in size.
33987                     // Component's animate function initially resizes to the larger size before resizing the
33988                     // outer element to clip the contents.
33989                     if (isLastFrame || me.dynamic) {
33990                         o.target.componentLayout.childrenChanged = true;
33991
33992                         // Flag if we are being called by an animating layout: use setCalculatedSize
33993                         if (me.layoutAnimation) {
33994                             o.target.setCalculatedSize(w, h);
33995                         } else {
33996                             o.target.setSize(w, h);
33997                         }
33998                     }
33999                     else {
34000                         o.target.el.setSize(w, h);
34001                     }
34002                 }
34003                 if (meth.setOpacity.target) {
34004                     o = meth.setOpacity;
34005                     o.target.el.setStyle('opacity', o.opacity);
34006                 }
34007             }
34008         }
34009     }
34010 });
34011
34012 /**
34013  * @class Ext.fx.CubicBezier
34014  * @ignore
34015  */
34016 Ext.define('Ext.fx.CubicBezier', {
34017
34018     /* Begin Definitions */
34019
34020     singleton: true,
34021
34022     /* End Definitions */
34023
34024     cubicBezierAtTime: function(t, p1x, p1y, p2x, p2y, duration) {
34025         var cx = 3 * p1x,
34026             bx = 3 * (p2x - p1x) - cx,
34027             ax = 1 - cx - bx,
34028             cy = 3 * p1y,
34029             by = 3 * (p2y - p1y) - cy,
34030             ay = 1 - cy - by;
34031         function sampleCurveX(t) {
34032             return ((ax * t + bx) * t + cx) * t;
34033         }
34034         function solve(x, epsilon) {
34035             var t = solveCurveX(x, epsilon);
34036             return ((ay * t + by) * t + cy) * t;
34037         }
34038         function solveCurveX(x, epsilon) {
34039             var t0, t1, t2, x2, d2, i;
34040             for (t2 = x, i = 0; i < 8; i++) {
34041                 x2 = sampleCurveX(t2) - x;
34042                 if (Math.abs(x2) < epsilon) {
34043                     return t2;
34044                 }
34045                 d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
34046                 if (Math.abs(d2) < 1e-6) {
34047                     break;
34048                 }
34049                 t2 = t2 - x2 / d2;
34050             }
34051             t0 = 0;
34052             t1 = 1;
34053             t2 = x;
34054             if (t2 < t0) {
34055                 return t0;
34056             }
34057             if (t2 > t1) {
34058                 return t1;
34059             }
34060             while (t0 < t1) {
34061                 x2 = sampleCurveX(t2);
34062                 if (Math.abs(x2 - x) < epsilon) {
34063                     return t2;
34064                 }
34065                 if (x > x2) {
34066                     t0 = t2;
34067                 } else {
34068                     t1 = t2;
34069                 }
34070                 t2 = (t1 - t0) / 2 + t0;
34071             }
34072             return t2;
34073         }
34074         return solve(t, 1 / (200 * duration));
34075     },
34076
34077     cubicBezier: function(x1, y1, x2, y2) {
34078         var fn = function(pos) {
34079             return Ext.fx.CubicBezier.cubicBezierAtTime(pos, x1, y1, x2, y2, 1);
34080         };
34081         fn.toCSS3 = function() {
34082             return 'cubic-bezier(' + [x1, y1, x2, y2].join(',') + ')';
34083         };
34084         fn.reverse = function() {
34085             return Ext.fx.CubicBezier.cubicBezier(1 - x2, 1 - y2, 1 - x1, 1 - y1);
34086         };
34087         return fn;
34088     }
34089 });
34090 /**
34091  * @class Ext.draw.Color
34092  * @extends Object
34093  *
34094  * Represents an RGB color and provides helper functions get
34095  * color components in HSL color space.
34096  */
34097 Ext.define('Ext.draw.Color', {
34098
34099     /* Begin Definitions */
34100
34101     /* End Definitions */
34102
34103     colorToHexRe: /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/,
34104     rgbRe: /\s*rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)\s*/,
34105     hexRe: /\s*#([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)\s*/,
34106
34107     /**
34108      * @cfg {Number} lightnessFactor
34109      *
34110      * The default factor to compute the lighter or darker color. Defaults to 0.2.
34111      */
34112     lightnessFactor: 0.2,
34113
34114     /**
34115      * @constructor
34116      * @param {Number} red Red component (0..255)
34117      * @param {Number} green Green component (0..255)
34118      * @param {Number} blue Blue component (0..255)
34119      */
34120     constructor : function(red, green, blue) {
34121         var me = this,
34122             clamp = Ext.Number.constrain;
34123         me.r = clamp(red, 0, 255);
34124         me.g = clamp(green, 0, 255);
34125         me.b = clamp(blue, 0, 255);
34126     },
34127
34128     /**
34129      * Get the red component of the color, in the range 0..255.
34130      * @return {Number}
34131      */
34132     getRed: function() {
34133         return this.r;
34134     },
34135
34136     /**
34137      * Get the green component of the color, in the range 0..255.
34138      * @return {Number}
34139      */
34140     getGreen: function() {
34141         return this.g;
34142     },
34143
34144     /**
34145      * Get the blue component of the color, in the range 0..255.
34146      * @return {Number}
34147      */
34148     getBlue: function() {
34149         return this.b;
34150     },
34151
34152     /**
34153      * Get the RGB values.
34154      * @return {Array}
34155      */
34156     getRGB: function() {
34157         var me = this;
34158         return [me.r, me.g, me.b];
34159     },
34160
34161     /**
34162      * Get the equivalent HSL components of the color.
34163      * @return {Array}
34164      */
34165     getHSL: function() {
34166         var me = this,
34167             r = me.r / 255,
34168             g = me.g / 255,
34169             b = me.b / 255,
34170             max = Math.max(r, g, b),
34171             min = Math.min(r, g, b),
34172             delta = max - min,
34173             h,
34174             s = 0,
34175             l = 0.5 * (max + min);
34176
34177         // min==max means achromatic (hue is undefined)
34178         if (min != max) {
34179             s = (l < 0.5) ? delta / (max + min) : delta / (2 - max - min);
34180             if (r == max) {
34181                 h = 60 * (g - b) / delta;
34182             } else if (g == max) {
34183                 h = 120 + 60 * (b - r) / delta;
34184             } else {
34185                 h = 240 + 60 * (r - g) / delta;
34186             }
34187             if (h < 0) {
34188                 h += 360;
34189             }
34190             if (h >= 360) {
34191                 h -= 360;
34192             }
34193         }
34194         return [h, s, l];
34195     },
34196
34197     /**
34198      * Return a new color that is lighter than this color.
34199      * @param {Number} factor Lighter factor (0..1), default to 0.2
34200      * @return Ext.draw.Color
34201      */
34202     getLighter: function(factor) {
34203         var hsl = this.getHSL();
34204         factor = factor || this.lightnessFactor;
34205         hsl[2] = Ext.Number.constrain(hsl[2] + factor, 0, 1);
34206         return this.fromHSL(hsl[0], hsl[1], hsl[2]);
34207     },
34208
34209     /**
34210      * Return a new color that is darker than this color.
34211      * @param {Number} factor Darker factor (0..1), default to 0.2
34212      * @return Ext.draw.Color
34213      */
34214     getDarker: function(factor) {
34215         factor = factor || this.lightnessFactor;
34216         return this.getLighter(-factor);
34217     },
34218
34219     /**
34220      * Return the color in the hex format, i.e. '#rrggbb'.
34221      * @return {String}
34222      */
34223     toString: function() {
34224         var me = this,
34225             round = Math.round,
34226             r = round(me.r).toString(16),
34227             g = round(me.g).toString(16),
34228             b = round(me.b).toString(16);
34229         r = (r.length == 1) ? '0' + r : r;
34230         g = (g.length == 1) ? '0' + g : g;
34231         b = (b.length == 1) ? '0' + b : b;
34232         return ['#', r, g, b].join('');
34233     },
34234
34235     /**
34236      * Convert a color to hexadecimal format.
34237      *
34238      * @param {String|Array} color The color value (i.e 'rgb(255, 255, 255)', 'color: #ffffff').
34239      * Can also be an Array, in this case the function handles the first member.
34240      * @returns {String} The color in hexadecimal format.
34241      */
34242     toHex: function(color) {
34243         if (Ext.isArray(color)) {
34244             color = color[0];
34245         }
34246         if (!Ext.isString(color)) {
34247             return '';
34248         }
34249         if (color.substr(0, 1) === '#') {
34250             return color;
34251         }
34252         var digits = this.colorToHexRe.exec(color);
34253
34254         if (Ext.isArray(digits)) {
34255             var red = parseInt(digits[2], 10),
34256                 green = parseInt(digits[3], 10),
34257                 blue = parseInt(digits[4], 10),
34258                 rgb = blue | (green << 8) | (red << 16);
34259             return digits[1] + '#' + ("000000" + rgb.toString(16)).slice(-6);
34260         }
34261         else {
34262             return '';
34263         }
34264     },
34265
34266     /**
34267      * Parse the string and create a new color.
34268      *
34269      * Supported formats: '#rrggbb', '#rgb', and 'rgb(r,g,b)'.
34270      *
34271      * If the string is not recognized, an undefined will be returned instead.
34272      *
34273      * @param {String} str Color in string.
34274      * @returns Ext.draw.Color
34275      */
34276     fromString: function(str) {
34277         var values, r, g, b,
34278             parse = parseInt;
34279
34280         if ((str.length == 4 || str.length == 7) && str.substr(0, 1) === '#') {
34281             values = str.match(this.hexRe);
34282             if (values) {
34283                 r = parse(values[1], 16) >> 0;
34284                 g = parse(values[2], 16) >> 0;
34285                 b = parse(values[3], 16) >> 0;
34286                 if (str.length == 4) {
34287                     r += (r * 16);
34288                     g += (g * 16);
34289                     b += (b * 16);
34290                 }
34291             }
34292         }
34293         else {
34294             values = str.match(this.rgbRe);
34295             if (values) {
34296                 r = values[1];
34297                 g = values[2];
34298                 b = values[3];
34299             }
34300         }
34301
34302         return (typeof r == 'undefined') ? undefined : Ext.create('Ext.draw.Color', r, g, b);
34303     },
34304
34305     /**
34306      * Returns the gray value (0 to 255) of the color.
34307      *
34308      * The gray value is calculated using the formula r*0.3 + g*0.59 + b*0.11.
34309      *
34310      * @returns {Number}
34311      */
34312     getGrayscale: function() {
34313         // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
34314         return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
34315     },
34316
34317     /**
34318      * Create a new color based on the specified HSL values.
34319      *
34320      * @param {Number} h Hue component (0..359)
34321      * @param {Number} s Saturation component (0..1)
34322      * @param {Number} l Lightness component (0..1)
34323      * @returns Ext.draw.Color
34324      */
34325     fromHSL: function(h, s, l) {
34326         var C, X, m, i, rgb = [],
34327             abs = Math.abs,
34328             floor = Math.floor;
34329
34330         if (s == 0 || h == null) {
34331             // achromatic
34332             rgb = [l, l, l];
34333         }
34334         else {
34335             // http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL
34336             // C is the chroma
34337             // X is the second largest component
34338             // m is the lightness adjustment
34339             h /= 60;
34340             C = s * (1 - abs(2 * l - 1));
34341             X = C * (1 - abs(h - 2 * floor(h / 2) - 1));
34342             m = l - C / 2;
34343             switch (floor(h)) {
34344                 case 0:
34345                     rgb = [C, X, 0];
34346                     break;
34347                 case 1:
34348                     rgb = [X, C, 0];
34349                     break;
34350                 case 2:
34351                     rgb = [0, C, X];
34352                     break;
34353                 case 3:
34354                     rgb = [0, X, C];
34355                     break;
34356                 case 4:
34357                     rgb = [X, 0, C];
34358                     break;
34359                 case 5:
34360                     rgb = [C, 0, X];
34361                     break;
34362             }
34363             rgb = [rgb[0] + m, rgb[1] + m, rgb[2] + m];
34364         }
34365         return Ext.create('Ext.draw.Color', rgb[0] * 255, rgb[1] * 255, rgb[2] * 255);
34366     }
34367 }, function() {
34368     var prototype = this.prototype;
34369
34370     //These functions are both static and instance. TODO: find a more elegant way of copying them
34371     this.addStatics({
34372         fromHSL: function() {
34373             return prototype.fromHSL.apply(prototype, arguments);
34374         },
34375         fromString: function() {
34376             return prototype.fromString.apply(prototype, arguments);
34377         },
34378         toHex: function() {
34379             return prototype.toHex.apply(prototype, arguments);
34380         }
34381     });
34382 });
34383
34384 /**
34385  * @class Ext.dd.StatusProxy
34386  * A specialized drag proxy that supports a drop status icon, {@link Ext.Layer} styles and auto-repair.  This is the
34387  * default drag proxy used by all Ext.dd components.
34388  * @constructor
34389  * @param {Object} config
34390  */
34391 Ext.define('Ext.dd.StatusProxy', {
34392     animRepair: false,
34393
34394     constructor: function(config){
34395         Ext.apply(this, config);
34396         this.id = this.id || Ext.id();
34397         this.proxy = Ext.createWidget('component', {
34398             floating: true,
34399             id: this.id,
34400             html: '<div class="' + Ext.baseCSSPrefix + 'dd-drop-icon"></div>' +
34401                   '<div class="' + Ext.baseCSSPrefix + 'dd-drag-ghost"></div>',
34402             cls: Ext.baseCSSPrefix + 'dd-drag-proxy ' + this.dropNotAllowed,
34403             shadow: !config || config.shadow !== false,
34404             renderTo: document.body
34405         });
34406
34407         this.el = this.proxy.el;
34408         this.el.show();
34409         this.el.setVisibilityMode(Ext.core.Element.VISIBILITY);
34410         this.el.hide();
34411
34412         this.ghost = Ext.get(this.el.dom.childNodes[1]);
34413         this.dropStatus = this.dropNotAllowed;
34414     },
34415     /**
34416      * @cfg {String} dropAllowed
34417      * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
34418      */
34419     dropAllowed : Ext.baseCSSPrefix + 'dd-drop-ok',
34420     /**
34421      * @cfg {String} dropNotAllowed
34422      * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
34423      */
34424     dropNotAllowed : Ext.baseCSSPrefix + 'dd-drop-nodrop',
34425
34426     /**
34427      * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
34428      * over the current target element.
34429      * @param {String} cssClass The css class for the new drop status indicator image
34430      */
34431     setStatus : function(cssClass){
34432         cssClass = cssClass || this.dropNotAllowed;
34433         if(this.dropStatus != cssClass){
34434             this.el.replaceCls(this.dropStatus, cssClass);
34435             this.dropStatus = cssClass;
34436         }
34437     },
34438
34439     /**
34440      * Resets the status indicator to the default dropNotAllowed value
34441      * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
34442      */
34443     reset : function(clearGhost){
34444         this.el.dom.className = Ext.baseCSSPrefix + 'dd-drag-proxy ' + this.dropNotAllowed;
34445         this.dropStatus = this.dropNotAllowed;
34446         if(clearGhost){
34447             this.ghost.update("");
34448         }
34449     },
34450
34451     /**
34452      * Updates the contents of the ghost element
34453      * @param {String/HTMLElement} html The html that will replace the current innerHTML of the ghost element, or a
34454      * DOM node to append as the child of the ghost element (in which case the innerHTML will be cleared first).
34455      */
34456     update : function(html){
34457         if(typeof html == "string"){
34458             this.ghost.update(html);
34459         }else{
34460             this.ghost.update("");
34461             html.style.margin = "0";
34462             this.ghost.dom.appendChild(html);
34463         }
34464         var el = this.ghost.dom.firstChild; 
34465         if(el){
34466             Ext.fly(el).setStyle('float', 'none');
34467         }
34468     },
34469
34470     /**
34471      * Returns the underlying proxy {@link Ext.Layer}
34472      * @return {Ext.Layer} el
34473     */
34474     getEl : function(){
34475         return this.el;
34476     },
34477
34478     /**
34479      * Returns the ghost element
34480      * @return {Ext.core.Element} el
34481      */
34482     getGhost : function(){
34483         return this.ghost;
34484     },
34485
34486     /**
34487      * Hides the proxy
34488      * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
34489      */
34490     hide : function(clear) {
34491         this.proxy.hide();
34492         if (clear) {
34493             this.reset(true);
34494         }
34495     },
34496
34497     /**
34498      * Stops the repair animation if it's currently running
34499      */
34500     stop : function(){
34501         if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
34502             this.anim.stop();
34503         }
34504     },
34505
34506     /**
34507      * Displays this proxy
34508      */
34509     show : function() {
34510         this.proxy.show();
34511         this.proxy.toFront();
34512     },
34513
34514     /**
34515      * Force the Layer to sync its shadow and shim positions to the element
34516      */
34517     sync : function(){
34518         this.proxy.el.sync();
34519     },
34520
34521     /**
34522      * Causes the proxy to return to its position of origin via an animation.  Should be called after an
34523      * invalid drop operation by the item being dragged.
34524      * @param {Array} xy The XY position of the element ([x, y])
34525      * @param {Function} callback The function to call after the repair is complete.
34526      * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
34527      */
34528     repair : function(xy, callback, scope){
34529         this.callback = callback;
34530         this.scope = scope;
34531         if (xy && this.animRepair !== false) {
34532             this.el.addCls(Ext.baseCSSPrefix + 'dd-drag-repair');
34533             this.el.hideUnders(true);
34534             this.anim = this.el.animate({
34535                 duration: this.repairDuration || 500,
34536                 easing: 'ease-out',
34537                 to: {
34538                     x: xy[0],
34539                     y: xy[1]
34540                 },
34541                 stopAnimation: true,
34542                 callback: this.afterRepair,
34543                 scope: this
34544             });
34545         } else {
34546             this.afterRepair();
34547         }
34548     },
34549
34550     // private
34551     afterRepair : function(){
34552         this.hide(true);
34553         if(typeof this.callback == "function"){
34554             this.callback.call(this.scope || this);
34555         }
34556         this.callback = null;
34557         this.scope = null;
34558     },
34559
34560     destroy: function(){
34561         Ext.destroy(this.ghost, this.proxy, this.el);
34562     }
34563 });
34564 /**
34565  * @class Ext.panel.Proxy
34566  * @extends Object
34567  * A custom drag proxy implementation specific to {@link Ext.panel.Panel}s. This class
34568  * is primarily used internally for the Panel's drag drop implementation, and
34569  * should never need to be created directly.
34570  * @constructor
34571  * @param panel The {@link Ext.panel.Panel} to proxy for
34572  * @param config Configuration options
34573  */
34574 Ext.define('Ext.panel.Proxy', {
34575     
34576     alternateClassName: 'Ext.dd.PanelProxy',
34577     
34578     constructor: function(panel, config){
34579         /**
34580          * @property panel
34581          * @type Ext.panel.Panel
34582          */
34583         this.panel = panel;
34584         this.id = this.panel.id +'-ddproxy';
34585         Ext.apply(this, config);
34586     },
34587
34588     /**
34589      * @cfg {Boolean} insertProxy True to insert a placeholder proxy element
34590      * while dragging the panel, false to drag with no proxy (defaults to true).
34591      * Most Panels are not absolute positioned and therefore we need to reserve
34592      * this space.
34593      */
34594     insertProxy: true,
34595
34596     // private overrides
34597     setStatus: Ext.emptyFn,
34598     reset: Ext.emptyFn,
34599     update: Ext.emptyFn,
34600     stop: Ext.emptyFn,
34601     sync: Ext.emptyFn,
34602
34603     /**
34604      * Gets the proxy's element
34605      * @return {Element} The proxy's element
34606      */
34607     getEl: function(){
34608         return this.ghost.el;
34609     },
34610
34611     /**
34612      * Gets the proxy's ghost Panel
34613      * @return {Panel} The proxy's ghost Panel
34614      */
34615     getGhost: function(){
34616         return this.ghost;
34617     },
34618
34619     /**
34620      * Gets the proxy element. This is the element that represents where the
34621      * Panel was before we started the drag operation.
34622      * @return {Element} The proxy's element
34623      */
34624     getProxy: function(){
34625         return this.proxy;
34626     },
34627
34628     /**
34629      * Hides the proxy
34630      */
34631     hide : function(){
34632         if (this.ghost) {
34633             if (this.proxy) {
34634                 this.proxy.remove();
34635                 delete this.proxy;
34636             }
34637
34638             // Unghost the Panel, do not move the Panel to where the ghost was
34639             this.panel.unghost(null, false);
34640             delete this.ghost;
34641         }
34642     },
34643
34644     /**
34645      * Shows the proxy
34646      */
34647     show: function(){
34648         if (!this.ghost) {
34649             var panelSize = this.panel.getSize();
34650             this.panel.el.setVisibilityMode(Ext.core.Element.DISPLAY);
34651             this.ghost = this.panel.ghost();
34652             if (this.insertProxy) {
34653                 // bc Panels aren't absolute positioned we need to take up the space
34654                 // of where the panel previously was
34655                 this.proxy = this.panel.el.insertSibling({cls: Ext.baseCSSPrefix + 'panel-dd-spacer'});
34656                 this.proxy.setSize(panelSize);
34657             }
34658         }
34659     },
34660
34661     // private
34662     repair: function(xy, callback, scope) {
34663         this.hide();
34664         if (typeof callback == "function") {
34665             callback.call(scope || this);
34666         }
34667     },
34668
34669     /**
34670      * Moves the proxy to a different position in the DOM.  This is typically
34671      * called while dragging the Panel to keep the proxy sync'd to the Panel's
34672      * location.
34673      * @param {HTMLElement} parentNode The proxy's parent DOM node
34674      * @param {HTMLElement} before (optional) The sibling node before which the
34675      * proxy should be inserted (defaults to the parent's last child if not
34676      * specified)
34677      */
34678     moveProxy : function(parentNode, before){
34679         if (this.proxy) {
34680             parentNode.insertBefore(this.proxy.dom, before);
34681         }
34682     }
34683 });
34684 /**
34685  * @class Ext.layout.component.AbstractDock
34686  * @extends Ext.layout.component.Component
34687  * @private
34688  * This ComponentLayout handles docking for Panels. It takes care of panels that are
34689  * part of a ContainerLayout that sets this Panel's size and Panels that are part of
34690  * an AutoContainerLayout in which this panel get his height based of the CSS or
34691  * or its content.
34692  */
34693
34694 Ext.define('Ext.layout.component.AbstractDock', {
34695
34696     /* Begin Definitions */
34697
34698     extend: 'Ext.layout.component.Component',
34699
34700     /* End Definitions */
34701
34702     type: 'dock',
34703
34704     /**
34705      * @private
34706      * @property autoSizing
34707      * @type boolean
34708      * This flag is set to indicate this layout may have an autoHeight/autoWidth.
34709      */
34710     autoSizing: true,
34711
34712     beforeLayout: function() {
34713         var returnValue = this.callParent(arguments);
34714         if (returnValue !== false && (!this.initializedBorders || this.childrenChanged) && (!this.owner.border || this.owner.manageBodyBorders)) {
34715             this.handleItemBorders();
34716             this.initializedBorders = true;
34717         }
34718         return returnValue;
34719     },
34720     
34721     handleItemBorders: function() {
34722         var owner = this.owner,
34723             body = owner.body,
34724             docked = this.getLayoutItems(),
34725             borders = {
34726                 top: [],
34727                 right: [],
34728                 bottom: [],
34729                 left: []
34730             },
34731             oldBorders = this.borders,
34732             opposites = {
34733                 top: 'bottom',
34734                 right: 'left',
34735                 bottom: 'top',
34736                 left: 'right'
34737             },
34738             i, ln, item, dock, side;
34739
34740         for (i = 0, ln = docked.length; i < ln; i++) {
34741             item = docked[i];
34742             dock = item.dock;
34743             
34744             if (item.ignoreBorderManagement) {
34745                 continue;
34746             }
34747             
34748             if (!borders[dock].satisfied) {
34749                 borders[dock].push(item);
34750                 borders[dock].satisfied = true;
34751             }
34752             
34753             if (!borders.top.satisfied && opposites[dock] !== 'top') {
34754                 borders.top.push(item);
34755             }
34756             if (!borders.right.satisfied && opposites[dock] !== 'right') {
34757                 borders.right.push(item);
34758             }            
34759             if (!borders.bottom.satisfied && opposites[dock] !== 'bottom') {
34760                 borders.bottom.push(item);
34761             }            
34762             if (!borders.left.satisfied && opposites[dock] !== 'left') {
34763                 borders.left.push(item);
34764             }
34765         }
34766
34767         if (oldBorders) {
34768             for (side in oldBorders) {
34769                 if (oldBorders.hasOwnProperty(side)) {
34770                     ln = oldBorders[side].length;
34771                     if (!owner.manageBodyBorders) {
34772                         for (i = 0; i < ln; i++) {
34773                             oldBorders[side][i].removeCls(Ext.baseCSSPrefix + 'docked-noborder-' + side);
34774                         }
34775                         if (!oldBorders[side].satisfied && !owner.bodyBorder) {
34776                             body.removeCls(Ext.baseCSSPrefix + 'docked-noborder-' + side);                   
34777                         }                    
34778                     }
34779                     else if (oldBorders[side].satisfied) {
34780                         body.setStyle('border-' + side + '-width', '');
34781                     }
34782                 }
34783             }
34784         }
34785                 
34786         for (side in borders) {
34787             if (borders.hasOwnProperty(side)) {
34788                 ln = borders[side].length;
34789                 if (!owner.manageBodyBorders) {
34790                     for (i = 0; i < ln; i++) {
34791                         borders[side][i].addCls(Ext.baseCSSPrefix + 'docked-noborder-' + side);
34792                     }
34793                     if ((!borders[side].satisfied && !owner.bodyBorder) || owner.bodyBorder === false) {
34794                         body.addCls(Ext.baseCSSPrefix + 'docked-noborder-' + side);                   
34795                     }                    
34796                 }
34797                 else if (borders[side].satisfied) {
34798                     body.setStyle('border-' + side + '-width', '1px');
34799                 }
34800             }
34801         }
34802         
34803         this.borders = borders;
34804     },
34805     
34806     /**
34807      * @protected
34808      * @param {Ext.Component} owner The Panel that owns this DockLayout
34809      * @param {Ext.core.Element} target The target in which we are going to render the docked items
34810      * @param {Array} args The arguments passed to the ComponentLayout.layout method
34811      */
34812     onLayout: function(width, height) {
34813         var me = this,
34814             owner = me.owner,
34815             body = owner.body,
34816             layout = owner.layout,
34817             target = me.getTarget(),
34818             autoWidth = false,
34819             autoHeight = false,
34820             padding, border, frameSize;
34821
34822         // We start of by resetting all the layouts info
34823         var info = me.info = {
34824             boxes: [],
34825             size: {
34826                 width: width,
34827                 height: height
34828             },
34829             bodyBox: {}
34830         };
34831
34832         Ext.applyIf(info, me.getTargetInfo());
34833
34834         // We need to bind to the ownerCt whenever we do not have a user set height or width.
34835         if (owner && owner.ownerCt && owner.ownerCt.layout && owner.ownerCt.layout.isLayout) {
34836             if (!Ext.isNumber(owner.height) || !Ext.isNumber(owner.width)) {
34837                 owner.ownerCt.layout.bindToOwnerCtComponent = true;
34838             }
34839             else {
34840                 owner.ownerCt.layout.bindToOwnerCtComponent = false;
34841             }
34842         }
34843
34844         // Determine if we have an autoHeight or autoWidth.
34845         if (height === undefined || height === null || width === undefined || width === null) {
34846             padding = info.padding;
34847             border = info.border;
34848             frameSize = me.frameSize;
34849
34850             // Auto-everything, clear out any style height/width and read from css
34851             if ((height === undefined || height === null) && (width === undefined || width === null)) {
34852                 autoHeight = true;
34853                 autoWidth = true;
34854                 me.setTargetSize(null);
34855                 me.setBodyBox({width: null, height: null});
34856             }
34857             // Auto-height
34858             else if (height === undefined || height === null) {
34859                 autoHeight = true;
34860                 // Clear any sizing that we already set in a previous layout
34861                 me.setTargetSize(width);
34862                 me.setBodyBox({width: width - padding.left - border.left - padding.right - border.right - frameSize.left - frameSize.right, height: null});
34863             // Auto-width
34864             }
34865             else {
34866                 autoWidth = true;
34867                 // Clear any sizing that we already set in a previous layout
34868                 me.setTargetSize(null, height);
34869                 me.setBodyBox({width: null, height: height - padding.top - padding.bottom - border.top - border.bottom - frameSize.top - frameSize.bottom});
34870             }
34871
34872             // Run the container
34873             if (layout && layout.isLayout) {
34874                 // Auto-Sized so have the container layout notify the component layout.
34875                 layout.bindToOwnerCtComponent = true;
34876                 layout.layout();
34877
34878                 // If this is an autosized container layout, then we must compensate for a
34879                 // body that is being autosized.  We do not want to adjust the body's size
34880                 // to accommodate the dock items, but rather we will want to adjust the
34881                 // target's size.
34882                 //
34883                 // This is necessary because, particularly in a Box layout, all child items
34884                 // are set with absolute dimensions that are not flexible to the size of its
34885                 // innerCt/target.  So once they are laid out, they are sized for good. By
34886                 // shrinking the body box to accommodate dock items, we're merely cutting off
34887                 // parts of the body.  Not good.  Instead, the target's size should expand
34888                 // to fit the dock items in.  This is valid because the target container is
34889                 // suppose to be autosized to fit everything accordingly.
34890                 info.autoSizedCtLayout = layout.autoSize === true;
34891             }
34892
34893             // The dockItems method will add all the top and bottom docked items height
34894             // to the info.panelSize height. That's why we have to call setSize after
34895             // we dock all the items to actually set the panel's width and height.
34896             // We have to do this because the panel body and docked items will be position
34897             // absolute which doesn't stretch the panel.
34898             me.dockItems(autoWidth, autoHeight);
34899             me.setTargetSize(info.size.width, info.size.height);
34900         }
34901         else {
34902             me.setTargetSize(width, height);
34903             me.dockItems();
34904         }
34905         me.callParent(arguments);
34906     },
34907
34908     /**
34909      * @protected
34910      * This method will first update all the information about the docked items,
34911      * body dimensions and position, the panel's total size. It will then
34912      * set all these values on the docked items and panel body.
34913      * @param {Array} items Array containing all the docked items
34914      * @param {Boolean} autoBoxes Set this to true if the Panel is part of an
34915      * AutoContainerLayout
34916      */
34917     dockItems : function(autoWidth, autoHeight) {
34918         this.calculateDockBoxes(autoWidth, autoHeight);
34919
34920         // Both calculateAutoBoxes and calculateSizedBoxes are changing the
34921         // information about the body, panel size, and boxes for docked items
34922         // inside a property called info.
34923         var info = this.info,
34924             boxes = info.boxes,
34925             ln = boxes.length,
34926             dock, i;
34927
34928         // We are going to loop over all the boxes that were calculated
34929         // and set the position of each item the box belongs to.
34930         for (i = 0; i < ln; i++) {
34931             dock = boxes[i];
34932             dock.item.setPosition(dock.x, dock.y);
34933             if ((autoWidth || autoHeight) && dock.layout && dock.layout.isLayout) {
34934                 // Auto-Sized so have the container layout notify the component layout.
34935                 dock.layout.bindToOwnerCtComponent = true;
34936             }
34937         }
34938
34939         // Don't adjust body width/height if the target is using an auto container layout.
34940         // But, we do want to adjust the body size if the container layout is auto sized.
34941         if (!info.autoSizedCtLayout) {
34942             if (autoWidth) {
34943                 info.bodyBox.width = null;
34944             }
34945             if (autoHeight) {
34946                 info.bodyBox.height = null;
34947             }
34948         }
34949
34950         // If the bodyBox has been adjusted because of the docked items
34951         // we will update the dimensions and position of the panel's body.
34952         this.setBodyBox(info.bodyBox);
34953     },
34954
34955     /**
34956      * @protected
34957      * This method will set up some initial information about the panel size and bodybox
34958      * and then loop over all the items you pass it to take care of stretching, aligning,
34959      * dock position and all calculations involved with adjusting the body box.
34960      * @param {Array} items Array containing all the docked items we have to layout
34961      */
34962     calculateDockBoxes : function(autoWidth, autoHeight) {
34963         // We want to use the Panel's el width, and the Panel's body height as the initial
34964         // size we are going to use in calculateDockBoxes. We also want to account for
34965         // the border of the panel.
34966         var me = this,
34967             target = me.getTarget(),
34968             items = me.getLayoutItems(),
34969             owner = me.owner,
34970             bodyEl = owner.body,
34971             info = me.info,
34972             size = info.size,
34973             ln = items.length,
34974             padding = info.padding,
34975             border = info.border,
34976             frameSize = me.frameSize,
34977             item, i, box, rect;
34978
34979         // If this Panel is inside an AutoContainerLayout, we will base all the calculations
34980         // around the height of the body and the width of the panel.
34981         if (autoHeight) {
34982             size.height = bodyEl.getHeight() + padding.top + border.top + padding.bottom + border.bottom + frameSize.top + frameSize.bottom;
34983         }
34984         else {
34985             size.height = target.getHeight();
34986         }
34987         if (autoWidth) {
34988             size.width = bodyEl.getWidth() + padding.left + border.left + padding.right + border.right + frameSize.left + frameSize.right;
34989         }
34990         else {
34991             size.width = target.getWidth();
34992         }
34993
34994         info.bodyBox = {
34995             x: padding.left + frameSize.left,
34996             y: padding.top + frameSize.top,
34997             width: size.width - padding.left - border.left - padding.right - border.right - frameSize.left - frameSize.right,
34998             height: size.height - border.top - padding.top - border.bottom - padding.bottom - frameSize.top - frameSize.bottom
34999         };
35000
35001         // Loop over all the docked items
35002         for (i = 0; i < ln; i++) {
35003             item = items[i];
35004             // The initBox method will take care of stretching and alignment
35005             // In some cases it will also layout the dock items to be able to
35006             // get a width or height measurement
35007             box = me.initBox(item);
35008
35009             if (autoHeight === true) {
35010                 box = me.adjustAutoBox(box, i);
35011             }
35012             else {
35013                 box = me.adjustSizedBox(box, i);
35014             }
35015
35016             // Save our box. This allows us to loop over all docked items and do all
35017             // calculations first. Then in one loop we will actually size and position
35018             // all the docked items that have changed.
35019             info.boxes.push(box);
35020         }
35021     },
35022
35023     /**
35024      * @protected
35025      * This method will adjust the position of the docked item and adjust the body box
35026      * accordingly.
35027      * @param {Object} box The box containing information about the width and height
35028      * of this docked item
35029      * @param {Number} index The index position of this docked item
35030      * @return {Object} The adjusted box
35031      */
35032     adjustSizedBox : function(box, index) {
35033         var bodyBox = this.info.bodyBox,
35034             frameSize = this.frameSize,
35035             info = this.info,
35036             padding = info.padding,
35037             pos = box.type,
35038             border = info.border;
35039
35040         switch (pos) {
35041             case 'top':
35042                 box.y = bodyBox.y;
35043                 break;
35044
35045             case 'left':
35046                 box.x = bodyBox.x;
35047                 break;
35048
35049             case 'bottom':
35050                 box.y = (bodyBox.y + bodyBox.height) - box.height;
35051                 break;
35052
35053             case 'right':
35054                 box.x = (bodyBox.x + bodyBox.width) - box.width;
35055                 break;
35056         }
35057
35058         if (box.ignoreFrame) {
35059             if (pos == 'bottom') {
35060                 box.y += (frameSize.bottom + padding.bottom + border.bottom);
35061             }
35062             else {
35063                 box.y -= (frameSize.top + padding.top + border.top);
35064             }
35065             if (pos == 'right') {
35066                 box.x += (frameSize.right + padding.right + border.right);
35067             }
35068             else {
35069                 box.x -= (frameSize.left + padding.left + border.left);
35070             }
35071         }
35072
35073         // If this is not an overlaying docked item, we have to adjust the body box
35074         if (!box.overlay) {
35075             switch (pos) {
35076                 case 'top':
35077                     bodyBox.y += box.height;
35078                     bodyBox.height -= box.height;
35079                     break;
35080
35081                 case 'left':
35082                     bodyBox.x += box.width;
35083                     bodyBox.width -= box.width;
35084                     break;
35085
35086                 case 'bottom':
35087                     bodyBox.height -= box.height;
35088                     break;
35089
35090                 case 'right':
35091                     bodyBox.width -= box.width;
35092                     break;
35093             }
35094         }
35095         return box;
35096     },
35097
35098     /**
35099      * @protected
35100      * This method will adjust the position of the docked item inside an AutoContainerLayout
35101      * and adjust the body box accordingly.
35102      * @param {Object} box The box containing information about the width and height
35103      * of this docked item
35104      * @param {Number} index The index position of this docked item
35105      * @return {Object} The adjusted box
35106      */
35107     adjustAutoBox : function (box, index) {
35108         var info = this.info,
35109             bodyBox = info.bodyBox,
35110             size = info.size,
35111             boxes = info.boxes,
35112             boxesLn = boxes.length,
35113             pos = box.type,
35114             frameSize = this.frameSize,
35115             padding = info.padding,
35116             border = info.border,
35117             autoSizedCtLayout = info.autoSizedCtLayout,
35118             ln = (boxesLn < index) ? boxesLn : index,
35119             i, adjustBox;
35120
35121         if (pos == 'top' || pos == 'bottom') {
35122             // This can affect the previously set left and right and bottom docked items
35123             for (i = 0; i < ln; i++) {
35124                 adjustBox = boxes[i];
35125                 if (adjustBox.stretched && adjustBox.type == 'left' || adjustBox.type == 'right') {
35126                     adjustBox.height += box.height;
35127                 }
35128                 else if (adjustBox.type == 'bottom') {
35129                     adjustBox.y += box.height;
35130                 }
35131             }
35132         }
35133
35134         switch (pos) {
35135             case 'top':
35136                 box.y = bodyBox.y;
35137                 if (!box.overlay) {
35138                     bodyBox.y += box.height;
35139                 }
35140                 size.height += box.height;
35141                 break;
35142
35143             case 'bottom':
35144                 box.y = (bodyBox.y + bodyBox.height);
35145                 size.height += box.height;
35146                 break;
35147
35148             case 'left':
35149                 box.x = bodyBox.x;
35150                 if (!box.overlay) {
35151                     bodyBox.x += box.width;
35152                     if (autoSizedCtLayout) {
35153                         size.width += box.width;
35154                     } else {
35155                         bodyBox.width -= box.width;
35156                     }
35157                 }
35158                 break;
35159
35160             case 'right':
35161                 if (!box.overlay) {
35162                     if (autoSizedCtLayout) {
35163                         size.width += box.width;
35164                     } else {
35165                         bodyBox.width -= box.width;
35166                     }
35167                 }
35168                 box.x = (bodyBox.x + bodyBox.width);
35169                 break;
35170         }
35171
35172         if (box.ignoreFrame) {
35173             if (pos == 'bottom') {
35174                 box.y += (frameSize.bottom + padding.bottom + border.bottom);
35175             }
35176             else {
35177                 box.y -= (frameSize.top + padding.top + border.top);
35178             }
35179             if (pos == 'right') {
35180                 box.x += (frameSize.right + padding.right + border.right);
35181             }
35182             else {
35183                 box.x -= (frameSize.left + padding.left + border.left);
35184             }
35185         }
35186         return box;
35187     },
35188
35189     /**
35190      * @protected
35191      * This method will create a box object, with a reference to the item, the type of dock
35192      * (top, left, bottom, right). It will also take care of stretching and aligning of the
35193      * docked items.
35194      * @param {Ext.Component} item The docked item we want to initialize the box for
35195      * @return {Object} The initial box containing width and height and other useful information
35196      */
35197     initBox : function(item) {
35198         var me = this,
35199             bodyBox = me.info.bodyBox,
35200             horizontal = (item.dock == 'top' || item.dock == 'bottom'),
35201             owner = me.owner,
35202             frameSize = me.frameSize,
35203             info = me.info,
35204             padding = info.padding,
35205             border = info.border,
35206             box = {
35207                 item: item,
35208                 overlay: item.overlay,
35209                 type: item.dock,
35210                 offsets: Ext.core.Element.parseBox(item.offsets || {}),
35211                 ignoreFrame: item.ignoreParentFrame
35212             };
35213         // First we are going to take care of stretch and align properties for all four dock scenarios.
35214         if (item.stretch !== false) {
35215             box.stretched = true;
35216             if (horizontal) {
35217                 box.x = bodyBox.x + box.offsets.left;
35218                 box.width = bodyBox.width - (box.offsets.left + box.offsets.right);
35219                 if (box.ignoreFrame) {
35220                     box.width += (frameSize.left + frameSize.right + border.left + border.right + padding.left + padding.right);
35221                 }
35222                 item.setCalculatedSize(box.width - item.el.getMargin('lr'), undefined, owner);
35223             }
35224             else {
35225                 box.y = bodyBox.y + box.offsets.top;
35226                 box.height = bodyBox.height - (box.offsets.bottom + box.offsets.top);
35227                 if (box.ignoreFrame) {
35228                     box.height += (frameSize.top + frameSize.bottom + border.top + border.bottom + padding.top + padding.bottom);
35229                 }
35230                 item.setCalculatedSize(undefined, box.height - item.el.getMargin('tb'), owner);
35231
35232                 // At this point IE will report the left/right-docked toolbar as having a width equal to the
35233                 // container's full width. Forcing a repaint kicks it into shape so it reports the correct width.
35234                 if (!Ext.supports.ComputedStyle) {
35235                     item.el.repaint();
35236                 }
35237             }
35238         }
35239         else {
35240             item.doComponentLayout();
35241             box.width = item.getWidth() - (box.offsets.left + box.offsets.right);
35242             box.height = item.getHeight() - (box.offsets.bottom + box.offsets.top);
35243             box.y += box.offsets.top;
35244             if (horizontal) {
35245                 box.x = (item.align == 'right') ? bodyBox.width - box.width : bodyBox.x;
35246                 box.x += box.offsets.left;
35247             }
35248         }
35249
35250         // If we haven't calculated the width or height of the docked item yet
35251         // do so, since we need this for our upcoming calculations
35252         if (box.width == undefined) {
35253             box.width = item.getWidth() + item.el.getMargin('lr');
35254         }
35255         if (box.height == undefined) {
35256             box.height = item.getHeight() + item.el.getMargin('tb');
35257         }
35258
35259         return box;
35260     },
35261
35262     /**
35263      * @protected
35264      * Returns an array containing all the <b>visible</b> docked items inside this layout's owner Panel
35265      * @return {Array} An array containing all the <b>visible</b> docked items of the Panel
35266      */
35267     getLayoutItems : function() {
35268         var it = this.owner.getDockedItems(),
35269             ln = it.length,
35270             i = 0,
35271             result = [];
35272         for (; i < ln; i++) {
35273             if (it[i].isVisible(true)) {
35274                 result.push(it[i]);
35275             }
35276         }
35277         return result;
35278     },
35279
35280     /**
35281      * @protected
35282      * Render the top and left docked items before any existing DOM nodes in our render target,
35283      * and then render the right and bottom docked items after. This is important, for such things
35284      * as tab stops and ARIA readers, that the DOM nodes are in a meaningful order.
35285      * Our collection of docked items will already be ordered via Panel.getDockedItems().
35286      */
35287     renderItems: function(items, target) {
35288         var cns = target.dom.childNodes,
35289             cnsLn = cns.length,
35290             ln = items.length,
35291             domLn = 0,
35292             i, j, cn, item;
35293
35294         // Calculate the number of DOM nodes in our target that are not our docked items
35295         for (i = 0; i < cnsLn; i++) {
35296             cn = Ext.get(cns[i]);
35297             for (j = 0; j < ln; j++) {
35298                 item = items[j];
35299                 if (item.rendered && (cn.id == item.el.id || cn.down('#' + item.el.id))) {
35300                     break;
35301                 }
35302             }
35303
35304             if (j === ln) {
35305                 domLn++;
35306             }
35307         }
35308
35309         // Now we go through our docked items and render/move them
35310         for (i = 0, j = 0; i < ln; i++, j++) {
35311             item = items[i];
35312
35313             // If we're now at the right/bottom docked item, we jump ahead in our
35314             // DOM position, just past the existing DOM nodes.
35315             //
35316             // TODO: This is affected if users provide custom weight values to their
35317             // docked items, which puts it out of (t,l,r,b) order. Avoiding a second
35318             // sort operation here, for now, in the name of performance. getDockedItems()
35319             // needs the sort operation not just for this layout-time rendering, but
35320             // also for getRefItems() to return a logical ordering (FocusManager, CQ, et al).
35321             if (i === j && (item.dock === 'right' || item.dock === 'bottom')) {
35322                 j += domLn;
35323             }
35324
35325             // Same logic as Layout.renderItems()
35326             if (item && !item.rendered) {
35327                 this.renderItem(item, target, j);
35328             }
35329             else if (!this.isValidParent(item, target, j)) {
35330                 this.moveItem(item, target, j);
35331             }
35332         }
35333     },
35334
35335     /**
35336      * @protected
35337      * This function will be called by the dockItems method. Since the body is positioned absolute,
35338      * we need to give it dimensions and a position so that it is in the middle surrounded by
35339      * docked items
35340      * @param {Object} box An object containing new x, y, width and height values for the
35341      * Panel's body
35342      */
35343     setBodyBox : function(box) {
35344         var me = this,
35345             owner = me.owner,
35346             body = owner.body,
35347             info = me.info,
35348             bodyMargin = info.bodyMargin,
35349             padding = info.padding,
35350             border = info.border,
35351             frameSize = me.frameSize;
35352         
35353         // Panel collapse effectively hides the Panel's body, so this is a no-op.
35354         if (owner.collapsed) {
35355             return;
35356         }
35357         
35358         if (Ext.isNumber(box.width)) {
35359             box.width -= bodyMargin.left + bodyMargin.right;
35360         }
35361         
35362         if (Ext.isNumber(box.height)) {
35363             box.height -= bodyMargin.top + bodyMargin.bottom;
35364         }
35365         
35366         me.setElementSize(body, box.width, box.height);
35367         if (Ext.isNumber(box.x)) {
35368             body.setLeft(box.x - padding.left - frameSize.left);
35369         }
35370         if (Ext.isNumber(box.y)) {
35371             body.setTop(box.y - padding.top - frameSize.top);
35372         }
35373     },
35374
35375     /**
35376      * @protected
35377      * We are overriding the Ext.layout.Layout configureItem method to also add a class that
35378      * indicates the position of the docked item. We use the itemCls (x-docked) as a prefix.
35379      * An example of a class added to a dock: right item is x-docked-right
35380      * @param {Ext.Component} item The item we are configuring
35381      */
35382     configureItem : function(item, pos) {
35383         this.callParent(arguments);
35384         
35385         item.addCls(Ext.baseCSSPrefix + 'docked');
35386         item.addClsWithUI('docked-' + item.dock);
35387     },
35388
35389     afterRemove : function(item) {
35390         this.callParent(arguments);
35391         if (this.itemCls) {
35392             item.el.removeCls(this.itemCls + '-' + item.dock);
35393         }
35394         var dom = item.el.dom;
35395
35396         if (!item.destroying && dom) {
35397             dom.parentNode.removeChild(dom);
35398         }
35399         this.childrenChanged = true;
35400     }
35401 });
35402 /**
35403  * @class Ext.app.EventBus
35404  * @private
35405  *
35406  * Class documentation for the MVC classes will be present before 4.0 final, in the mean time please refer to the MVC
35407  * guide
35408  */
35409 Ext.define('Ext.app.EventBus', {
35410     requires: [
35411         'Ext.util.Event'
35412     ],
35413     mixins: {
35414         observable: 'Ext.util.Observable'
35415     },
35416     
35417     constructor: function() {
35418         this.mixins.observable.constructor.call(this);
35419         
35420         this.bus = {};
35421         
35422         var me = this;
35423         Ext.override(Ext.Component, {
35424             fireEvent: function(ev) {
35425                 if (Ext.util.Observable.prototype.fireEvent.apply(this, arguments) !== false) {
35426                     return me.dispatch.call(me, ev, this, arguments);
35427                 }
35428                 return false;
35429             }
35430         });
35431     },
35432
35433     dispatch: function(ev, target, args) {
35434         var bus = this.bus,
35435             selectors = bus[ev],
35436             selector, controllers, id, events, event, i, ln;
35437         
35438         if (selectors) {
35439             // Loop over all the selectors that are bound to this event
35440             for (selector in selectors) {
35441                 // Check if the target matches the selector
35442                 if (target.is(selector)) {
35443                     // Loop over all the controllers that are bound to this selector   
35444                     controllers = selectors[selector];
35445                     for (id in controllers) {
35446                         // Loop over all the events that are bound to this selector on this controller
35447                         events = controllers[id];
35448                         for (i = 0, ln = events.length; i < ln; i++) {
35449                             event = events[i];
35450                             // Fire the event!
35451                             return event.fire.apply(event, Array.prototype.slice.call(args, 1));
35452                         }
35453                     }
35454                 }
35455             }
35456         }
35457     },
35458     
35459     control: function(selectors, listeners, controller) {
35460         var bus = this.bus,
35461             selector, fn;
35462         
35463         if (Ext.isString(selectors)) {
35464             selector = selectors;
35465             selectors = {};
35466             selectors[selector] = listeners;
35467             this.control(selectors, null, controller);
35468             return;
35469         }
35470     
35471         Ext.Object.each(selectors, function(selector, listeners) {
35472             Ext.Object.each(listeners, function(ev, listener) {
35473                 var options = {},   
35474                     scope = controller,
35475                     event = Ext.create('Ext.util.Event', controller, ev);
35476                 
35477                 // Normalize the listener                
35478                 if (Ext.isObject(listener)) {
35479                     options = listener;
35480                     listener = options.fn;
35481                     scope = options.scope || controller;
35482                     delete options.fn;
35483                     delete options.scope;
35484                 }
35485                 
35486                 event.addListener(listener, scope, options);
35487
35488                 // Create the bus tree if it is not there yet
35489                 bus[ev] = bus[ev] || {};
35490                 bus[ev][selector] = bus[ev][selector] || {};
35491                 bus[ev][selector][controller.id] = bus[ev][selector][controller.id] || [];            
35492                 
35493                 // Push our listener in our bus
35494                 bus[ev][selector][controller.id].push(event);
35495             });
35496         });
35497     }
35498 });
35499 /**
35500  * @class Ext.data.Types
35501  * <p>This is s static class containing the system-supplied data types which may be given to a {@link Ext.data.Field Field}.<p/>
35502  * <p>The properties in this class are used as type indicators in the {@link Ext.data.Field Field} class, so to
35503  * test whether a Field is of a certain type, compare the {@link Ext.data.Field#type type} property against properties
35504  * of this class.</p>
35505  * <p>Developers may add their own application-specific data types to this class. Definition names must be UPPERCASE.
35506  * each type definition must contain three properties:</p>
35507  * <div class="mdetail-params"><ul>
35508  * <li><code>convert</code> : <i>Function</i><div class="sub-desc">A function to convert raw data values from a data block into the data
35509  * to be stored in the Field. The function is passed the collowing parameters:
35510  * <div class="mdetail-params"><ul>
35511  * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
35512  * the configured <tt>{@link Ext.data.Field#defaultValue defaultValue}</tt>.</div></li>
35513  * <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
35514  * Depending on the Reader type, this could be an Array ({@link Ext.data.reader.Array ArrayReader}), an object
35515  * ({@link Ext.data.reader.Json JsonReader}), or an XML element.</div></li>
35516  * </ul></div></div></li>
35517  * <li><code>sortType</code> : <i>Function</i> <div class="sub-desc">A function to convert the stored data into comparable form, as defined by {@link Ext.data.SortTypes}.</div></li>
35518  * <li><code>type</code> : <i>String</i> <div class="sub-desc">A textual data type name.</div></li>
35519  * </ul></div>
35520  * <p>For example, to create a VELatLong field (See the Microsoft Bing Mapping API) containing the latitude/longitude value of a datapoint on a map from a JsonReader data block
35521  * which contained the properties <code>lat</code> and <code>long</code>, you would define a new data type like this:</p>
35522  *<pre><code>
35523 // Add a new Field data type which stores a VELatLong object in the Record.
35524 Ext.data.Types.VELATLONG = {
35525     convert: function(v, data) {
35526         return new VELatLong(data.lat, data.long);
35527     },
35528     sortType: function(v) {
35529         return v.Latitude;  // When sorting, order by latitude
35530     },
35531     type: 'VELatLong'
35532 };
35533 </code></pre>
35534  * <p>Then, when declaring a Model, use <pre><code>
35535 var types = Ext.data.Types; // allow shorthand type access
35536 Ext.define('Unit',
35537     extend: 'Ext.data.Model', 
35538     fields: [
35539         { name: 'unitName', mapping: 'UnitName' },
35540         { name: 'curSpeed', mapping: 'CurSpeed', type: types.INT },
35541         { name: 'latitude', mapping: 'lat', type: types.FLOAT },
35542         { name: 'latitude', mapping: 'lat', type: types.FLOAT },
35543         { name: 'position', type: types.VELATLONG }
35544     ]
35545 });
35546 </code></pre>
35547  * @singleton
35548  */
35549 Ext.define('Ext.data.Types', {
35550     singleton: true,
35551     requires: ['Ext.data.SortTypes']
35552 }, function() {
35553     var st = Ext.data.SortTypes;
35554     
35555     Ext.apply(Ext.data.Types, {
35556         /**
35557          * @type Regexp
35558          * @property stripRe
35559          * A regular expression for stripping non-numeric characters from a numeric value. Defaults to <tt>/[\$,%]/g</tt>.
35560          * This should be overridden for localization.
35561          */
35562         stripRe: /[\$,%]/g,
35563         
35564         /**
35565          * @type Object.
35566          * @property AUTO
35567          * This data type means that no conversion is applied to the raw data before it is placed into a Record.
35568          */
35569         AUTO: {
35570             convert: function(v) {
35571                 return v;
35572             },
35573             sortType: st.none,
35574             type: 'auto'
35575         },
35576
35577         /**
35578          * @type Object.
35579          * @property STRING
35580          * This data type means that the raw data is converted into a String before it is placed into a Record.
35581          */
35582         STRING: {
35583             convert: function(v) {
35584                 var defaultValue = this.useNull ? null : '';
35585                 return (v === undefined || v === null) ? defaultValue : String(v);
35586             },
35587             sortType: st.asUCString,
35588             type: 'string'
35589         },
35590
35591         /**
35592          * @type Object.
35593          * @property INT
35594          * This data type means that the raw data is converted into an integer before it is placed into a Record.
35595          * <p>The synonym <code>INTEGER</code> is equivalent.</p>
35596          */
35597         INT: {
35598             convert: function(v) {
35599                 return v !== undefined && v !== null && v !== '' ?
35600                     parseInt(String(v).replace(Ext.data.Types.stripRe, ''), 10) : (this.useNull ? null : 0);
35601             },
35602             sortType: st.none,
35603             type: 'int'
35604         },
35605         
35606         /**
35607          * @type Object.
35608          * @property FLOAT
35609          * This data type means that the raw data is converted into a number before it is placed into a Record.
35610          * <p>The synonym <code>NUMBER</code> is equivalent.</p>
35611          */
35612         FLOAT: {
35613             convert: function(v) {
35614                 return v !== undefined && v !== null && v !== '' ?
35615                     parseFloat(String(v).replace(Ext.data.Types.stripRe, ''), 10) : (this.useNull ? null : 0);
35616             },
35617             sortType: st.none,
35618             type: 'float'
35619         },
35620         
35621         /**
35622          * @type Object.
35623          * @property BOOL
35624          * <p>This data type means that the raw data is converted into a boolean before it is placed into
35625          * a Record. The string "true" and the number 1 are converted to boolean <code>true</code>.</p>
35626          * <p>The synonym <code>BOOLEAN</code> is equivalent.</p>
35627          */
35628         BOOL: {
35629             convert: function(v) {
35630                 if (this.useNull && v === undefined || v === null || v === '') {
35631                     return null;
35632                 }
35633                 return v === true || v === 'true' || v == 1;
35634             },
35635             sortType: st.none,
35636             type: 'bool'
35637         },
35638         
35639         /**
35640          * @type Object.
35641          * @property DATE
35642          * This data type means that the raw data is converted into a Date before it is placed into a Record.
35643          * The date format is specified in the constructor of the {@link Ext.data.Field} to which this type is
35644          * being applied.
35645          */
35646         DATE: {
35647             convert: function(v) {
35648                 var df = this.dateFormat;
35649                 if (!v) {
35650                     return null;
35651                 }
35652                 if (Ext.isDate(v)) {
35653                     return v;
35654                 }
35655                 if (df) {
35656                     if (df == 'timestamp') {
35657                         return new Date(v*1000);
35658                     }
35659                     if (df == 'time') {
35660                         return new Date(parseInt(v, 10));
35661                     }
35662                     return Ext.Date.parse(v, df);
35663                 }
35664                 
35665                 var parsed = Date.parse(v);
35666                 return parsed ? new Date(parsed) : null;
35667             },
35668             sortType: st.asDate,
35669             type: 'date'
35670         }
35671     });
35672     
35673     Ext.apply(Ext.data.Types, {
35674         /**
35675          * @type Object.
35676          * @property BOOLEAN
35677          * <p>This data type means that the raw data is converted into a boolean before it is placed into
35678          * a Record. The string "true" and the number 1 are converted to boolean <code>true</code>.</p>
35679          * <p>The synonym <code>BOOL</code> is equivalent.</p>
35680          */
35681         BOOLEAN: this.BOOL,
35682         
35683         /**
35684          * @type Object.
35685          * @property INTEGER
35686          * This data type means that the raw data is converted into an integer before it is placed into a Record.
35687          * <p>The synonym <code>INT</code> is equivalent.</p>
35688          */
35689         INTEGER: this.INT,
35690         
35691         /**
35692          * @type Object.
35693          * @property NUMBER
35694          * This data type means that the raw data is converted into a number before it is placed into a Record.
35695          * <p>The synonym <code>FLOAT</code> is equivalent.</p>
35696          */
35697         NUMBER: this.FLOAT    
35698     });
35699 });
35700
35701 /**
35702  * @author Ed Spencer
35703  * @class Ext.data.Field
35704  * @extends Object
35705  * 
35706  * <p>Fields are used to define what a Model is. They aren't instantiated directly - instead, when we create a class 
35707  * that extends {@link Ext.data.Model}, it will automatically create a Field instance for each field configured in a 
35708  * {@link Ext.data.Model Model}. For example, we might set up a model like this:</p>
35709  * 
35710 <pre><code>
35711 Ext.define('User', {
35712     extend: 'Ext.data.Model',
35713     fields: [
35714         'name', 'email',
35715         {name: 'age', type: 'int'},
35716         {name: 'gender', type: 'string', defaultValue: 'Unknown'}
35717     ]
35718 });
35719 </code></pre>
35720  * 
35721  * <p>Four fields will have been created for the User Model - name, email, age and gender. Note that we specified a
35722  * couple of different formats here; if we only pass in the string name of the field (as with name and email), the
35723  * field is set up with the 'auto' type. It's as if we'd done this instead:</p>
35724  * 
35725 <pre><code>
35726 Ext.define('User', {
35727     extend: 'Ext.data.Model',
35728     fields: [
35729         {name: 'name', type: 'auto'},
35730         {name: 'email', type: 'auto'},
35731         {name: 'age', type: 'int'},
35732         {name: 'gender', type: 'string', defaultValue: 'Unknown'}
35733     ]
35734 });
35735 </code></pre>
35736  * 
35737  * <p><u>Types and conversion</u></p>
35738  * 
35739  * <p>The {@link #type} is important - it's used to automatically convert data passed to the field into the correct
35740  * format. In our example above, the name and email fields used the 'auto' type and will just accept anything that is
35741  * passed into them. The 'age' field had an 'int' type however, so if we passed 25.4 this would be rounded to 25.</p>
35742  * 
35743  * <p>Sometimes a simple type isn't enough, or we want to perform some processing when we load a Field's data. We can
35744  * do this using a {@link #convert} function. Here, we're going to create a new field based on another:</p>
35745  * 
35746 <code><pre>
35747 Ext.define('User', {
35748     extend: 'Ext.data.Model',
35749     fields: [
35750         'name', 'email',
35751         {name: 'age', type: 'int'},
35752         {name: 'gender', type: 'string', defaultValue: 'Unknown'},
35753
35754         {
35755             name: 'firstName',
35756             convert: function(value, record) {
35757                 var fullName  = record.get('name'),
35758                     splits    = fullName.split(" "),
35759                     firstName = splits[0];
35760
35761                 return firstName;
35762             }
35763         }
35764     ]
35765 });
35766 </code></pre>
35767  * 
35768  * <p>Now when we create a new User, the firstName is populated automatically based on the name:</p>
35769  * 
35770 <code><pre>
35771 var ed = Ext.ModelManager.create({name: 'Ed Spencer'}, 'User');
35772
35773 console.log(ed.get('firstName')); //logs 'Ed', based on our convert function
35774 </code></pre>
35775  * 
35776  * <p>In fact, if we log out all of the data inside ed, we'll see this:</p>
35777  * 
35778 <code><pre>
35779 console.log(ed.data);
35780
35781 //outputs this:
35782 {
35783     age: 0,
35784     email: "",
35785     firstName: "Ed",
35786     gender: "Unknown",
35787     name: "Ed Spencer"
35788 }
35789 </code></pre>
35790  * 
35791  * <p>The age field has been given a default of zero because we made it an int type. As an auto field, email has
35792  * defaulted to an empty string. When we registered the User model we set gender's {@link #defaultValue} to 'Unknown'
35793  * so we see that now. Let's correct that and satisfy ourselves that the types work as we expect:</p>
35794  * 
35795 <code><pre>
35796 ed.set('gender', 'Male');
35797 ed.get('gender'); //returns 'Male'
35798
35799 ed.set('age', 25.4);
35800 ed.get('age'); //returns 25 - we wanted an int, not a float, so no decimal places allowed
35801 </code></pre>
35802  * 
35803  */
35804 Ext.define('Ext.data.Field', {
35805     requires: ['Ext.data.Types', 'Ext.data.SortTypes'],
35806     alias: 'data.field',
35807     
35808     constructor : function(config) {
35809         if (Ext.isString(config)) {
35810             config = {name: config};
35811         }
35812         Ext.apply(this, config);
35813         
35814         var types = Ext.data.Types,
35815             st = this.sortType,
35816             t;
35817
35818         if (this.type) {
35819             if (Ext.isString(this.type)) {
35820                 this.type = types[this.type.toUpperCase()] || types.AUTO;
35821             }
35822         } else {
35823             this.type = types.AUTO;
35824         }
35825
35826         // named sortTypes are supported, here we look them up
35827         if (Ext.isString(st)) {
35828             this.sortType = Ext.data.SortTypes[st];
35829         } else if(Ext.isEmpty(st)) {
35830             this.sortType = this.type.sortType;
35831         }
35832
35833         if (!this.convert) {
35834             this.convert = this.type.convert;
35835         }
35836     },
35837     
35838     /**
35839      * @cfg {String} name
35840      * The name by which the field is referenced within the Model. This is referenced by, for example,
35841      * the <code>dataIndex</code> property in column definition objects passed to {@link Ext.grid.property.HeaderContainer}.
35842      * <p>Note: In the simplest case, if no properties other than <code>name</code> are required, a field
35843      * definition may consist of just a String for the field name.</p>
35844      */
35845     
35846     /**
35847      * @cfg {Mixed} type
35848      * (Optional) The data type for automatic conversion from received data to the <i>stored</i> value if <code>{@link Ext.data.Field#convert convert}</code>
35849      * has not been specified. This may be specified as a string value. Possible values are
35850      * <div class="mdetail-params"><ul>
35851      * <li>auto (Default, implies no conversion)</li>
35852      * <li>string</li>
35853      * <li>int</li>
35854      * <li>float</li>
35855      * <li>boolean</li>
35856      * <li>date</li></ul></div>
35857      * <p>This may also be specified by referencing a member of the {@link Ext.data.Types} class.</p>
35858      * <p>Developers may create their own application-specific data types by defining new members of the
35859      * {@link Ext.data.Types} class.</p>
35860      */
35861     
35862     /**
35863      * @cfg {Function} convert
35864      * (Optional) A function which converts the value provided by the Reader into an object that will be stored
35865      * in the Model. It is passed the following parameters:<div class="mdetail-params"><ul>
35866      * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
35867      * the configured <code>{@link Ext.data.Field#defaultValue defaultValue}</code>.</div></li>
35868      * <li><b>rec</b> : Ext.data.Model<div class="sub-desc">The data object containing the Model as read so far by the 
35869      * Reader. Note that the Model may not be fully populated at this point as the fields are read in the order that 
35870      * they are defined in your {@link #fields} array.</div></li>
35871      * </ul></div>
35872      * <pre><code>
35873 // example of convert function
35874 function fullName(v, record){
35875     return record.name.last + ', ' + record.name.first;
35876 }
35877
35878 function location(v, record){
35879     return !record.city ? '' : (record.city + ', ' + record.state);
35880 }
35881
35882 Ext.define('Dude', {
35883     extend: 'Ext.data.Model',
35884     fields: [
35885         {name: 'fullname',  convert: fullName},
35886         {name: 'firstname', mapping: 'name.first'},
35887         {name: 'lastname',  mapping: 'name.last'},
35888         {name: 'city', defaultValue: 'homeless'},
35889         'state',
35890         {name: 'location',  convert: location}
35891     ]
35892 });
35893
35894 // create the data store
35895 var store = new Ext.data.Store({
35896     reader: {
35897         type: 'json',
35898         model: 'Dude',
35899         idProperty: 'key',
35900         root: 'daRoot',
35901         totalProperty: 'total'
35902     }
35903 });
35904
35905 var myData = [
35906     { key: 1,
35907       name: { first: 'Fat',    last:  'Albert' }
35908       // notice no city, state provided in data object
35909     },
35910     { key: 2,
35911       name: { first: 'Barney', last:  'Rubble' },
35912       city: 'Bedrock', state: 'Stoneridge'
35913     },
35914     { key: 3,
35915       name: { first: 'Cliff',  last:  'Claven' },
35916       city: 'Boston',  state: 'MA'
35917     }
35918 ];
35919      * </code></pre>
35920      */
35921     /**
35922      * @cfg {String} dateFormat
35923      * <p>(Optional) Used when converting received data into a Date when the {@link #type} is specified as <code>"date"</code>.</p>
35924      * <p>A format string for the {@link Ext.Date#parse Ext.Date.parse} function, or "timestamp" if the
35925      * value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
35926      * javascript millisecond timestamp. See {@link Date}</p>
35927      */
35928     dateFormat: null,
35929     
35930     /**
35931      * @cfg {Boolean} useNull
35932      * <p>(Optional) Use when converting received data into a Number type (either int or float). If the value cannot be parsed,
35933      * null will be used if useNull is true, otherwise the value will be 0. Defaults to <tt>false</tt>
35934      */
35935     useNull: false,
35936     
35937     /**
35938      * @cfg {Mixed} defaultValue
35939      * (Optional) The default value used <b>when a Model is being created by a {@link Ext.data.reader.Reader Reader}</b>
35940      * when the item referenced by the <code>{@link Ext.data.Field#mapping mapping}</code> does not exist in the data
35941      * object (i.e. undefined). (defaults to "")
35942      */
35943     defaultValue: "",
35944     /**
35945      * @cfg {String/Number} mapping
35946      * <p>(Optional) A path expression for use by the {@link Ext.data.reader.Reader} implementation
35947      * that is creating the {@link Ext.data.Model Model} to extract the Field value from the data object.
35948      * If the path expression is the same as the field name, the mapping may be omitted.</p>
35949      * <p>The form of the mapping expression depends on the Reader being used.</p>
35950      * <div class="mdetail-params"><ul>
35951      * <li>{@link Ext.data.reader.Json}<div class="sub-desc">The mapping is a string containing the javascript
35952      * expression to reference the data from an element of the data item's {@link Ext.data.reader.Json#root root} Array. Defaults to the field name.</div></li>
35953      * <li>{@link Ext.data.reader.Xml}<div class="sub-desc">The mapping is an {@link Ext.DomQuery} path to the data
35954      * item relative to the DOM element that represents the {@link Ext.data.reader.Xml#record record}. Defaults to the field name.</div></li>
35955      * <li>{@link Ext.data.reader.Array}<div class="sub-desc">The mapping is a number indicating the Array index
35956      * of the field's value. Defaults to the field specification's Array position.</div></li>
35957      * </ul></div>
35958      * <p>If a more complex value extraction strategy is required, then configure the Field with a {@link #convert}
35959      * function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
35960      * return the desired data.</p>
35961      */
35962     mapping: null,
35963     /**
35964      * @cfg {Function} sortType
35965      * (Optional) A function which converts a Field's value to a comparable value in order to ensure
35966      * correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}. A custom
35967      * sort example:<pre><code>
35968 // current sort     after sort we want
35969 // +-+------+          +-+------+
35970 // |1|First |          |1|First |
35971 // |2|Last  |          |3|Second|
35972 // |3|Second|          |2|Last  |
35973 // +-+------+          +-+------+
35974
35975 sortType: function(value) {
35976    switch (value.toLowerCase()) // native toLowerCase():
35977    {
35978       case 'first': return 1;
35979       case 'second': return 2;
35980       default: return 3;
35981    }
35982 }
35983      * </code></pre>
35984      */
35985     sortType : null,
35986     /**
35987      * @cfg {String} sortDir
35988      * (Optional) Initial direction to sort (<code>"ASC"</code> or  <code>"DESC"</code>).  Defaults to
35989      * <code>"ASC"</code>.
35990      */
35991     sortDir : "ASC",
35992     /**
35993      * @cfg {Boolean} allowBlank
35994      * @private
35995      * (Optional) Used for validating a {@link Ext.data.Model model}, defaults to <code>true</code>.
35996      * An empty value here will cause {@link Ext.data.Model}.{@link Ext.data.Model#isValid isValid}
35997      * to evaluate to <code>false</code>.
35998      */
35999     allowBlank : true,
36000     
36001     /**
36002      * @cfg {Boolean} persist
36003      * False to exclude this field from the {@link Ext.data.Model#modified} fields in a model. This 
36004      * will also exclude the field from being written using a {@link Ext.data.writer.Writer}. This option
36005      * is useful when model fields are used to keep state on the client but do not need to be persisted
36006      * to the server. Defaults to <tt>true</tt>.
36007      */
36008     persist: true
36009 });
36010
36011 /**
36012  * @author Ed Spencer
36013  * @class Ext.data.reader.Reader
36014  * @extends Object
36015  * 
36016  * <p>Readers are used to interpret data to be loaded into a {@link Ext.data.Model Model} instance or a {@link Ext.data.Store Store}
36017  * - usually in response to an AJAX request. This is normally handled transparently by passing some configuration to either the 
36018  * {@link Ext.data.Model Model} or the {@link Ext.data.Store Store} in question - see their documentation for further details.</p>
36019  * 
36020  * <p><u>Loading Nested Data</u></p>
36021  * 
36022  * <p>Readers have the ability to automatically load deeply-nested data objects based on the {@link Ext.data.Association associations}
36023  * configured on each Model. Below is an example demonstrating the flexibility of these associations in a fictional CRM system which
36024  * manages a User, their Orders, OrderItems and Products. First we'll define the models:
36025  * 
36026 <pre><code>
36027 Ext.define("User", {
36028     extend: 'Ext.data.Model',
36029     fields: [
36030         'id', 'name'
36031     ],
36032
36033     hasMany: {model: 'Order', name: 'orders'},
36034
36035     proxy: {
36036         type: 'rest',
36037         url : 'users.json',
36038         reader: {
36039             type: 'json',
36040             root: 'users'
36041         }
36042     }
36043 });
36044
36045 Ext.define("Order", {
36046     extend: 'Ext.data.Model',
36047     fields: [
36048         'id', 'total'
36049     ],
36050
36051     hasMany  : {model: 'OrderItem', name: 'orderItems', associationKey: 'order_items'},
36052     belongsTo: 'User'
36053 });
36054
36055 Ext.define("OrderItem", {
36056     extend: 'Ext.data.Model',
36057     fields: [
36058         'id', 'price', 'quantity', 'order_id', 'product_id'
36059     ],
36060
36061     belongsTo: ['Order', {model: 'Product', associationKey: 'product'}]
36062 });
36063
36064 Ext.define("Product", {
36065     extend: 'Ext.data.Model',
36066     fields: [
36067         'id', 'name'
36068     ],
36069
36070     hasMany: 'OrderItem'
36071 });
36072 </code></pre>
36073  * 
36074  * <p>This may be a lot to take in - basically a User has many Orders, each of which is composed of several OrderItems. Finally,
36075  * each OrderItem has a single Product. This allows us to consume data like this:</p>
36076  * 
36077 <pre><code>
36078 {
36079     "users": [
36080         {
36081             "id": 123,
36082             "name": "Ed",
36083             "orders": [
36084                 {
36085                     "id": 50,
36086                     "total": 100,
36087                     "order_items": [
36088                         {
36089                             "id"      : 20,
36090                             "price"   : 40,
36091                             "quantity": 2,
36092                             "product" : {
36093                                 "id": 1000,
36094                                 "name": "MacBook Pro"
36095                             }
36096                         },
36097                         {
36098                             "id"      : 21,
36099                             "price"   : 20,
36100                             "quantity": 3,
36101                             "product" : {
36102                                 "id": 1001,
36103                                 "name": "iPhone"
36104                             }
36105                         }
36106                     ]
36107                 }
36108             ]
36109         }
36110     ]
36111 }
36112 </code></pre>
36113  * 
36114  * <p>The JSON response is deeply nested - it returns all Users (in this case just 1 for simplicity's sake), all of the Orders
36115  * for each User (again just 1 in this case), all of the OrderItems for each Order (2 order items in this case), and finally
36116  * the Product associated with each OrderItem. Now we can read the data and use it as follows:
36117  * 
36118 <pre><code>
36119 var store = new Ext.data.Store({
36120     model: "User"
36121 });
36122
36123 store.load({
36124     callback: function() {
36125         //the user that was loaded
36126         var user = store.first();
36127
36128         console.log("Orders for " + user.get('name') + ":")
36129
36130         //iterate over the Orders for each User
36131         user.orders().each(function(order) {
36132             console.log("Order ID: " + order.getId() + ", which contains items:");
36133
36134             //iterate over the OrderItems for each Order
36135             order.orderItems().each(function(orderItem) {
36136                 //we know that the Product data is already loaded, so we can use the synchronous getProduct
36137                 //usually, we would use the asynchronous version (see {@link Ext.data.BelongsToAssociation})
36138                 var product = orderItem.getProduct();
36139
36140                 console.log(orderItem.get('quantity') + ' orders of ' + product.get('name'));
36141             });
36142         });
36143     }
36144 });
36145 </code></pre>
36146  * 
36147  * <p>Running the code above results in the following:</p>
36148  * 
36149 <pre><code>
36150 Orders for Ed:
36151 Order ID: 50, which contains items:
36152 2 orders of MacBook Pro
36153 3 orders of iPhone
36154 </code></pre>
36155  * 
36156  * @constructor
36157  * @param {Object} config Optional config object
36158  */
36159 Ext.define('Ext.data.reader.Reader', {
36160     requires: ['Ext.data.ResultSet'],
36161     alternateClassName: ['Ext.data.Reader', 'Ext.data.DataReader'],
36162     
36163     /**
36164      * @cfg {String} idProperty Name of the property within a row object
36165      * that contains a record identifier value.  Defaults to <tt>The id of the model</tt>.
36166      * If an idProperty is explicitly specified it will override that of the one specified
36167      * on the model
36168      */
36169
36170     /**
36171      * @cfg {String} totalProperty Name of the property from which to
36172      * retrieve the total number of records in the dataset. This is only needed
36173      * if the whole dataset is not passed in one go, but is being paged from
36174      * the remote server.  Defaults to <tt>total</tt>.
36175      */
36176     totalProperty: 'total',
36177
36178     /**
36179      * @cfg {String} successProperty Name of the property from which to
36180      * retrieve the success attribute. Defaults to <tt>success</tt>.  See
36181      * {@link Ext.data.proxy.Proxy}.{@link Ext.data.proxy.Proxy#exception exception}
36182      * for additional information.
36183      */
36184     successProperty: 'success',
36185
36186     /**
36187      * @cfg {String} root <b>Required</b>.  The name of the property
36188      * which contains the Array of row objects.  Defaults to <tt>undefined</tt>.
36189      * An exception will be thrown if the root property is undefined. The data
36190      * packet value for this property should be an empty array to clear the data
36191      * or show no data.
36192      */
36193     root: '',
36194     
36195     /**
36196      * @cfg {String} messageProperty The name of the property which contains a response message.
36197      * This property is optional.
36198      */
36199     
36200     /**
36201      * @cfg {Boolean} implicitIncludes True to automatically parse models nested within other models in a response
36202      * object. See the Ext.data.reader.Reader intro docs for full explanation. Defaults to true.
36203      */
36204     implicitIncludes: true,
36205     
36206     isReader: true,
36207     
36208     constructor: function(config) {
36209         var me = this;
36210         
36211         Ext.apply(me, config || {});
36212         me.fieldCount = 0;
36213         me.model = Ext.ModelManager.getModel(config.model);
36214         if (me.model) {
36215             me.buildExtractors();
36216         }
36217     },
36218
36219     /**
36220      * Sets a new model for the reader.
36221      * @private
36222      * @param {Object} model The model to set.
36223      * @param {Boolean} setOnProxy True to also set on the Proxy, if one is configured
36224      */
36225     setModel: function(model, setOnProxy) {
36226         var me = this;
36227         
36228         me.model = Ext.ModelManager.getModel(model);
36229         me.buildExtractors(true);
36230         
36231         if (setOnProxy && me.proxy) {
36232             me.proxy.setModel(me.model, true);
36233         }
36234     },
36235
36236     /**
36237      * Reads the given response object. This method normalizes the different types of response object that may be passed
36238      * to it, before handing off the reading of records to the {@link #readRecords} function.
36239      * @param {Object} response The response object. This may be either an XMLHttpRequest object or a plain JS object
36240      * @return {Ext.data.ResultSet} The parsed ResultSet object
36241      */
36242     read: function(response) {
36243         var data = response;
36244         
36245         if (response && response.responseText) {
36246             data = this.getResponseData(response);
36247         }
36248         
36249         if (data) {
36250             return this.readRecords(data);
36251         } else {
36252             return this.nullResultSet;
36253         }
36254     },
36255
36256     /**
36257      * Abstracts common functionality used by all Reader subclasses. Each subclass is expected to call
36258      * this function before running its own logic and returning the Ext.data.ResultSet instance. For most
36259      * Readers additional processing should not be needed.
36260      * @param {Mixed} data The raw data object
36261      * @return {Ext.data.ResultSet} A ResultSet object
36262      */
36263     readRecords: function(data) {
36264         var me  = this;
36265         
36266         /*
36267          * We check here whether the number of fields has changed since the last read.
36268          * This works around an issue when a Model is used for both a Tree and another
36269          * source, because the tree decorates the model with extra fields and it causes
36270          * issues because the readers aren't notified.
36271          */
36272         if (me.fieldCount !== me.getFields().length) {
36273             me.buildExtractors(true);
36274         }
36275         
36276         /**
36277          * The raw data object that was last passed to readRecords. Stored for further processing if needed
36278          * @property rawData
36279          * @type Mixed
36280          */
36281         me.rawData = data;
36282
36283         data = me.getData(data);
36284
36285         // If we pass an array as the data, we dont use getRoot on the data.
36286         // Instead the root equals to the data.
36287         var root    = Ext.isArray(data) ? data : me.getRoot(data),
36288             success = true,
36289             recordCount = 0,
36290             total, value, records, message;
36291             
36292         if (root) {
36293             total = root.length;
36294         }
36295
36296         if (me.totalProperty) {
36297             value = parseInt(me.getTotal(data), 10);
36298             if (!isNaN(value)) {
36299                 total = value;
36300             }
36301         }
36302
36303         if (me.successProperty) {
36304             value = me.getSuccess(data);
36305             if (value === false || value === 'false') {
36306                 success = false;
36307             }
36308         }
36309         
36310         if (me.messageProperty) {
36311             message = me.getMessage(data);
36312         }
36313         
36314         if (root) {
36315             records = me.extractData(root);
36316             recordCount = records.length;
36317         } else {
36318             recordCount = 0;
36319             records = [];
36320         }
36321
36322         return Ext.create('Ext.data.ResultSet', {
36323             total  : total || recordCount,
36324             count  : recordCount,
36325             records: records,
36326             success: success,
36327             message: message
36328         });
36329     },
36330
36331     /**
36332      * Returns extracted, type-cast rows of data.  Iterates to call #extractValues for each row
36333      * @param {Object[]/Object} data-root from server response
36334      * @private
36335      */
36336     extractData : function(root) {
36337         var me = this,
36338             values  = [],
36339             records = [],
36340             Model   = me.model,
36341             i       = 0,
36342             length  = root.length,
36343             idProp  = me.getIdProperty(),
36344             node, id, record;
36345             
36346         if (!root.length && Ext.isObject(root)) {
36347             root = [root];
36348             length = 1;
36349         }
36350
36351         for (; i < length; i++) {
36352             node   = root[i];
36353             values = me.extractValues(node);
36354             id     = me.getId(node);
36355
36356             
36357             record = new Model(values, id);
36358             record.raw = node;
36359             records.push(record);
36360                 
36361             if (me.implicitIncludes) {
36362                 me.readAssociated(record, node);
36363             }
36364         }
36365
36366         return records;
36367     },
36368     
36369     /**
36370      * @private
36371      * Loads a record's associations from the data object. This prepopulates hasMany and belongsTo associations
36372      * on the record provided.
36373      * @param {Ext.data.Model} record The record to load associations for
36374      * @param {Mixed} data The data object
36375      * @return {String} Return value description
36376      */
36377     readAssociated: function(record, data) {
36378         var associations = record.associations.items,
36379             i            = 0,
36380             length       = associations.length,
36381             association, associationData, proxy, reader;
36382         
36383         for (; i < length; i++) {
36384             association     = associations[i];
36385             associationData = this.getAssociatedDataRoot(data, association.associationKey || association.name);
36386             
36387             if (associationData) {
36388                 reader = association.getReader();
36389                 if (!reader) {
36390                     proxy = association.associatedModel.proxy;
36391                     // if the associated model has a Reader already, use that, otherwise attempt to create a sensible one
36392                     if (proxy) {
36393                         reader = proxy.getReader();
36394                     } else {
36395                         reader = new this.constructor({
36396                             model: association.associatedName
36397                         });
36398                     }
36399                 }
36400                 association.read(record, reader, associationData);
36401             }  
36402         }
36403     },
36404     
36405     /**
36406      * @private
36407      * Used internally by {@link #readAssociated}. Given a data object (which could be json, xml etc) for a specific
36408      * record, this should return the relevant part of that data for the given association name. This is only really
36409      * needed to support the XML Reader, which has to do a query to get the associated data object
36410      * @param {Mixed} data The raw data object
36411      * @param {String} associationName The name of the association to get data for (uses associationKey if present)
36412      * @return {Mixed} The root
36413      */
36414     getAssociatedDataRoot: function(data, associationName) {
36415         return data[associationName];
36416     },
36417     
36418     getFields: function() {
36419         return this.model.prototype.fields.items;
36420     },
36421
36422     /**
36423      * @private
36424      * Given an object representing a single model instance's data, iterates over the model's fields and
36425      * builds an object with the value for each field.
36426      * @param {Object} data The data object to convert
36427      * @return {Object} Data object suitable for use with a model constructor
36428      */
36429     extractValues: function(data) {
36430         var fields = this.getFields(),
36431             i      = 0,
36432             length = fields.length,
36433             output = {},
36434             field, value;
36435
36436         for (; i < length; i++) {
36437             field = fields[i];
36438             value = this.extractorFunctions[i](data);
36439
36440             output[field.name] = value;
36441         }
36442
36443         return output;
36444     },
36445
36446     /**
36447      * @private
36448      * By default this function just returns what is passed to it. It can be overridden in a subclass
36449      * to return something else. See XmlReader for an example.
36450      * @param {Object} data The data object
36451      * @return {Object} The normalized data object
36452      */
36453     getData: function(data) {
36454         return data;
36455     },
36456
36457     /**
36458      * @private
36459      * This will usually need to be implemented in a subclass. Given a generic data object (the type depends on the type
36460      * of data we are reading), this function should return the object as configured by the Reader's 'root' meta data config.
36461      * See XmlReader's getRoot implementation for an example. By default the same data object will simply be returned.
36462      * @param {Mixed} data The data object
36463      * @return {Mixed} The same data object
36464      */
36465     getRoot: function(data) {
36466         return data;
36467     },
36468
36469     /**
36470      * Takes a raw response object (as passed to this.read) and returns the useful data segment of it. This must be implemented by each subclass
36471      * @param {Object} response The responce object
36472      * @return {Object} The useful data from the response
36473      */
36474     getResponseData: function(response) {
36475         Ext.Error.raise("getResponseData must be implemented in the Ext.data.reader.Reader subclass");
36476     },
36477
36478     /**
36479      * @private
36480      * Reconfigures the meta data tied to this Reader
36481      */
36482     onMetaChange : function(meta) {
36483         var fields = meta.fields,
36484             newModel;
36485         
36486         Ext.apply(this, meta);
36487         
36488         if (fields) {
36489             newModel = Ext.define("Ext.data.reader.Json-Model" + Ext.id(), {
36490                 extend: 'Ext.data.Model',
36491                 fields: fields
36492             });
36493             this.setModel(newModel, true);
36494         } else {
36495             this.buildExtractors(true);
36496         }
36497     },
36498     
36499     /**
36500      * Get the idProperty to use for extracting data
36501      * @private
36502      * @return {String} The id property
36503      */
36504     getIdProperty: function(){
36505         var prop = this.idProperty;
36506         if (Ext.isEmpty(prop)) {
36507             prop = this.model.prototype.idProperty;
36508         }
36509         return prop;
36510     },
36511
36512     /**
36513      * @private
36514      * This builds optimized functions for retrieving record data and meta data from an object.
36515      * Subclasses may need to implement their own getRoot function.
36516      * @param {Boolean} force True to automatically remove existing extractor functions first (defaults to false)
36517      */
36518     buildExtractors: function(force) {
36519         var me          = this,
36520             idProp      = me.getIdProperty(),
36521             totalProp   = me.totalProperty,
36522             successProp = me.successProperty,
36523             messageProp = me.messageProperty,
36524             accessor;
36525             
36526         if (force === true) {
36527             delete me.extractorFunctions;
36528         }
36529         
36530         if (me.extractorFunctions) {
36531             return;
36532         }   
36533
36534         //build the extractors for all the meta data
36535         if (totalProp) {
36536             me.getTotal = me.createAccessor(totalProp);
36537         }
36538
36539         if (successProp) {
36540             me.getSuccess = me.createAccessor(successProp);
36541         }
36542
36543         if (messageProp) {
36544             me.getMessage = me.createAccessor(messageProp);
36545         }
36546
36547         if (idProp) {
36548             accessor = me.createAccessor(idProp);
36549
36550             me.getId = function(record) {
36551                 var id = accessor.call(me, record);
36552                 return (id === undefined || id === '') ? null : id;
36553             };
36554         } else {
36555             me.getId = function() {
36556                 return null;
36557             };
36558         }
36559         me.buildFieldExtractors();
36560     },
36561
36562     /**
36563      * @private
36564      */
36565     buildFieldExtractors: function() {
36566         //now build the extractors for all the fields
36567         var me = this,
36568             fields = me.getFields(),
36569             ln = fields.length,
36570             i  = 0,
36571             extractorFunctions = [],
36572             field, map;
36573
36574         for (; i < ln; i++) {
36575             field = fields[i];
36576             map   = (field.mapping !== undefined && field.mapping !== null) ? field.mapping : field.name;
36577
36578             extractorFunctions.push(me.createAccessor(map));
36579         }
36580         me.fieldCount = ln;
36581
36582         me.extractorFunctions = extractorFunctions;
36583     }
36584 }, function() {
36585     Ext.apply(this, {
36586         // Private. Empty ResultSet to return when response is falsy (null|undefined|empty string)
36587         nullResultSet: Ext.create('Ext.data.ResultSet', {
36588             total  : 0,
36589             count  : 0,
36590             records: [],
36591             success: true
36592         })
36593     });
36594 });
36595 /**
36596  * @author Ed Spencer
36597  * @class Ext.data.reader.Json
36598  * @extends Ext.data.reader.Reader
36599  * 
36600  * <p>The JSON Reader is used by a Proxy to read a server response that is sent back in JSON format. This usually
36601  * happens as a result of loading a Store - for example we might create something like this:</p>
36602  * 
36603 <pre><code>
36604 Ext.define('User', {
36605     extend: 'Ext.data.Model',
36606     fields: ['id', 'name', 'email']
36607 });
36608
36609 var store = new Ext.data.Store({
36610     model: 'User',
36611     proxy: {
36612         type: 'ajax',
36613         url : 'users.json',
36614         reader: {
36615             type: 'json'
36616         }
36617     }
36618 });
36619 </code></pre>
36620  * 
36621  * <p>The example above creates a 'User' model. Models are explained in the {@link Ext.data.Model Model} docs if you're
36622  * not already familiar with them.</p>
36623  * 
36624  * <p>We created the simplest type of JSON Reader possible by simply telling our {@link Ext.data.Store Store}'s 
36625  * {@link Ext.data.proxy.Proxy Proxy} that we want a JSON Reader. The Store automatically passes the configured model to the
36626  * Store, so it is as if we passed this instead:
36627  * 
36628 <pre><code>
36629 reader: {
36630     type : 'json',
36631     model: 'User'
36632 }
36633 </code></pre>
36634  * 
36635  * <p>The reader we set up is ready to read data from our server - at the moment it will accept a response like this:</p>
36636  * 
36637 <pre><code>
36638 [
36639     {
36640         "id": 1,
36641         "name": "Ed Spencer",
36642         "email": "ed@sencha.com"
36643     },
36644     {
36645         "id": 2,
36646         "name": "Abe Elias",
36647         "email": "abe@sencha.com"
36648     }
36649 ]
36650 </code></pre>
36651  * 
36652  * <p><u>Reading other JSON formats</u></p>
36653  * 
36654  * <p>If you already have your JSON format defined and it doesn't look quite like what we have above, you can usually
36655  * pass JsonReader a couple of configuration options to make it parse your format. For example, we can use the 
36656  * {@link #root} configuration to parse data that comes back like this:</p>
36657  * 
36658 <pre><code>
36659 {
36660     "users": [
36661        {
36662            "id": 1,
36663            "name": "Ed Spencer",
36664            "email": "ed@sencha.com"
36665        },
36666        {
36667            "id": 2,
36668            "name": "Abe Elias",
36669            "email": "abe@sencha.com"
36670        }
36671     ]
36672 }
36673 </code></pre>
36674  * 
36675  * <p>To parse this we just pass in a {@link #root} configuration that matches the 'users' above:</p>
36676  * 
36677 <pre><code>
36678 reader: {
36679     type: 'json',
36680     root: 'users'
36681 }
36682 </code></pre>
36683  * 
36684  * <p>Sometimes the JSON structure is even more complicated. Document databases like CouchDB often provide metadata
36685  * around each record inside a nested structure like this:</p>
36686  * 
36687 <pre><code>
36688 {
36689     "total": 122,
36690     "offset": 0,
36691     "users": [
36692         {
36693             "id": "ed-spencer-1",
36694             "value": 1,
36695             "user": {
36696                 "id": 1,
36697                 "name": "Ed Spencer",
36698                 "email": "ed@sencha.com"
36699             }
36700         }
36701     ]
36702 }
36703 </code></pre>
36704  * 
36705  * <p>In the case above the record data is nested an additional level inside the "users" array as each "user" item has
36706  * additional metadata surrounding it ('id' and 'value' in this case). To parse data out of each "user" item in the 
36707  * JSON above we need to specify the {@link #record} configuration like this:</p>
36708  * 
36709 <pre><code>
36710 reader: {
36711     type  : 'json',
36712     root  : 'users',
36713     record: 'user'
36714 }
36715 </code></pre>
36716  * 
36717  * <p><u>Response metadata</u></p>
36718  * 
36719  * <p>The server can return additional data in its response, such as the {@link #totalProperty total number of records} 
36720  * and the {@link #successProperty success status of the response}. These are typically included in the JSON response
36721  * like this:</p>
36722  * 
36723 <pre><code>
36724 {
36725     "total": 100,
36726     "success": true,
36727     "users": [
36728         {
36729             "id": 1,
36730             "name": "Ed Spencer",
36731             "email": "ed@sencha.com"
36732         }
36733     ]
36734 }
36735 </code></pre>
36736  * 
36737  * <p>If these properties are present in the JSON response they can be parsed out by the JsonReader and used by the
36738  * Store that loaded it. We can set up the names of these properties by specifying a final pair of configuration 
36739  * options:</p>
36740  * 
36741 <pre><code>
36742 reader: {
36743     type : 'json',
36744     root : 'users',
36745     totalProperty  : 'total',
36746     successProperty: 'success'
36747 }
36748 </code></pre>
36749  * 
36750  * <p>These final options are not necessary to make the Reader work, but can be useful when the server needs to report
36751  * an error or if it needs to indicate that there is a lot of data available of which only a subset is currently being
36752  * returned.</p>
36753  */
36754 Ext.define('Ext.data.reader.Json', {
36755     extend: 'Ext.data.reader.Reader',
36756     alternateClassName: 'Ext.data.JsonReader',
36757     alias : 'reader.json',
36758     
36759     root: '',
36760     
36761     /**
36762      * @cfg {String} record The optional location within the JSON response that the record data itself can be found at.
36763      * See the JsonReader intro docs for more details. This is not often needed and defaults to undefined.
36764      */
36765     
36766     /**
36767      * @cfg {Boolean} useSimpleAccessors True to ensure that field names/mappings are treated as literals when
36768      * reading values. Defalts to <tt>false</tt>.
36769      * For example, by default, using the mapping "foo.bar.baz" will try and read a property foo from the root, then a property bar
36770      * from foo, then a property baz from bar. Setting the simple accessors to true will read the property with the name 
36771      * "foo.bar.baz" direct from the root object.
36772      */
36773     useSimpleAccessors: false,
36774     
36775     /**
36776      * Reads a JSON object and returns a ResultSet. Uses the internal getTotal and getSuccess extractors to
36777      * retrieve meta data from the response, and extractData to turn the JSON data into model instances.
36778      * @param {Object} data The raw JSON data
36779      * @return {Ext.data.ResultSet} A ResultSet containing model instances and meta data about the results
36780      */
36781     readRecords: function(data) {
36782         //this has to be before the call to super because we use the meta data in the superclass readRecords
36783         if (data.metaData) {
36784             this.onMetaChange(data.metaData);
36785         }
36786
36787         /**
36788          * DEPRECATED - will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead
36789          * @property jsonData
36790          * @type Mixed
36791          */
36792         this.jsonData = data;
36793         return this.callParent([data]);
36794     },
36795
36796     //inherit docs
36797     getResponseData: function(response) {
36798         try {
36799             var data = Ext.decode(response.responseText);
36800         }
36801         catch (ex) {
36802             Ext.Error.raise({
36803                 response: response,
36804                 json: response.responseText,
36805                 parseError: ex,
36806                 msg: 'Unable to parse the JSON returned by the server: ' + ex.toString()
36807             });
36808         }
36809         if (!data) {
36810             Ext.Error.raise('JSON object not found');
36811         }
36812
36813         return data;
36814     },
36815
36816     //inherit docs
36817     buildExtractors : function() {
36818         var me = this;
36819         
36820         me.callParent(arguments);
36821
36822         if (me.root) {
36823             me.getRoot = me.createAccessor(me.root);
36824         } else {
36825             me.getRoot = function(root) {
36826                 return root;
36827             };
36828         }
36829     },
36830     
36831     /**
36832      * @private
36833      * We're just preparing the data for the superclass by pulling out the record objects we want. If a {@link #record}
36834      * was specified we have to pull those out of the larger JSON object, which is most of what this function is doing
36835      * @param {Object} root The JSON root node
36836      * @return {Array} The records
36837      */
36838     extractData: function(root) {
36839         var recordName = this.record,
36840             data = [],
36841             length, i;
36842         
36843         if (recordName) {
36844             length = root.length;
36845             
36846             for (i = 0; i < length; i++) {
36847                 data[i] = root[i][recordName];
36848             }
36849         } else {
36850             data = root;
36851         }
36852         return this.callParent([data]);
36853     },
36854
36855     /**
36856      * @private
36857      * Returns an accessor function for the given property string. Gives support for properties such as the following:
36858      * 'someProperty'
36859      * 'some.property'
36860      * 'some["property"]'
36861      * This is used by buildExtractors to create optimized extractor functions when casting raw data into model instances.
36862      */
36863     createAccessor: function() {
36864         var re = /[\[\.]/;
36865         
36866         return function(expr) {
36867             if (Ext.isEmpty(expr)) {
36868                 return Ext.emptyFn;
36869             }
36870             if (Ext.isFunction(expr)) {
36871                 return expr;
36872             }
36873             if (this.useSimpleAccessors !== true) {
36874                 var i = String(expr).search(re);
36875                 if (i >= 0) {
36876                     return Ext.functionFactory('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
36877                 }
36878             }
36879             return function(obj) {
36880                 return obj[expr];
36881             };
36882         };
36883     }()
36884 });
36885 /**
36886  * @class Ext.data.writer.Json
36887  * @extends Ext.data.writer.Writer
36888  * @ignore
36889  */
36890 Ext.define('Ext.data.writer.Json', {
36891     extend: 'Ext.data.writer.Writer',
36892     alternateClassName: 'Ext.data.JsonWriter',
36893     alias: 'writer.json',
36894     
36895     /**
36896      * @cfg {String} root The key under which the records in this Writer will be placed. Defaults to <tt>undefined</tt>.
36897      * Example generated request, using root: 'records':
36898 <pre><code>
36899 {'records': [{name: 'my record'}, {name: 'another record'}]}
36900 </code></pre>
36901      */
36902     root: undefined,
36903     
36904     /**
36905      * @cfg {Boolean} encode True to use Ext.encode() on the data before sending. Defaults to <tt>false</tt>.
36906      * The encode option should only be set to true when a {@link #root} is defined, because the values will be
36907      * sent as part of the request parameters as opposed to a raw post. The root will be the name of the parameter
36908      * sent to the server.
36909      */
36910     encode: false,
36911     
36912     /**
36913      * @cfg {Boolean} allowSingle False to ensure that records are always wrapped in an array, even if there is only
36914      * one record being sent. When there is more than one record, they will always be encoded into an array.
36915      * Defaults to <tt>true</tt>. Example:
36916      * <pre><code>
36917 // with allowSingle: true
36918 "root": {
36919     "first": "Mark",
36920     "last": "Corrigan"
36921 }
36922
36923 // with allowSingle: false
36924 "root": [{
36925     "first": "Mark",
36926     "last": "Corrigan"
36927 }]
36928      * </code></pre>
36929      */
36930     allowSingle: true,
36931     
36932     //inherit docs
36933     writeRecords: function(request, data) {
36934         var root = this.root;
36935         
36936         if (this.allowSingle && data.length == 1) {
36937             // convert to single object format
36938             data = data[0];
36939         }
36940         
36941         if (this.encode) {
36942             if (root) {
36943                 // sending as a param, need to encode
36944                 request.params[root] = Ext.encode(data);
36945             } else {
36946                 Ext.Error.raise('Must specify a root when using encode');
36947             }
36948         } else {
36949             // send as jsonData
36950             request.jsonData = request.jsonData || {};
36951             if (root) {
36952                 request.jsonData[root] = data;
36953             } else {
36954                 request.jsonData = data;
36955             }
36956         }
36957         return request;
36958     }
36959 });
36960
36961 /**
36962  * @author Ed Spencer
36963  * @class Ext.data.proxy.Proxy
36964  * 
36965  * <p>Proxies are used by {@link Ext.data.Store Stores} to handle the loading and saving of {@link Ext.data.Model Model} data.
36966  * Usually developers will not need to create or interact with proxies directly.</p>
36967  * <p><u>Types of Proxy</u></p>
36968  * 
36969  * <p>There are two main types of Proxy - {@link Ext.data.proxy.Client Client} and {@link Ext.data.proxy.Server Server}. The Client proxies
36970  * save their data locally and include the following subclasses:</p>
36971  * 
36972  * <ul style="list-style-type: disc; padding-left: 25px">
36973  * <li>{@link Ext.data.proxy.LocalStorage LocalStorageProxy} - saves its data to localStorage if the browser supports it</li>
36974  * <li>{@link Ext.data.proxy.SessionStorage SessionStorageProxy} - saves its data to sessionStorage if the browsers supports it</li>
36975  * <li>{@link Ext.data.proxy.Memory MemoryProxy} - holds data in memory only, any data is lost when the page is refreshed</li>
36976  * </ul>
36977  * 
36978  * <p>The Server proxies save their data by sending requests to some remote server. These proxies include:</p>
36979  * 
36980  * <ul style="list-style-type: disc; padding-left: 25px">
36981  * <li>{@link Ext.data.proxy.Ajax Ajax} - sends requests to a server on the same domain</li>
36982  * <li>{@link Ext.data.proxy.JsonP JsonP} - uses JSON-P to send requests to a server on a different domain</li>
36983  * <li>{@link Ext.data.proxy.Direct Direct} - uses {@link Ext.direct} to send requests</li>
36984  * </ul>
36985  * 
36986  * <p>Proxies operate on the principle that all operations performed are either Create, Read, Update or Delete. These four operations 
36987  * are mapped to the methods {@link #create}, {@link #read}, {@link #update} and {@link #destroy} respectively. Each Proxy subclass 
36988  * implements these functions.</p>
36989  * 
36990  * <p>The CRUD methods each expect an {@link Ext.data.Operation Operation} object as the sole argument. The Operation encapsulates 
36991  * information about the action the Store wishes to perform, the {@link Ext.data.Model model} instances that are to be modified, etc.
36992  * See the {@link Ext.data.Operation Operation} documentation for more details. Each CRUD method also accepts a callback function to be 
36993  * called asynchronously on completion.</p>
36994  * 
36995  * <p>Proxies also support batching of Operations via a {@link Ext.data.Batch batch} object, invoked by the {@link #batch} method.</p>
36996  * 
36997  * @constructor
36998  * Creates the Proxy
36999  * @param {Object} config Optional config object
37000  */
37001 Ext.define('Ext.data.proxy.Proxy', {
37002     alias: 'proxy.proxy',
37003     alternateClassName: ['Ext.data.DataProxy', 'Ext.data.Proxy'],
37004     requires: [
37005         'Ext.data.reader.Json',
37006         'Ext.data.writer.Json'
37007     ],
37008     uses: [
37009         'Ext.data.Batch', 
37010         'Ext.data.Operation', 
37011         'Ext.data.Model'
37012     ],
37013     mixins: {
37014         observable: 'Ext.util.Observable'
37015     },
37016     
37017     /**
37018      * @cfg {String} batchOrder
37019      * Comma-separated ordering 'create', 'update' and 'destroy' actions when batching. Override this
37020      * to set a different order for the batched CRUD actions to be executed in. Defaults to 'create,update,destroy'
37021      */
37022     batchOrder: 'create,update,destroy',
37023     
37024     /**
37025      * @cfg {Boolean} batchActions True to batch actions of a particular type when synchronizing the store.
37026      * Defaults to <tt>true</tt>.
37027      */
37028     batchActions: true,
37029     
37030     /**
37031      * @cfg {String} defaultReaderType The default registered reader type. Defaults to 'json'
37032      * @private
37033      */
37034     defaultReaderType: 'json',
37035     
37036     /**
37037      * @cfg {String} defaultWriterType The default registered writer type. Defaults to 'json'
37038      * @private
37039      */
37040     defaultWriterType: 'json',
37041     
37042     /**
37043      * @cfg {String/Ext.data.Model} model The name of the Model to tie to this Proxy. Can be either the string name of
37044      * the Model, or a reference to the Model constructor. Required.
37045      */
37046     
37047     isProxy: true,
37048     
37049     constructor: function(config) {
37050         config = config || {};
37051         
37052         if (config.model === undefined) {
37053             delete config.model;
37054         }
37055
37056         this.mixins.observable.constructor.call(this, config);
37057         
37058         if (this.model !== undefined && !(this.model instanceof Ext.data.Model)) {
37059             this.setModel(this.model);
37060         }
37061     },
37062     
37063     /**
37064      * Sets the model associated with this proxy. This will only usually be called by a Store
37065      * @param {String|Ext.data.Model} model The new model. Can be either the model name string,
37066      * or a reference to the model's constructor
37067      * @param {Boolean} setOnStore Sets the new model on the associated Store, if one is present
37068      */
37069     setModel: function(model, setOnStore) {
37070         this.model = Ext.ModelManager.getModel(model);
37071         
37072         var reader = this.reader,
37073             writer = this.writer;
37074         
37075         this.setReader(reader);
37076         this.setWriter(writer);
37077         
37078         if (setOnStore && this.store) {
37079             this.store.setModel(this.model);
37080         }
37081     },
37082     
37083     /**
37084      * Returns the model attached to this Proxy
37085      * @return {Ext.data.Model} The model
37086      */
37087     getModel: function() {
37088         return this.model;
37089     },
37090     
37091     /**
37092      * Sets the Proxy's Reader by string, config object or Reader instance
37093      * @param {String|Object|Ext.data.reader.Reader} reader The new Reader, which can be either a type string, a configuration object
37094      * or an Ext.data.reader.Reader instance
37095      * @return {Ext.data.reader.Reader} The attached Reader object
37096      */
37097     setReader: function(reader) {
37098         var me = this;
37099         
37100         if (reader === undefined || typeof reader == 'string') {
37101             reader = {
37102                 type: reader
37103             };
37104         }
37105
37106         if (reader.isReader) {
37107             reader.setModel(me.model);
37108         } else {
37109             Ext.applyIf(reader, {
37110                 proxy: me,
37111                 model: me.model,
37112                 type : me.defaultReaderType
37113             });
37114
37115             reader = Ext.createByAlias('reader.' + reader.type, reader);
37116         }
37117         
37118         me.reader = reader;
37119         return me.reader;
37120     },
37121     
37122     /**
37123      * Returns the reader currently attached to this proxy instance
37124      * @return {Ext.data.reader.Reader} The Reader instance
37125      */
37126     getReader: function() {
37127         return this.reader;
37128     },
37129     
37130     /**
37131      * Sets the Proxy's Writer by string, config object or Writer instance
37132      * @param {String|Object|Ext.data.writer.Writer} writer The new Writer, which can be either a type string, a configuration object
37133      * or an Ext.data.writer.Writer instance
37134      * @return {Ext.data.writer.Writer} The attached Writer object
37135      */
37136     setWriter: function(writer) {
37137         if (writer === undefined || typeof writer == 'string') {
37138             writer = {
37139                 type: writer
37140             };
37141         }
37142
37143         if (!(writer instanceof Ext.data.writer.Writer)) {
37144             Ext.applyIf(writer, {
37145                 model: this.model,
37146                 type : this.defaultWriterType
37147             });
37148
37149             writer = Ext.createByAlias('writer.' + writer.type, writer);
37150         }
37151         
37152         this.writer = writer;
37153         
37154         return this.writer;
37155     },
37156     
37157     /**
37158      * Returns the writer currently attached to this proxy instance
37159      * @return {Ext.data.writer.Writer} The Writer instance
37160      */
37161     getWriter: function() {
37162         return this.writer;
37163     },
37164     
37165     /**
37166      * Performs the given create operation.
37167      * @param {Ext.data.Operation} operation The Operation to perform
37168      * @param {Function} callback Callback function to be called when the Operation has completed (whether successful or not)
37169      * @param {Object} scope Scope to execute the callback function in
37170      */
37171     create: Ext.emptyFn,
37172     
37173     /**
37174      * Performs the given read operation.
37175      * @param {Ext.data.Operation} operation The Operation to perform
37176      * @param {Function} callback Callback function to be called when the Operation has completed (whether successful or not)
37177      * @param {Object} scope Scope to execute the callback function in
37178      */
37179     read: Ext.emptyFn,
37180     
37181     /**
37182      * Performs the given update operation.
37183      * @param {Ext.data.Operation} operation The Operation to perform
37184      * @param {Function} callback Callback function to be called when the Operation has completed (whether successful or not)
37185      * @param {Object} scope Scope to execute the callback function in
37186      */
37187     update: Ext.emptyFn,
37188     
37189     /**
37190      * Performs the given destroy operation.
37191      * @param {Ext.data.Operation} operation The Operation to perform
37192      * @param {Function} callback Callback function to be called when the Operation has completed (whether successful or not)
37193      * @param {Object} scope Scope to execute the callback function in
37194      */
37195     destroy: Ext.emptyFn,
37196     
37197     /**
37198      * Performs a batch of {@link Ext.data.Operation Operations}, in the order specified by {@link #batchOrder}. Used internally by
37199      * {@link Ext.data.Store}'s {@link Ext.data.Store#sync sync} method. Example usage:
37200      * <pre><code>
37201      * myProxy.batch({
37202      *     create : [myModel1, myModel2],
37203      *     update : [myModel3],
37204      *     destroy: [myModel4, myModel5]
37205      * });
37206      * </code></pre>
37207      * Where the myModel* above are {@link Ext.data.Model Model} instances - in this case 1 and 2 are new instances and have not been 
37208      * saved before, 3 has been saved previously but needs to be updated, and 4 and 5 have already been saved but should now be destroyed.
37209      * @param {Object} operations Object containing the Model instances to act upon, keyed by action name
37210      * @param {Object} listeners Optional listeners object passed straight through to the Batch - see {@link Ext.data.Batch}
37211      * @return {Ext.data.Batch} The newly created Ext.data.Batch object
37212      */
37213     batch: function(operations, listeners) {
37214         var me = this,
37215             batch = Ext.create('Ext.data.Batch', {
37216                 proxy: me,
37217                 listeners: listeners || {}
37218             }),
37219             useBatch = me.batchActions, 
37220             records;
37221         
37222         Ext.each(me.batchOrder.split(','), function(action) {
37223             records = operations[action];
37224             if (records) {
37225                 if (useBatch) {
37226                     batch.add(Ext.create('Ext.data.Operation', {
37227                         action: action,
37228                         records: records
37229                     }));
37230                 } else {
37231                     Ext.each(records, function(record){
37232                         batch.add(Ext.create('Ext.data.Operation', {
37233                             action : action, 
37234                             records: [record]
37235                         }));
37236                     });
37237                 }
37238             }
37239         }, me);
37240         
37241         batch.start();
37242         return batch;
37243     }
37244 }, function() {
37245     // Ext.data.proxy.ProxyMgr.registerType('proxy', this);
37246     
37247     //backwards compatibility
37248     Ext.data.DataProxy = this;
37249     // Ext.deprecate('platform', '2.0', function() {
37250     //     Ext.data.DataProxy = this;
37251     // }, this);
37252 });
37253
37254 /**
37255  * @author Ed Spencer
37256  * @class Ext.data.proxy.Server
37257  * @extends Ext.data.proxy.Proxy
37258  * 
37259  * <p>ServerProxy is a superclass of {@link Ext.data.proxy.JsonP JsonPProxy} and {@link Ext.data.proxy.Ajax AjaxProxy},
37260  * and would not usually be used directly.</p>
37261  * 
37262  * <p>ServerProxy should ideally be named HttpProxy as it is a superclass for all HTTP proxies - for Ext JS 4.x it has been 
37263  * called ServerProxy to enable any 3.x applications that reference the HttpProxy to continue to work (HttpProxy is now an 
37264  * alias of AjaxProxy).</p>
37265  */
37266 Ext.define('Ext.data.proxy.Server', {
37267     extend: 'Ext.data.proxy.Proxy',
37268     alias : 'proxy.server',
37269     alternateClassName: 'Ext.data.ServerProxy',
37270     uses  : ['Ext.data.Request'],
37271     
37272     /**
37273      * @cfg {String} url The URL from which to request the data object.
37274      */
37275     
37276     /**
37277      * @cfg {Object/String/Ext.data.reader.Reader} reader The Ext.data.reader.Reader to use to decode the server's response. This can
37278      * either be a Reader instance, a config object or just a valid Reader type name (e.g. 'json', 'xml').
37279      */
37280     
37281     /**
37282      * @cfg {Object/String/Ext.data.writer.Writer} writer The Ext.data.writer.Writer to use to encode any request sent to the server.
37283      * This can either be a Writer instance, a config object or just a valid Writer type name (e.g. 'json', 'xml').
37284      */
37285     
37286     /**
37287      * @cfg {String} pageParam The name of the 'page' parameter to send in a request. Defaults to 'page'. Set this to
37288      * undefined if you don't want to send a page parameter
37289      */
37290     pageParam: 'page',
37291     
37292     /**
37293      * @cfg {String} startParam The name of the 'start' parameter to send in a request. Defaults to 'start'. Set this
37294      * to undefined if you don't want to send a start parameter
37295      */
37296     startParam: 'start',
37297
37298     /**
37299      * @cfg {String} limitParam The name of the 'limit' parameter to send in a request. Defaults to 'limit'. Set this
37300      * to undefined if you don't want to send a limit parameter
37301      */
37302     limitParam: 'limit',
37303     
37304     /**
37305      * @cfg {String} groupParam The name of the 'group' parameter to send in a request. Defaults to 'group'. Set this
37306      * to undefined if you don't want to send a group parameter
37307      */
37308     groupParam: 'group',
37309     
37310     /**
37311      * @cfg {String} sortParam The name of the 'sort' parameter to send in a request. Defaults to 'sort'. Set this
37312      * to undefined if you don't want to send a sort parameter
37313      */
37314     sortParam: 'sort',
37315     
37316     /**
37317      * @cfg {String} filterParam The name of the 'filter' parameter to send in a request. Defaults to 'filter'. Set 
37318      * this to undefined if you don't want to send a filter parameter
37319      */
37320     filterParam: 'filter',
37321     
37322     /**
37323      * @cfg {String} directionParam The name of the direction parameter to send in a request. <strong>This is only used when simpleSortMode is set to true.</strong>
37324      * Defaults to 'dir'.
37325      */
37326     directionParam: 'dir',
37327     
37328     /**
37329      * @cfg {Boolean} simpleSortMode Enabling simpleSortMode in conjunction with remoteSort will only send one sort property and a direction when a remote sort is requested.
37330      * The directionParam and sortParam will be sent with the property name and either 'ASC' or 'DESC'
37331      */
37332     simpleSortMode: false,
37333     
37334     /**
37335      * @cfg {Boolean} noCache (optional) Defaults to true. Disable caching by adding a unique parameter
37336      * name to the request.
37337      */
37338     noCache : true,
37339     
37340     /**
37341      * @cfg {String} cacheString The name of the cache param added to the url when using noCache (defaults to "_dc")
37342      */
37343     cacheString: "_dc",
37344     
37345     /**
37346      * @cfg {Number} timeout (optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
37347      */
37348     timeout : 30000,
37349     
37350     /**
37351      * @cfg {Object} api
37352      * Specific urls to call on CRUD action methods "read", "create", "update" and "destroy".
37353      * Defaults to:<pre><code>
37354 api: {
37355     read    : undefined,
37356     create  : undefined,
37357     update  : undefined,
37358     destroy : undefined
37359 }
37360      * </code></pre>
37361      * <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>
37362      * using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the
37363      * configured {@link Ext.data.Store}.{@link Ext.data.proxy.Server#url url}.</p><br>
37364      * <p>For example:</p>
37365      * <pre><code>
37366 api: {
37367     load :    '/controller/load',
37368     create :  '/controller/new',
37369     save :    '/controller/update',
37370     destroy : '/controller/destroy_action'
37371 }
37372      * </code></pre>
37373      * <p>If the specific URL for a given CRUD action is undefined, the CRUD action request
37374      * will be directed to the configured <tt>{@link Ext.data.proxy.Server#url url}</tt>.</p>
37375      */
37376     
37377     /**
37378      * @ignore
37379      */
37380     constructor: function(config) {
37381         var me = this;
37382         
37383         config = config || {};
37384         this.addEvents(
37385             /**
37386              * @event exception
37387              * Fires when the server returns an exception
37388              * @param {Ext.data.proxy.Proxy} this
37389              * @param {Object} response The response from the AJAX request
37390              * @param {Ext.data.Operation} operation The operation that triggered request
37391              */
37392             'exception'
37393         );
37394         me.callParent([config]);
37395         
37396         /**
37397          * @cfg {Object} extraParams Extra parameters that will be included on every request. Individual requests with params
37398          * of the same name will override these params when they are in conflict.
37399          */
37400         me.extraParams = config.extraParams || {};
37401         
37402         me.api = config.api || {};
37403         
37404         //backwards compatibility, will be deprecated in 5.0
37405         me.nocache = me.noCache;
37406     },
37407     
37408     //in a ServerProxy all four CRUD operations are executed in the same manner, so we delegate to doRequest in each case
37409     create: function() {
37410         return this.doRequest.apply(this, arguments);
37411     },
37412     
37413     read: function() {
37414         return this.doRequest.apply(this, arguments);
37415     },
37416     
37417     update: function() {
37418         return this.doRequest.apply(this, arguments);
37419     },
37420     
37421     destroy: function() {
37422         return this.doRequest.apply(this, arguments);
37423     },
37424     
37425     /**
37426      * Creates and returns an Ext.data.Request object based on the options passed by the {@link Ext.data.Store Store}
37427      * that this Proxy is attached to.
37428      * @param {Ext.data.Operation} operation The {@link Ext.data.Operation Operation} object to execute
37429      * @return {Ext.data.Request} The request object
37430      */
37431     buildRequest: function(operation) {
37432         var params = Ext.applyIf(operation.params || {}, this.extraParams || {}),
37433             request;
37434         
37435         //copy any sorters, filters etc into the params so they can be sent over the wire
37436         params = Ext.applyIf(params, this.getParams(params, operation));
37437         
37438         if (operation.id && !params.id) {
37439             params.id = operation.id;
37440         }
37441         
37442         request = Ext.create('Ext.data.Request', {
37443             params   : params,
37444             action   : operation.action,
37445             records  : operation.records,
37446             operation: operation,
37447             url      : operation.url
37448         });
37449         
37450         request.url = this.buildUrl(request);
37451         
37452         /*
37453          * Save the request on the Operation. Operations don't usually care about Request and Response data, but in the
37454          * ServerProxy and any of its subclasses we add both request and response as they may be useful for further processing
37455          */
37456         operation.request = request;
37457         
37458         return request;
37459     },
37460     
37461     /**
37462      * 
37463      */
37464     processResponse: function(success, operation, request, response, callback, scope){
37465         var me = this,
37466             reader,
37467             result,
37468             records,
37469             length,
37470             mc,
37471             record,
37472             i;
37473             
37474         if (success === true) {
37475             reader = me.getReader();
37476             result = reader.read(me.extractResponseData(response));
37477             records = result.records;
37478             length = records.length;
37479             
37480             if (result.success !== false) {
37481                 mc = Ext.create('Ext.util.MixedCollection', true, function(r) {return r.getId();});
37482                 mc.addAll(operation.records);
37483                 for (i = 0; i < length; i++) {
37484                     record = mc.get(records[i].getId());
37485                     
37486                     if (record) {
37487                         record.beginEdit();
37488                         record.set(record.data);
37489                         record.endEdit(true);
37490                     }
37491                 }
37492                 
37493                 //see comment in buildRequest for why we include the response object here
37494                 Ext.apply(operation, {
37495                     response: response,
37496                     resultSet: result
37497                 });
37498                 
37499                 operation.setCompleted();
37500                 operation.setSuccessful();
37501             } else {
37502                 operation.setException(result.message);
37503                 me.fireEvent('exception', this, response, operation);
37504             }
37505         } else {
37506             me.setException(operation, response);
37507             me.fireEvent('exception', this, response, operation);              
37508         }
37509             
37510         //this callback is the one that was passed to the 'read' or 'write' function above
37511         if (typeof callback == 'function') {
37512             callback.call(scope || me, operation);
37513         }
37514             
37515         me.afterRequest(request, success);
37516     },
37517     
37518     /**
37519      * Sets up an exception on the operation
37520      * @private
37521      * @param {Ext.data.Operation} operation The operation
37522      * @param {Object} response The response
37523      */
37524     setException: function(operation, response){
37525         operation.setException({
37526             status: response.status,
37527             statusText: response.statusText
37528         });     
37529     },
37530     
37531     /**
37532      * Template method to allow subclasses to specify how to get the response for the reader.
37533      * @private
37534      * @param {Object} response The server response
37535      * @return {Mixed} The response data to be used by the reader
37536      */
37537     extractResponseData: function(response){
37538         return response; 
37539     },
37540     
37541     /**
37542      * Encode any values being sent to the server. Can be overridden in subclasses.
37543      * @private
37544      * @param {Array} An array of sorters/filters.
37545      * @return {Mixed} The encoded value
37546      */
37547     applyEncoding: function(value){
37548         return Ext.encode(value);
37549     },
37550     
37551     /**
37552      * Encodes the array of {@link Ext.util.Sorter} objects into a string to be sent in the request url. By default, 
37553      * this simply JSON-encodes the sorter data
37554      * @param {Array} sorters The array of {@link Ext.util.Sorter Sorter} objects
37555      * @return {String} The encoded sorters
37556      */
37557     encodeSorters: function(sorters) {
37558         var min = [],
37559             length = sorters.length,
37560             i = 0;
37561         
37562         for (; i < length; i++) {
37563             min[i] = {
37564                 property : sorters[i].property,
37565                 direction: sorters[i].direction
37566             };
37567         }
37568         return this.applyEncoding(min);
37569         
37570     },
37571     
37572     /**
37573      * Encodes the array of {@link Ext.util.Filter} objects into a string to be sent in the request url. By default, 
37574      * this simply JSON-encodes the filter data
37575      * @param {Array} sorters The array of {@link Ext.util.Filter Filter} objects
37576      * @return {String} The encoded filters
37577      */
37578     encodeFilters: function(filters) {
37579         var min = [],
37580             length = filters.length,
37581             i = 0;
37582         
37583         for (; i < length; i++) {
37584             min[i] = {
37585                 property: filters[i].property,
37586                 value   : filters[i].value
37587             };
37588         }
37589         return this.applyEncoding(min);
37590     },
37591     
37592     /**
37593      * @private
37594      * Copy any sorters, filters etc into the params so they can be sent over the wire
37595      */
37596     getParams: function(params, operation) {
37597         params = params || {};
37598         
37599         var me             = this,
37600             isDef          = Ext.isDefined,
37601             groupers       = operation.groupers,
37602             sorters        = operation.sorters,
37603             filters        = operation.filters,
37604             page           = operation.page,
37605             start          = operation.start,
37606             limit          = operation.limit,
37607             
37608             simpleSortMode = me.simpleSortMode,
37609             
37610             pageParam      = me.pageParam,
37611             startParam     = me.startParam,
37612             limitParam     = me.limitParam,
37613             groupParam     = me.groupParam,
37614             sortParam      = me.sortParam,
37615             filterParam    = me.filterParam,
37616             directionParam       = me.directionParam;
37617         
37618         if (pageParam && isDef(page)) {
37619             params[pageParam] = page;
37620         }
37621         
37622         if (startParam && isDef(start)) {
37623             params[startParam] = start;
37624         }
37625         
37626         if (limitParam && isDef(limit)) {
37627             params[limitParam] = limit;
37628         }
37629         
37630         if (groupParam && groupers && groupers.length > 0) {
37631             // Grouper is a subclass of sorter, so we can just use the sorter method
37632             params[groupParam] = me.encodeSorters(groupers);
37633         }
37634         
37635         if (sortParam && sorters && sorters.length > 0) {
37636             if (simpleSortMode) {
37637                 params[sortParam] = sorters[0].property;
37638                 params[directionParam] = sorters[0].direction;
37639             } else {
37640                 params[sortParam] = me.encodeSorters(sorters);
37641             }
37642             
37643         }
37644         
37645         if (filterParam && filters && filters.length > 0) {
37646             params[filterParam] = me.encodeFilters(filters);
37647         }
37648         
37649         return params;
37650     },
37651     
37652     /**
37653      * Generates a url based on a given Ext.data.Request object. By default, ServerProxy's buildUrl will
37654      * add the cache-buster param to the end of the url. Subclasses may need to perform additional modifications
37655      * to the url.
37656      * @param {Ext.data.Request} request The request object
37657      * @return {String} The url
37658      */
37659     buildUrl: function(request) {
37660         var me = this,
37661             url = me.getUrl(request);
37662         
37663         if (!url) {
37664             Ext.Error.raise("You are using a ServerProxy but have not supplied it with a url.");
37665         }
37666         
37667         if (me.noCache) {
37668             url = Ext.urlAppend(url, Ext.String.format("{0}={1}", me.cacheString, Ext.Date.now()));
37669         }
37670         
37671         return url;
37672     },
37673     
37674     /**
37675      * Get the url for the request taking into account the order of priority,
37676      * - The request
37677      * - The api
37678      * - The url
37679      * @private
37680      * @param {Ext.data.Request} request The request
37681      * @return {String} The url
37682      */
37683     getUrl: function(request){
37684         return request.url || this.api[request.action] || this.url;
37685     },
37686     
37687     /**
37688      * In ServerProxy subclasses, the {@link #create}, {@link #read}, {@link #update} and {@link #destroy} methods all pass
37689      * through to doRequest. Each ServerProxy subclass must implement the doRequest method - see {@link Ext.data.proxy.JsonP}
37690      * and {@link Ext.data.proxy.Ajax} for examples. This method carries the same signature as each of the methods that delegate to it.
37691      * @param {Ext.data.Operation} operation The Ext.data.Operation object
37692      * @param {Function} callback The callback function to call when the Operation has completed
37693      * @param {Object} scope The scope in which to execute the callback
37694      */
37695     doRequest: function(operation, callback, scope) {
37696         Ext.Error.raise("The doRequest function has not been implemented on your Ext.data.proxy.Server subclass. See src/data/ServerProxy.js for details");
37697     },
37698     
37699     /**
37700      * Optional callback function which can be used to clean up after a request has been completed.
37701      * @param {Ext.data.Request} request The Request object
37702      * @param {Boolean} success True if the request was successful
37703      */
37704     afterRequest: Ext.emptyFn,
37705     
37706     onDestroy: function() {
37707         Ext.destroy(this.reader, this.writer);
37708     }
37709 });
37710
37711 /**
37712  * @author Ed Spencer
37713  * @class Ext.data.proxy.Ajax
37714  * @extends Ext.data.proxy.Server
37715  * 
37716  * <p>AjaxProxy is one of the most widely-used ways of getting data into your application. It uses AJAX requests to 
37717  * load data from the server, usually to be placed into a {@link Ext.data.Store Store}. Let's take a look at a typical
37718  * setup. Here we're going to set up a Store that has an AjaxProxy. To prepare, we'll also set up a 
37719  * {@link Ext.data.Model Model}:</p>
37720  * 
37721 <pre><code>
37722 Ext.define('User', {
37723     extend: 'Ext.data.Model',
37724     fields: ['id', 'name', 'email']
37725 });
37726
37727 //The Store contains the AjaxProxy as an inline configuration
37728 var store = new Ext.data.Store({
37729     model: 'User',
37730     proxy: {
37731         type: 'ajax',
37732         url : 'users.json'
37733     }
37734 });
37735
37736 store.load();
37737 </code></pre>
37738  * 
37739  * <p>Our example is going to load user data into a Store, so we start off by defining a {@link Ext.data.Model Model}
37740  * with the fields that we expect the server to return. Next we set up the Store itself, along with a {@link #proxy}
37741  * configuration. This configuration was automatically turned into an Ext.data.proxy.Ajax instance, with the url we
37742  * specified being passed into AjaxProxy's constructor. It's as if we'd done this:</p>
37743  * 
37744 <pre><code>
37745 new Ext.data.proxy.Ajax({
37746     url: 'users.json',
37747     model: 'User',
37748     reader: 'json'
37749 });
37750 </code></pre>
37751  * 
37752  * <p>A couple of extra configurations appeared here - {@link #model} and {@link #reader}. These are set by default 
37753  * when we create the proxy via the Store - the Store already knows about the Model, and Proxy's default 
37754  * {@link Ext.data.reader.Reader Reader} is {@link Ext.data.reader.Json JsonReader}.</p>
37755  * 
37756  * <p>Now when we call store.load(), the AjaxProxy springs into action, making a request to the url we configured
37757  * ('users.json' in this case). As we're performing a read, it sends a GET request to that url (see {@link #actionMethods}
37758  * to customize this - by default any kind of read will be sent as a GET request and any kind of write will be sent as a
37759  * POST request).</p>
37760  * 
37761  * <p><u>Limitations</u></p>
37762  * 
37763  * <p>AjaxProxy cannot be used to retrieve data from other domains. If your application is running on http://domainA.com
37764  * it cannot load data from http://domainB.com because browsers have a built-in security policy that prohibits domains
37765  * talking to each other via AJAX.</p>
37766  * 
37767  * <p>If you need to read data from another domain and can't set up a proxy server (some software that runs on your own
37768  * domain's web server and transparently forwards requests to http://domainB.com, making it look like they actually came
37769  * from http://domainA.com), you can use {@link Ext.data.proxy.JsonP} and a technique known as JSON-P (JSON with 
37770  * Padding), which can help you get around the problem so long as the server on http://domainB.com is set up to support
37771  * JSON-P responses. See {@link Ext.data.proxy.JsonP JsonPProxy}'s introduction docs for more details.</p>
37772  * 
37773  * <p><u>Readers and Writers</u></p>
37774  * 
37775  * <p>AjaxProxy can be configured to use any type of {@link Ext.data.reader.Reader Reader} to decode the server's response. If
37776  * no Reader is supplied, AjaxProxy will default to using a {@link Ext.data.reader.Json JsonReader}. Reader configuration
37777  * can be passed in as a simple object, which the Proxy automatically turns into a {@link Ext.data.reader.Reader Reader}
37778  * instance:</p>
37779  * 
37780 <pre><code>
37781 var proxy = new Ext.data.proxy.Ajax({
37782     model: 'User',
37783     reader: {
37784         type: 'xml',
37785         root: 'users'
37786     }
37787 });
37788
37789 proxy.getReader(); //returns an {@link Ext.data.reader.Xml XmlReader} instance based on the config we supplied
37790 </code></pre>
37791  * 
37792  * <p><u>Url generation</u></p>
37793  * 
37794  * <p>AjaxProxy automatically inserts any sorting, filtering, paging and grouping options into the url it generates for
37795  * each request. These are controlled with the following configuration options:</p>
37796  * 
37797  * <ul style="list-style-type: disc; padding-left: 20px;">
37798  *     <li>{@link #pageParam} - controls how the page number is sent to the server 
37799  *     (see also {@link #startParam} and {@link #limitParam})</li>
37800  *     <li>{@link #sortParam} - controls how sort information is sent to the server</li>
37801  *     <li>{@link #groupParam} - controls how grouping information is sent to the server</li>
37802  *     <li>{@link #filterParam} - controls how filter information is sent to the server</li>
37803  * </ul>
37804  * 
37805  * <p>Each request sent by AjaxProxy is described by an {@link Ext.data.Operation Operation}. To see how we can 
37806  * customize the generated urls, let's say we're loading the Proxy with the following Operation:</p>
37807  * 
37808 <pre><code>
37809 var operation = new Ext.data.Operation({
37810     action: 'read',
37811     page  : 2
37812 });
37813 </code></pre>
37814  * 
37815  * <p>Now we'll issue the request for this Operation by calling {@link #read}:</p>
37816  * 
37817 <pre><code>
37818 var proxy = new Ext.data.proxy.Ajax({
37819     url: '/users'
37820 });
37821
37822 proxy.read(operation); //GET /users?page=2
37823 </code></pre>
37824  * 
37825  * <p>Easy enough - the Proxy just copied the page property from the Operation. We can customize how this page data is
37826  * sent to the server:</p>
37827  * 
37828 <pre><code>
37829 var proxy = new Ext.data.proxy.Ajax({
37830     url: '/users',
37831     pagePage: 'pageNumber'
37832 });
37833
37834 proxy.read(operation); //GET /users?pageNumber=2
37835 </code></pre>
37836  * 
37837  * <p>Alternatively, our Operation could have been configured to send start and limit parameters instead of page:</p>
37838  * 
37839 <pre><code>
37840 var operation = new Ext.data.Operation({
37841     action: 'read',
37842     start : 50,
37843     limit : 25
37844 });
37845
37846 var proxy = new Ext.data.proxy.Ajax({
37847     url: '/users'
37848 });
37849
37850 proxy.read(operation); //GET /users?start=50&limit=25
37851 </code></pre>
37852  * 
37853  * <p>Again we can customize this url:</p>
37854  * 
37855 <pre><code>
37856 var proxy = new Ext.data.proxy.Ajax({
37857     url: '/users',
37858     startParam: 'startIndex',
37859     limitParam: 'limitIndex'
37860 });
37861
37862 proxy.read(operation); //GET /users?startIndex=50&limitIndex=25
37863 </code></pre>
37864  * 
37865  * <p>AjaxProxy will also send sort and filter information to the server. Let's take a look at how this looks with a
37866  * more expressive Operation object:</p>
37867  * 
37868 <pre><code>
37869 var operation = new Ext.data.Operation({
37870     action: 'read',
37871     sorters: [
37872         new Ext.util.Sorter({
37873             property : 'name',
37874             direction: 'ASC'
37875         }),
37876         new Ext.util.Sorter({
37877             property : 'age',
37878             direction: 'DESC'
37879         })
37880     ],
37881     filters: [
37882         new Ext.util.Filter({
37883             property: 'eyeColor',
37884             value   : 'brown'
37885         })
37886     ]
37887 });
37888 </code></pre>
37889  * 
37890  * <p>This is the type of object that is generated internally when loading a {@link Ext.data.Store Store} with sorters
37891  * and filters defined. By default the AjaxProxy will JSON encode the sorters and filters, resulting in something like
37892  * this (note that the url is escaped before sending the request, but is left unescaped here for clarity):</p>
37893  * 
37894 <pre><code>
37895 var proxy = new Ext.data.proxy.Ajax({
37896     url: '/users'
37897 });
37898
37899 proxy.read(operation); //GET /users?sort=[{"property":"name","direction":"ASC"},{"property":"age","direction":"DESC"}]&filter=[{"property":"eyeColor","value":"brown"}]
37900 </code></pre>
37901  * 
37902  * <p>We can again customize how this is created by supplying a few configuration options. Let's say our server is set 
37903  * up to receive sorting information is a format like "sortBy=name#ASC,age#DESC". We can configure AjaxProxy to provide
37904  * that format like this:</p>
37905  * 
37906  <pre><code>
37907  var proxy = new Ext.data.proxy.Ajax({
37908      url: '/users',
37909      sortParam: 'sortBy',
37910      filterParam: 'filterBy',
37911
37912      //our custom implementation of sorter encoding - turns our sorters into "name#ASC,age#DESC"
37913      encodeSorters: function(sorters) {
37914          var length   = sorters.length,
37915              sortStrs = [],
37916              sorter, i;
37917
37918          for (i = 0; i < length; i++) {
37919              sorter = sorters[i];
37920
37921              sortStrs[i] = sorter.property + '#' + sorter.direction
37922          }
37923
37924          return sortStrs.join(",");
37925      }
37926  });
37927
37928  proxy.read(operation); //GET /users?sortBy=name#ASC,age#DESC&filterBy=[{"property":"eyeColor","value":"brown"}]
37929  </code></pre>
37930  * 
37931  * <p>We can also provide a custom {@link #encodeFilters} function to encode our filters.</p>
37932  * 
37933  * @constructor
37934  * 
37935  * <p>Note that if this HttpProxy is being used by a {@link Ext.data.Store Store}, then the
37936  * Store's call to {@link #load} will override any specified <tt>callback</tt> and <tt>params</tt>
37937  * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters,
37938  * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be
37939  * used to pass parameters known at instantiation time.</p>
37940  * 
37941  * <p>If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make
37942  * the request.</p>
37943  */
37944 Ext.define('Ext.data.proxy.Ajax', {
37945     requires: ['Ext.util.MixedCollection', 'Ext.Ajax'],
37946     extend: 'Ext.data.proxy.Server',
37947     alias: 'proxy.ajax',
37948     alternateClassName: ['Ext.data.HttpProxy', 'Ext.data.AjaxProxy'],
37949     
37950     /**
37951      * @property actionMethods
37952      * Mapping of action name to HTTP request method. In the basic AjaxProxy these are set to 'GET' for 'read' actions and 'POST' 
37953      * for 'create', 'update' and 'destroy' actions. The {@link Ext.data.proxy.Rest} maps these to the correct RESTful methods.
37954      */
37955     actionMethods: {
37956         create : 'POST',
37957         read   : 'GET',
37958         update : 'POST',
37959         destroy: 'POST'
37960     },
37961     
37962     /**
37963      * @cfg {Object} headers Any headers to add to the Ajax request. Defaults to <tt>undefined</tt>.
37964      */
37965     
37966     /**
37967      * @ignore
37968      */
37969     doRequest: function(operation, callback, scope) {
37970         var writer  = this.getWriter(),
37971             request = this.buildRequest(operation, callback, scope);
37972             
37973         if (operation.allowWrite()) {
37974             request = writer.write(request);
37975         }
37976         
37977         Ext.apply(request, {
37978             headers       : this.headers,
37979             timeout       : this.timeout,
37980             scope         : this,
37981             callback      : this.createRequestCallback(request, operation, callback, scope),
37982             method        : this.getMethod(request),
37983             disableCaching: false // explicitly set it to false, ServerProxy handles caching
37984         });
37985         
37986         Ext.Ajax.request(request);
37987         
37988         return request;
37989     },
37990     
37991     /**
37992      * Returns the HTTP method name for a given request. By default this returns based on a lookup on {@link #actionMethods}.
37993      * @param {Ext.data.Request} request The request object
37994      * @return {String} The HTTP method to use (should be one of 'GET', 'POST', 'PUT' or 'DELETE')
37995      */
37996     getMethod: function(request) {
37997         return this.actionMethods[request.action];
37998     },
37999     
38000     /**
38001      * @private
38002      * TODO: This is currently identical to the JsonPProxy version except for the return function's signature. There is a lot
38003      * of code duplication inside the returned function so we need to find a way to DRY this up.
38004      * @param {Ext.data.Request} request The Request object
38005      * @param {Ext.data.Operation} operation The Operation being executed
38006      * @param {Function} callback The callback function to be called when the request completes. This is usually the callback
38007      * passed to doRequest
38008      * @param {Object} scope The scope in which to execute the callback function
38009      * @return {Function} The callback function
38010      */
38011     createRequestCallback: function(request, operation, callback, scope) {
38012         var me = this;
38013         
38014         return function(options, success, response) {
38015             me.processResponse(success, operation, request, response, callback, scope);
38016         };
38017     }
38018 }, function() {
38019     //backwards compatibility, remove in Ext JS 5.0
38020     Ext.data.HttpProxy = this;
38021 });
38022
38023 /**
38024  * @author Ed Spencer
38025  * @class Ext.data.Model
38026  *
38027  * <p>A Model represents some object that your application manages. For example, one might define a Model for Users, Products,
38028  * Cars, or any other real-world object that we want to model in the system. Models are registered via the {@link Ext.ModelManager model manager},
38029  * and are used by {@link Ext.data.Store stores}, which are in turn used by many of the data-bound components in Ext.</p>
38030  *
38031  * <p>Models are defined as a set of fields and any arbitrary methods and properties relevant to the model. For example:</p>
38032  *
38033 <pre><code>
38034 Ext.define('User', {
38035     extend: 'Ext.data.Model',
38036     fields: [
38037         {name: 'name',  type: 'string'},
38038         {name: 'age',   type: 'int'},
38039         {name: 'phone', type: 'string'},
38040         {name: 'alive', type: 'boolean', defaultValue: true}
38041     ],
38042
38043     changeName: function() {
38044         var oldName = this.get('name'),
38045             newName = oldName + " The Barbarian";
38046
38047         this.set('name', newName);
38048     }
38049 });
38050 </code></pre>
38051 *
38052 * <p>The fields array is turned into a {@link Ext.util.MixedCollection MixedCollection} automatically by the {@link Ext.ModelManager ModelManager}, and all
38053 * other functions and properties are copied to the new Model's prototype.</p>
38054 *
38055 * <p>Now we can create instances of our User model and call any model logic we defined:</p>
38056 *
38057 <pre><code>
38058 var user = Ext.ModelManager.create({
38059     name : 'Conan',
38060     age  : 24,
38061     phone: '555-555-5555'
38062 }, 'User');
38063
38064 user.changeName();
38065 user.get('name'); //returns "Conan The Barbarian"
38066 </code></pre>
38067  *
38068  * <p><u>Validations</u></p>
38069  *
38070  * <p>Models have built-in support for validations, which are executed against the validator functions in
38071  * {@link Ext.data.validations} ({@link Ext.data.validations see all validation functions}). Validations are easy to add to models:</p>
38072  *
38073 <pre><code>
38074 Ext.define('User', {
38075     extend: 'Ext.data.Model',
38076     fields: [
38077         {name: 'name',     type: 'string'},
38078         {name: 'age',      type: 'int'},
38079         {name: 'phone',    type: 'string'},
38080         {name: 'gender',   type: 'string'},
38081         {name: 'username', type: 'string'},
38082         {name: 'alive',    type: 'boolean', defaultValue: true}
38083     ],
38084
38085     validations: [
38086         {type: 'presence',  field: 'age'},
38087         {type: 'length',    field: 'name',     min: 2},
38088         {type: 'inclusion', field: 'gender',   list: ['Male', 'Female']},
38089         {type: 'exclusion', field: 'username', list: ['Admin', 'Operator']},
38090         {type: 'format',    field: 'username', matcher: /([a-z]+)[0-9]{2,3}/}
38091     ]
38092 });
38093 </code></pre>
38094  *
38095  * <p>The validations can be run by simply calling the {@link #validate} function, which returns a {@link Ext.data.Errors}
38096  * object:</p>
38097  *
38098 <pre><code>
38099 var instance = Ext.ModelManager.create({
38100     name: 'Ed',
38101     gender: 'Male',
38102     username: 'edspencer'
38103 }, 'User');
38104
38105 var errors = instance.validate();
38106 </code></pre>
38107  *
38108  * <p><u>Associations</u></p>
38109  *
38110  * <p>Models can have associations with other Models via {@link Ext.data.BelongsToAssociation belongsTo} and
38111  * {@link Ext.data.HasManyAssociation hasMany} associations. For example, let's say we're writing a blog administration
38112  * application which deals with Users, Posts and Comments. We can express the relationships between these models like this:</p>
38113  *
38114 <pre><code>
38115 Ext.define('Post', {
38116     extend: 'Ext.data.Model',
38117     fields: ['id', 'user_id'],
38118
38119     belongsTo: 'User',
38120     hasMany  : {model: 'Comment', name: 'comments'}
38121 });
38122
38123 Ext.define('Comment', {
38124     extend: 'Ext.data.Model',
38125     fields: ['id', 'user_id', 'post_id'],
38126
38127     belongsTo: 'Post'
38128 });
38129
38130 Ext.define('User', {
38131     extend: 'Ext.data.Model',
38132     fields: ['id'],
38133
38134     hasMany: [
38135         'Post',
38136         {model: 'Comment', name: 'comments'}
38137     ]
38138 });
38139 </code></pre>
38140  *
38141  * <p>See the docs for {@link Ext.data.BelongsToAssociation} and {@link Ext.data.HasManyAssociation} for details on the usage
38142  * and configuration of associations. Note that associations can also be specified like this:</p>
38143  *
38144 <pre><code>
38145 Ext.define('User', {
38146     extend: 'Ext.data.Model',
38147     fields: ['id'],
38148
38149     associations: [
38150         {type: 'hasMany', model: 'Post',    name: 'posts'},
38151         {type: 'hasMany', model: 'Comment', name: 'comments'}
38152     ]
38153 });
38154 </code></pre>
38155  *
38156  * <p><u>Using a Proxy</u></p>
38157  *
38158  * <p>Models are great for representing types of data and relationships, but sooner or later we're going to want to
38159  * load or save that data somewhere. All loading and saving of data is handled via a {@link Ext.data.proxy.Proxy Proxy},
38160  * which can be set directly on the Model:</p>
38161  *
38162 <pre><code>
38163 Ext.define('User', {
38164     extend: 'Ext.data.Model',
38165     fields: ['id', 'name', 'email'],
38166
38167     proxy: {
38168         type: 'rest',
38169         url : '/users'
38170     }
38171 });
38172 </code></pre>
38173  *
38174  * <p>Here we've set up a {@link Ext.data.proxy.Rest Rest Proxy}, which knows how to load and save data to and from a
38175  * RESTful backend. Let's see how this works:</p>
38176  *
38177 <pre><code>
38178 var user = Ext.ModelManager.create({name: 'Ed Spencer', email: 'ed@sencha.com'}, 'User');
38179
38180 user.save(); //POST /users
38181 </code></pre>
38182  *
38183  * <p>Calling {@link #save} on the new Model instance tells the configured RestProxy that we wish to persist this
38184  * Model's data onto our server. RestProxy figures out that this Model hasn't been saved before because it doesn't
38185  * have an id, and performs the appropriate action - in this case issuing a POST request to the url we configured
38186  * (/users). We configure any Proxy on any Model and always follow this API - see {@link Ext.data.proxy.Proxy} for a full
38187  * list.</p>
38188  *
38189  * <p>Loading data via the Proxy is equally easy:</p>
38190  *
38191 <pre><code>
38192 //get a reference to the User model class
38193 var User = Ext.ModelManager.getModel('User');
38194
38195 //Uses the configured RestProxy to make a GET request to /users/123
38196 User.load(123, {
38197     success: function(user) {
38198         console.log(user.getId()); //logs 123
38199     }
38200 });
38201 </code></pre>
38202  *
38203  * <p>Models can also be updated and destroyed easily:</p>
38204  *
38205 <pre><code>
38206 //the user Model we loaded in the last snippet:
38207 user.set('name', 'Edward Spencer');
38208
38209 //tells the Proxy to save the Model. In this case it will perform a PUT request to /users/123 as this Model already has an id
38210 user.save({
38211     success: function() {
38212         console.log('The User was updated');
38213     }
38214 });
38215
38216 //tells the Proxy to destroy the Model. Performs a DELETE request to /users/123
38217 user.destroy({
38218     success: function() {
38219         console.log('The User was destroyed!');
38220     }
38221 });
38222 </code></pre>
38223  *
38224  * <p><u>Usage in Stores</u></p>
38225  *
38226  * <p>It is very common to want to load a set of Model instances to be displayed and manipulated in the UI. We do this
38227  * by creating a {@link Ext.data.Store Store}:</p>
38228  *
38229 <pre><code>
38230 var store = new Ext.data.Store({
38231     model: 'User'
38232 });
38233
38234 //uses the Proxy we set up on Model to load the Store data
38235 store.load();
38236 </code></pre>
38237  *
38238  * <p>A Store is just a collection of Model instances - usually loaded from a server somewhere. Store can also maintain
38239  * a set of added, updated and removed Model instances to be synchronized with the server via the Proxy. See the
38240  * {@link Ext.data.Store Store docs} for more information on Stores.</p>
38241  *
38242  * @constructor
38243  * @param {Object} data An object containing keys corresponding to this model's fields, and their associated values
38244  * @param {Number} id Optional unique ID to assign to this model instance
38245  */
38246 Ext.define('Ext.data.Model', {
38247     alternateClassName: 'Ext.data.Record',
38248     
38249     mixins: {
38250         observable: 'Ext.util.Observable'
38251     },
38252
38253     requires: [
38254         'Ext.ModelManager',
38255         'Ext.data.Field',
38256         'Ext.data.Errors',
38257         'Ext.data.Operation',
38258         'Ext.data.validations',
38259         'Ext.data.proxy.Ajax',
38260         'Ext.util.MixedCollection'
38261     ],
38262
38263     onClassExtended: function(cls, data) {
38264         var onBeforeClassCreated = data.onBeforeClassCreated;
38265
38266         data.onBeforeClassCreated = function(cls, data) {
38267             var me = this,
38268                 name = Ext.getClassName(cls),
38269                 prototype = cls.prototype,
38270                 superCls = cls.prototype.superclass,
38271
38272                 validations = data.validations || [],
38273                 fields = data.fields || [],
38274                 associations = data.associations || [],
38275                 belongsTo = data.belongsTo,
38276                 hasMany = data.hasMany,
38277
38278                 fieldsMixedCollection = new Ext.util.MixedCollection(false, function(field) {
38279                     return field.name;
38280                 }),
38281
38282                 associationsMixedCollection = new Ext.util.MixedCollection(false, function(association) {
38283                     return association.name;
38284                 }),
38285
38286                 superValidations = superCls.validations,
38287                 superFields = superCls.fields,
38288                 superAssociations = superCls.associations,
38289
38290                 association, i, ln,
38291                 dependencies = [];
38292
38293             // Save modelName on class and its prototype
38294             cls.modelName = name;
38295             prototype.modelName = name;
38296
38297             // Merge the validations of the superclass and the new subclass
38298             if (superValidations) {
38299                 validations = superValidations.concat(validations);
38300             }
38301
38302             data.validations = validations;
38303
38304             // Merge the fields of the superclass and the new subclass
38305             if (superFields) {
38306                 fields = superFields.items.concat(fields);
38307             }
38308
38309             for (i = 0, ln = fields.length; i < ln; ++i) {
38310                 fieldsMixedCollection.add(new Ext.data.Field(fields[i]));
38311             }
38312
38313             data.fields = fieldsMixedCollection;
38314
38315             //associations can be specified in the more convenient format (e.g. not inside an 'associations' array).
38316             //we support that here
38317             if (belongsTo) {
38318                 belongsTo = Ext.Array.from(belongsTo);
38319
38320                 for (i = 0, ln = belongsTo.length; i < ln; ++i) {
38321                     association = belongsTo[i];
38322
38323                     if (!Ext.isObject(association)) {
38324                         association = {model: association};
38325                     }
38326
38327                     association.type = 'belongsTo';
38328                     associations.push(association);
38329                 }
38330
38331                 delete data.belongsTo;
38332             }
38333
38334             if (hasMany) {
38335                 hasMany = Ext.Array.from(hasMany);
38336                 for (i = 0, ln = hasMany.length; i < ln; ++i) {
38337                     association = hasMany[i];
38338
38339                     if (!Ext.isObject(association)) {
38340                         association = {model: association};
38341                     }
38342
38343                     association.type = 'hasMany';
38344                     associations.push(association);
38345                 }
38346
38347                 delete data.hasMany;
38348             }
38349
38350             if (superAssociations) {
38351                 associations = superAssociations.items.concat(associations);
38352             }
38353
38354             for (i = 0, ln = associations.length; i < ln; ++i) {
38355                 dependencies.push('association.' + associations[i].type.toLowerCase());
38356             }
38357
38358             if (data.proxy) {
38359                 if (typeof data.proxy === 'string') {
38360                     dependencies.push('proxy.' + data.proxy);
38361                 }
38362                 else if (typeof data.proxy.type === 'string') {
38363                     dependencies.push('proxy.' + data.proxy.type);
38364                 }
38365             }
38366
38367             Ext.require(dependencies, function() {
38368                 Ext.ModelManager.registerType(name, cls);
38369
38370                 for (i = 0, ln = associations.length; i < ln; ++i) {
38371                     association = associations[i];
38372
38373                     Ext.apply(association, {
38374                         ownerModel: name,
38375                         associatedModel: association.model
38376                     });
38377
38378                     if (Ext.ModelManager.getModel(association.model) === undefined) {
38379                         Ext.ModelManager.registerDeferredAssociation(association);
38380                     } else {
38381                         associationsMixedCollection.add(Ext.data.Association.create(association));
38382                     }
38383                 }
38384
38385                 data.associations = associationsMixedCollection;
38386
38387                 onBeforeClassCreated.call(me, cls, data);
38388
38389                 cls.setProxy(cls.prototype.proxy || cls.prototype.defaultProxyType);
38390
38391                 // Fire the onModelDefined template method on ModelManager
38392                 Ext.ModelManager.onModelDefined(cls);
38393             });
38394         }
38395     },
38396
38397     inheritableStatics: {
38398         /**
38399          * Sets the Proxy to use for this model. Accepts any options that can be accepted by {@link Ext#createByAlias Ext.createByAlias}
38400          * @param {String/Object/Ext.data.proxy.Proxy} proxy The proxy
38401          * @static
38402          */
38403         setProxy: function(proxy) {
38404             //make sure we have an Ext.data.proxy.Proxy object
38405             if (!proxy.isProxy) {
38406                 if (typeof proxy == "string") {
38407                     proxy = {
38408                         type: proxy
38409                     };
38410                 }
38411                 proxy = Ext.createByAlias("proxy." + proxy.type, proxy);
38412             }
38413             proxy.setModel(this);
38414             this.proxy = this.prototype.proxy = proxy;
38415
38416             return proxy;
38417         },
38418
38419         /**
38420          * Returns the configured Proxy for this Model
38421          * @return {Ext.data.proxy.Proxy} The proxy
38422          */
38423         getProxy: function() {
38424             return this.proxy;
38425         },
38426
38427         /**
38428          * <b>Static</b>. Asynchronously loads a model instance by id. Sample usage:
38429     <pre><code>
38430     MyApp.User = Ext.define('User', {
38431         extend: 'Ext.data.Model',
38432         fields: [
38433             {name: 'id', type: 'int'},
38434             {name: 'name', type: 'string'}
38435         ]
38436     });
38437
38438     MyApp.User.load(10, {
38439         scope: this,
38440         failure: function(record, operation) {
38441             //do something if the load failed
38442         },
38443         success: function(record, operation) {
38444             //do something if the load succeeded
38445         },
38446         callback: function(record, operation) {
38447             //do something whether the load succeeded or failed
38448         }
38449     });
38450     </code></pre>
38451          * @param {Number} id The id of the model to load
38452          * @param {Object} config Optional config object containing success, failure and callback functions, plus optional scope
38453          * @member Ext.data.Model
38454          * @method load
38455          * @static
38456          */
38457         load: function(id, config) {
38458             config = Ext.apply({}, config);
38459             config = Ext.applyIf(config, {
38460                 action: 'read',
38461                 id    : id
38462             });
38463
38464             var operation  = Ext.create('Ext.data.Operation', config),
38465                 scope      = config.scope || this,
38466                 record     = null,
38467                 callback;
38468
38469             callback = function(operation) {
38470                 if (operation.wasSuccessful()) {
38471                     record = operation.getRecords()[0];
38472                     Ext.callback(config.success, scope, [record, operation]);
38473                 } else {
38474                     Ext.callback(config.failure, scope, [record, operation]);
38475                 }
38476                 Ext.callback(config.callback, scope, [record, operation]);
38477             };
38478
38479             this.proxy.read(operation, callback, this);
38480         }
38481     },
38482
38483     statics: {
38484         PREFIX : 'ext-record',
38485         AUTO_ID: 1,
38486         EDIT   : 'edit',
38487         REJECT : 'reject',
38488         COMMIT : 'commit',
38489
38490         /**
38491          * Generates a sequential id. This method is typically called when a record is {@link #create}d
38492          * and {@link #Record no id has been specified}. The id will automatically be assigned
38493          * to the record. The returned id takes the form:
38494          * <tt>&#123;PREFIX}-&#123;AUTO_ID}</tt>.<div class="mdetail-params"><ul>
38495          * <li><b><tt>PREFIX</tt></b> : String<p class="sub-desc"><tt>Ext.data.Model.PREFIX</tt>
38496          * (defaults to <tt>'ext-record'</tt>)</p></li>
38497          * <li><b><tt>AUTO_ID</tt></b> : String<p class="sub-desc"><tt>Ext.data.Model.AUTO_ID</tt>
38498          * (defaults to <tt>1</tt> initially)</p></li>
38499          * </ul></div>
38500          * @param {Ext.data.Model} rec The record being created.  The record does not exist, it's a {@link #phantom}.
38501          * @return {String} auto-generated string id, <tt>"ext-record-i++'</tt>;
38502          * @static
38503          */
38504         id: function(rec) {
38505             var id = [this.PREFIX, '-', this.AUTO_ID++].join('');
38506             rec.phantom = true;
38507             rec.internalId = id;
38508             return id;
38509         }
38510     },
38511     
38512     /**
38513      * Internal flag used to track whether or not the model instance is currently being edited. Read-only
38514      * @property editing
38515      * @type Boolean
38516      */
38517     editing : false,
38518
38519     /**
38520      * Readonly flag - true if this Record has been modified.
38521      * @type Boolean
38522      */
38523     dirty : false,
38524
38525     /**
38526      * @cfg {String} persistanceProperty The property on this Persistable object that its data is saved to.
38527      * Defaults to 'data' (e.g. all persistable data resides in this.data.)
38528      */
38529     persistanceProperty: 'data',
38530
38531     evented: false,
38532     isModel: true,
38533
38534     /**
38535      * <tt>true</tt> when the record does not yet exist in a server-side database (see
38536      * {@link #setDirty}).  Any record which has a real database pk set as its id property
38537      * is NOT a phantom -- it's real.
38538      * @property phantom
38539      * @type {Boolean}
38540      */
38541     phantom : false,
38542
38543     /**
38544      * @cfg {String} idProperty The name of the field treated as this Model's unique id (defaults to 'id').
38545      */
38546     idProperty: 'id',
38547
38548     /**
38549      * The string type of the default Model Proxy. Defaults to 'ajax'
38550      * @property defaultProxyType
38551      * @type String
38552      */
38553     defaultProxyType: 'ajax',
38554
38555     /**
38556      * An array of the fields defined on this model
38557      * @property fields
38558      * @type {Array}
38559      */
38560
38561     constructor: function(data, id) {
38562         data = data || {};
38563         
38564         var me = this,
38565             fields,
38566             length,
38567             field,
38568             name,
38569             i,
38570             isArray = Ext.isArray(data),
38571             newData = isArray ? {} : null; // to hold mapped array data if needed
38572
38573         /**
38574          * An internal unique ID for each Model instance, used to identify Models that don't have an ID yet
38575          * @property internalId
38576          * @type String
38577          * @private
38578          */
38579         me.internalId = (id || id === 0) ? id : Ext.data.Model.id(me);
38580
38581         Ext.applyIf(me, {
38582             data: {}    
38583         });
38584         
38585         /**
38586          * Key: value pairs of all fields whose values have changed
38587          * @property modified
38588          * @type Object
38589          */
38590         me.modified = {};
38591
38592         me[me.persistanceProperty] = {};
38593
38594         me.mixins.observable.constructor.call(me);
38595
38596         //add default field values if present
38597         fields = me.fields.items;
38598         length = fields.length;
38599
38600         for (i = 0; i < length; i++) {
38601             field = fields[i];
38602             name  = field.name;
38603
38604             if (isArray){ 
38605                 // Have to map array data so the values get assigned to the named fields
38606                 // rather than getting set as the field names with undefined values.
38607                 newData[name] = data[i];
38608             }
38609             else if (data[name] === undefined) {
38610                 data[name] = field.defaultValue;
38611             }
38612         }
38613
38614         me.set(newData || data);
38615         // clear any dirty/modified since we're initializing
38616         me.dirty = false;
38617         me.modified = {};
38618
38619         if (me.getId()) {
38620             me.phantom = false;
38621         }
38622
38623         if (typeof me.init == 'function') {
38624             me.init();
38625         }
38626
38627         me.id = me.modelName + '-' + me.internalId;
38628
38629         Ext.ModelManager.register(me);
38630     },
38631     
38632     /**
38633      * Returns the value of the given field
38634      * @param {String} fieldName The field to fetch the value for
38635      * @return {Mixed} The value
38636      */
38637     get: function(field) {
38638         return this[this.persistanceProperty][field];
38639     },
38640     
38641     /**
38642      * Sets the given field to the given value, marks the instance as dirty
38643      * @param {String|Object} fieldName The field to set, or an object containing key/value pairs
38644      * @param {Mixed} value The value to set
38645      */
38646     set: function(fieldName, value) {
38647         var me = this,
38648             fields = me.fields,
38649             modified = me.modified,
38650             convertFields = [],
38651             field, key, i, currentValue;
38652
38653         /*
38654          * If we're passed an object, iterate over that object. NOTE: we pull out fields with a convert function and
38655          * set those last so that all other possible data is set before the convert function is called
38656          */
38657         if (arguments.length == 1 && Ext.isObject(fieldName)) {
38658             for (key in fieldName) {
38659                 if (fieldName.hasOwnProperty(key)) {
38660                 
38661                     //here we check for the custom convert function. Note that if a field doesn't have a convert function,
38662                     //we default it to its type's convert function, so we have to check that here. This feels rather dirty.
38663                     field = fields.get(key);
38664                     if (field && field.convert !== field.type.convert) {
38665                         convertFields.push(key);
38666                         continue;
38667                     }
38668                     
38669                     me.set(key, fieldName[key]);
38670                 }
38671             }
38672
38673             for (i = 0; i < convertFields.length; i++) {
38674                 field = convertFields[i];
38675                 me.set(field, fieldName[field]);
38676             }
38677
38678         } else {
38679             if (fields) {
38680                 field = fields.get(fieldName);
38681
38682                 if (field && field.convert) {
38683                     value = field.convert(value, me);
38684                 }
38685             }
38686             currentValue = me.get(fieldName);
38687             me[me.persistanceProperty][fieldName] = value;
38688             
38689             if (field && field.persist && !me.isEqual(currentValue, value)) {
38690                 me.dirty = true;
38691                 me.modified[fieldName] = currentValue;
38692             }
38693
38694             if (!me.editing) {
38695                 me.afterEdit();
38696             }
38697         }
38698     },
38699     
38700     /**
38701      * Checks if two values are equal, taking into account certain
38702      * special factors, for example dates.
38703      * @private
38704      * @param {Object} a The first value
38705      * @param {Object} b The second value
38706      * @return {Boolean} True if the values are equal
38707      */
38708     isEqual: function(a, b){
38709         if (Ext.isDate(a) && Ext.isDate(b)) {
38710             return a.getTime() === b.getTime();
38711         }
38712         return a === b;
38713     },
38714     
38715     /**
38716      * Begin an edit. While in edit mode, no events (e.g.. the <code>update</code> event)
38717      * are relayed to the containing store. When an edit has begun, it must be followed
38718      * by either {@link #endEdit} or {@link #cancelEdit}.
38719      */
38720     beginEdit : function(){
38721         var me = this;
38722         if (!me.editing) {
38723             me.editing = true;
38724             me.dirtySave = me.dirty;
38725             me.dataSave = Ext.apply({}, me[me.persistanceProperty]);
38726             me.modifiedSave = Ext.apply({}, me.modified);
38727         }
38728     },
38729     
38730     /**
38731      * Cancels all changes made in the current edit operation.
38732      */
38733     cancelEdit : function(){
38734         var me = this;
38735         if (me.editing) {
38736             me.editing = false;
38737             // reset the modified state, nothing changed since the edit began
38738             me.modified = me.modifiedSave;
38739             me[me.persistanceProperty] = me.dataSave;
38740             me.dirty = me.dirtySave;
38741             delete me.modifiedSave;
38742             delete me.dataSave;
38743             delete me.dirtySave;
38744         }
38745     },
38746     
38747     /**
38748      * End an edit. If any data was modified, the containing store is notified
38749      * (ie, the store's <code>update</code> event will fire).
38750      * @param {Boolean} silent True to not notify the store of the change
38751      */
38752     endEdit : function(silent){
38753         var me = this;
38754         if (me.editing) {
38755             me.editing = false;
38756             delete me.modifiedSave;
38757             delete me.dataSave;
38758             delete me.dirtySave;
38759             if (silent !== true && me.dirty) {
38760                 me.afterEdit();
38761             }
38762         }
38763     },
38764     
38765     /**
38766      * Gets a hash of only the fields that have been modified since this Model was created or commited.
38767      * @return Object
38768      */
38769     getChanges : function(){
38770         var modified = this.modified,
38771             changes  = {},
38772             field;
38773
38774         for (field in modified) {
38775             if (modified.hasOwnProperty(field)){
38776                 changes[field] = this.get(field);
38777             }
38778         }
38779
38780         return changes;
38781     },
38782     
38783     /**
38784      * Returns <tt>true</tt> if the passed field name has been <code>{@link #modified}</code>
38785      * since the load or last commit.
38786      * @param {String} fieldName {@link Ext.data.Field#name}
38787      * @return {Boolean}
38788      */
38789     isModified : function(fieldName) {
38790         return this.modified.hasOwnProperty(fieldName);
38791     },
38792     
38793     /**
38794      * <p>Marks this <b>Record</b> as <code>{@link #dirty}</code>.  This method
38795      * is used interally when adding <code>{@link #phantom}</code> records to a
38796      * {@link Ext.data.Store#writer writer enabled store}.</p>
38797      * <br><p>Marking a record <code>{@link #dirty}</code> causes the phantom to
38798      * be returned by {@link Ext.data.Store#getModifiedRecords} where it will
38799      * have a create action composed for it during {@link Ext.data.Store#save store save}
38800      * operations.</p>
38801      */
38802     setDirty : function() {
38803         var me = this,
38804             name;
38805         
38806         me.dirty = true;
38807
38808         me.fields.each(function(field) {
38809             if (field.persist) {
38810                 name = field.name;
38811                 me.modified[name] = me.get(name);
38812             }
38813         }, me);
38814     },
38815
38816     markDirty : function() {
38817         if (Ext.isDefined(Ext.global.console)) {
38818             Ext.global.console.warn('Ext.data.Model: markDirty has been deprecated. Use setDirty instead.');
38819         }
38820         return this.setDirty.apply(this, arguments);
38821     },
38822     
38823     /**
38824      * Usually called by the {@link Ext.data.Store} to which this model instance has been {@link #join joined}.
38825      * Rejects all changes made to the model instance since either creation, or the last commit operation.
38826      * Modified fields are reverted to their original values.
38827      * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
38828      * to have their code notified of reject operations.</p>
38829      * @param {Boolean} silent (optional) True to skip notification of the owning
38830      * store of the change (defaults to false)
38831      */
38832     reject : function(silent) {
38833         var me = this,
38834             modified = me.modified,
38835             field;
38836
38837         for (field in modified) {
38838             if (modified.hasOwnProperty(field)) {
38839                 if (typeof modified[field] != "function") {
38840                     me[me.persistanceProperty][field] = modified[field];
38841                 }
38842             }
38843         }
38844
38845         me.dirty = false;
38846         me.editing = false;
38847         me.modified = {};
38848
38849         if (silent !== true) {
38850             me.afterReject();
38851         }
38852     },
38853
38854     /**
38855      * Usually called by the {@link Ext.data.Store} which owns the model instance.
38856      * Commits all changes made to the instance since either creation or the last commit operation.
38857      * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
38858      * to have their code notified of commit operations.</p>
38859      * @param {Boolean} silent (optional) True to skip notification of the owning
38860      * store of the change (defaults to false)
38861      */
38862     commit : function(silent) {
38863         var me = this;
38864         
38865         me.dirty = false;
38866         me.editing = false;
38867
38868         me.modified = {};
38869
38870         if (silent !== true) {
38871             me.afterCommit();
38872         }
38873     },
38874
38875     /**
38876      * Creates a copy (clone) of this Model instance.
38877      * @param {String} id (optional) A new id, defaults to the id
38878      * of the instance being copied. See <code>{@link #id}</code>.
38879      * To generate a phantom instance with a new id use:<pre><code>
38880 var rec = record.copy(); // clone the record
38881 Ext.data.Model.id(rec); // automatically generate a unique sequential id
38882      * </code></pre>
38883      * @return {Record}
38884      */
38885     copy : function(newId) {
38886         var me = this;
38887         
38888         return new me.self(Ext.apply({}, me[me.persistanceProperty]), newId || me.internalId);
38889     },
38890
38891     /**
38892      * Sets the Proxy to use for this model. Accepts any options that can be accepted by {@link Ext#createByAlias Ext.createByAlias}
38893      * @param {String/Object/Ext.data.proxy.Proxy} proxy The proxy
38894      * @static
38895      */
38896     setProxy: function(proxy) {
38897         //make sure we have an Ext.data.proxy.Proxy object
38898         if (!proxy.isProxy) {
38899             if (typeof proxy === "string") {
38900                 proxy = {
38901                     type: proxy
38902                 };
38903             }
38904             proxy = Ext.createByAlias("proxy." + proxy.type, proxy);
38905         }
38906         proxy.setModel(this.self);
38907         this.proxy = proxy;
38908
38909         return proxy;
38910     },
38911
38912     /**
38913      * Returns the configured Proxy for this Model
38914      * @return {Ext.data.proxy.Proxy} The proxy
38915      */
38916     getProxy: function() {
38917         return this.proxy;
38918     },
38919
38920     /**
38921      * Validates the current data against all of its configured {@link #validations} and returns an
38922      * {@link Ext.data.Errors Errors} object
38923      * @return {Ext.data.Errors} The errors object
38924      */
38925     validate: function() {
38926         var errors      = Ext.create('Ext.data.Errors'),
38927             validations = this.validations,
38928             validators  = Ext.data.validations,
38929             length, validation, field, valid, type, i;
38930
38931         if (validations) {
38932             length = validations.length;
38933
38934             for (i = 0; i < length; i++) {
38935                 validation = validations[i];
38936                 field = validation.field || validation.name;
38937                 type  = validation.type;
38938                 valid = validators[type](validation, this.get(field));
38939
38940                 if (!valid) {
38941                     errors.add({
38942                         field  : field,
38943                         message: validation.message || validators[type + 'Message']
38944                     });
38945                 }
38946             }
38947         }
38948
38949         return errors;
38950     },
38951
38952     /**
38953      * Checks if the model is valid. See {@link #validate}.
38954      * @return {Boolean} True if the model is valid.
38955      */
38956     isValid: function(){
38957         return this.validate().isValid();
38958     },
38959
38960     /**
38961      * Saves the model instance using the configured proxy
38962      * @param {Object} options Options to pass to the proxy
38963      * @return {Ext.data.Model} The Model instance
38964      */
38965     save: function(options) {
38966         options = Ext.apply({}, options);
38967
38968         var me     = this,
38969             action = me.phantom ? 'create' : 'update',
38970             record = null,
38971             scope  = options.scope || me,
38972             operation,
38973             callback;
38974
38975         Ext.apply(options, {
38976             records: [me],
38977             action : action
38978         });
38979
38980         operation = Ext.create('Ext.data.Operation', options);
38981
38982         callback = function(operation) {
38983             if (operation.wasSuccessful()) {
38984                 record = operation.getRecords()[0];
38985                 //we need to make sure we've set the updated data here. Ideally this will be redundant once the
38986                 //ModelCache is in place
38987                 me.set(record.data);
38988                 record.dirty = false;
38989
38990                 Ext.callback(options.success, scope, [record, operation]);
38991             } else {
38992                 Ext.callback(options.failure, scope, [record, operation]);
38993             }
38994
38995             Ext.callback(options.callback, scope, [record, operation]);
38996         };
38997
38998         me.getProxy()[action](operation, callback, me);
38999
39000         return me;
39001     },
39002
39003     /**
39004      * Destroys the model using the configured proxy
39005      * @param {Object} options Options to pass to the proxy
39006      * @return {Ext.data.Model} The Model instance
39007      */
39008     destroy: function(options){
39009         options = Ext.apply({}, options);
39010
39011         var me     = this,
39012             record = null,
39013             scope  = options.scope || me,
39014             operation,
39015             callback;
39016
39017         Ext.apply(options, {
39018             records: [me],
39019             action : 'destroy'
39020         });
39021
39022         operation = Ext.create('Ext.data.Operation', options);
39023         callback = function(operation) {
39024             if (operation.wasSuccessful()) {
39025                 Ext.callback(options.success, scope, [record, operation]);
39026             } else {
39027                 Ext.callback(options.failure, scope, [record, operation]);
39028             }
39029             Ext.callback(options.callback, scope, [record, operation]);
39030         };
39031
39032         me.getProxy().destroy(operation, callback, me);
39033         return me;
39034     },
39035
39036     /**
39037      * Returns the unique ID allocated to this model instance as defined by {@link #idProperty}
39038      * @return {Number} The id
39039      */
39040     getId: function() {
39041         return this.get(this.idProperty);
39042     },
39043
39044     /**
39045      * Sets the model instance's id field to the given id
39046      * @param {Number} id The new id
39047      */
39048     setId: function(id) {
39049         this.set(this.idProperty, id);
39050     },
39051
39052     /**
39053      * Tells this model instance that it has been added to a store
39054      * @param {Ext.data.Store} store The store that the model has been added to
39055      */
39056     join : function(store) {
39057         /**
39058          * The {@link Ext.data.Store} to which this Record belongs.
39059          * @property store
39060          * @type {Ext.data.Store}
39061          */
39062         this.store = store;
39063     },
39064
39065     /**
39066      * Tells this model instance that it has been removed from the store
39067      */
39068     unjoin: function() {
39069         delete this.store;
39070     },
39071
39072     /**
39073      * @private
39074      * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's
39075      * afterEdit method is called
39076      */
39077     afterEdit : function() {
39078         this.callStore('afterEdit');
39079     },
39080
39081     /**
39082      * @private
39083      * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's
39084      * afterReject method is called
39085      */
39086     afterReject : function() {
39087         this.callStore("afterReject");
39088     },
39089
39090     /**
39091      * @private
39092      * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's
39093      * afterCommit method is called
39094      */
39095     afterCommit: function() {
39096         this.callStore('afterCommit');
39097     },
39098
39099     /**
39100      * @private
39101      * Helper function used by afterEdit, afterReject and afterCommit. Calls the given method on the
39102      * {@link Ext.data.Store store} that this instance has {@link #join joined}, if any. The store function
39103      * will always be called with the model instance as its single argument.
39104      * @param {String} fn The function to call on the store
39105      */
39106     callStore: function(fn) {
39107         var store = this.store;
39108
39109         if (store !== undefined && typeof store[fn] == "function") {
39110             store[fn](this);
39111         }
39112     },
39113
39114     /**
39115      * Gets all of the data from this Models *loaded* associations.
39116      * It does this recursively - for example if we have a User which
39117      * hasMany Orders, and each Order hasMany OrderItems, it will return an object like this:
39118      * {
39119      *     orders: [
39120      *         {
39121      *             id: 123,
39122      *             status: 'shipped',
39123      *             orderItems: [
39124      *                 ...
39125      *             ]
39126      *         }
39127      *     ]
39128      * }
39129      * @return {Object} The nested data set for the Model's loaded associations
39130      */
39131     getAssociatedData: function(){
39132         return this.prepareAssociatedData(this, [], null);
39133     },
39134
39135     /**
39136      * @private
39137      * This complex-looking method takes a given Model instance and returns an object containing all data from
39138      * all of that Model's *loaded* associations. See (@link #getAssociatedData}
39139      * @param {Ext.data.Model} record The Model instance
39140      * @param {Array} ids PRIVATE. The set of Model instance internalIds that have already been loaded
39141      * @param {String} associationType (optional) The name of the type of association to limit to.
39142      * @return {Object} The nested data set for the Model's loaded associations
39143      */
39144     prepareAssociatedData: function(record, ids, associationType) {
39145         //we keep track of all of the internalIds of the models that we have loaded so far in here
39146         var associations     = record.associations.items,
39147             associationCount = associations.length,
39148             associationData  = {},
39149             associatedStore, associatedName, associatedRecords, associatedRecord,
39150             associatedRecordCount, association, id, i, j, type, allow;
39151
39152         for (i = 0; i < associationCount; i++) {
39153             association = associations[i];
39154             type = association.type;
39155             allow = true;
39156             if (associationType) {
39157                 allow = type == associationType;
39158             }
39159             if (allow && type == 'hasMany') {
39160
39161                 //this is the hasMany store filled with the associated data
39162                 associatedStore = record[association.storeName];
39163
39164                 //we will use this to contain each associated record's data
39165                 associationData[association.name] = [];
39166
39167                 //if it's loaded, put it into the association data
39168                 if (associatedStore && associatedStore.data.length > 0) {
39169                     associatedRecords = associatedStore.data.items;
39170                     associatedRecordCount = associatedRecords.length;
39171
39172                     //now we're finally iterating over the records in the association. We do this recursively
39173                     for (j = 0; j < associatedRecordCount; j++) {
39174                         associatedRecord = associatedRecords[j];
39175                         // Use the id, since it is prefixed with the model name, guaranteed to be unique
39176                         id = associatedRecord.id;
39177
39178                         //when we load the associations for a specific model instance we add it to the set of loaded ids so that
39179                         //we don't load it twice. If we don't do this, we can fall into endless recursive loading failures.
39180                         if (Ext.Array.indexOf(ids, id) == -1) {
39181                             ids.push(id);
39182
39183                             associationData[association.name][j] = associatedRecord.data;
39184                             Ext.apply(associationData[association.name][j], this.prepareAssociatedData(associatedRecord, ids, type));
39185                         }
39186                     }
39187                 }
39188             } else if (allow && type == 'belongsTo') {
39189                 associatedRecord = record[association.instanceName];
39190                 if (associatedRecord !== undefined) {
39191                     id = associatedRecord.id;
39192                     if (Ext.Array.indexOf(ids, id) == -1) {
39193                         ids.push(id);
39194                         associationData[association.name] = associatedRecord.data;
39195                         Ext.apply(associationData[association.name], this.prepareAssociatedData(associatedRecord, ids, type));
39196                     }
39197                 }
39198             }
39199         }
39200
39201         return associationData;
39202     }
39203 });
39204
39205 /**
39206  * @class Ext.Component
39207  * @extends Ext.AbstractComponent
39208  * <p>Base class for all Ext components.  All subclasses of Component may participate in the automated
39209  * Ext component lifecycle of creation, rendering and destruction which is provided by the {@link Ext.container.Container Container} class.
39210  * Components may be added to a Container through the {@link Ext.container.Container#items items} config option at the time the Container is created,
39211  * or they may be added dynamically via the {@link Ext.container.Container#add add} method.</p>
39212  * <p>The Component base class has built-in support for basic hide/show and enable/disable and size control behavior.</p>
39213  * <p>All Components are registered with the {@link Ext.ComponentManager} on construction so that they can be referenced at any time via
39214  * {@link Ext#getCmp Ext.getCmp}, passing the {@link #id}.</p>
39215  * <p>All user-developed visual widgets that are required to participate in automated lifecycle and size management should subclass Component.</p>
39216  * <p>See the <a href="http://sencha.com/learn/Tutorial:Creating_new_UI_controls">Creating new UI controls</a> tutorial for details on how
39217  * and to either extend or augment ExtJs base classes to create custom Components.</p>
39218  * <p>Every component has a specific xtype, which is its Ext-specific type name, along with methods for checking the
39219  * xtype like {@link #getXType} and {@link #isXType}. This is the list of all valid xtypes:</p>
39220  * <pre>
39221 xtype            Class
39222 -------------    ------------------
39223 button           {@link Ext.button.Button}
39224 buttongroup      {@link Ext.container.ButtonGroup}
39225 colorpalette     {@link Ext.picker.Color}
39226 component        {@link Ext.Component}
39227 container        {@link Ext.container.Container}
39228 cycle            {@link Ext.button.Cycle}
39229 dataview         {@link Ext.view.View}
39230 datepicker       {@link Ext.picker.Date}
39231 editor           {@link Ext.Editor}
39232 editorgrid       {@link Ext.grid.plugin.Editing}
39233 grid             {@link Ext.grid.Panel}
39234 multislider      {@link Ext.slider.Multi}
39235 panel            {@link Ext.panel.Panel}
39236 progress         {@link Ext.ProgressBar}
39237 slider           {@link Ext.slider.Single}
39238 spacer           {@link Ext.toolbar.Spacer}
39239 splitbutton      {@link Ext.button.Split}
39240 tabpanel         {@link Ext.tab.Panel}
39241 treepanel        {@link Ext.tree.Panel}
39242 viewport         {@link Ext.container.Viewport}
39243 window           {@link Ext.window.Window}
39244
39245 Toolbar components
39246 ---------------------------------------
39247 paging           {@link Ext.toolbar.Paging}
39248 toolbar          {@link Ext.toolbar.Toolbar}
39249 tbfill           {@link Ext.toolbar.Fill}
39250 tbitem           {@link Ext.toolbar.Item}
39251 tbseparator      {@link Ext.toolbar.Separator}
39252 tbspacer         {@link Ext.toolbar.Spacer}
39253 tbtext           {@link Ext.toolbar.TextItem}
39254
39255 Menu components
39256 ---------------------------------------
39257 menu             {@link Ext.menu.Menu}
39258 menucheckitem    {@link Ext.menu.CheckItem}
39259 menuitem         {@link Ext.menu.Item}
39260 menuseparator    {@link Ext.menu.Separator}
39261 menutextitem     {@link Ext.menu.Item}
39262
39263 Form components
39264 ---------------------------------------
39265 form             {@link Ext.form.Panel}
39266 checkbox         {@link Ext.form.field.Checkbox}
39267 combo            {@link Ext.form.field.ComboBox}
39268 datefield        {@link Ext.form.field.Date}
39269 displayfield     {@link Ext.form.field.Display}
39270 field            {@link Ext.form.field.Base}
39271 fieldset         {@link Ext.form.FieldSet}
39272 hidden           {@link Ext.form.field.Hidden}
39273 htmleditor       {@link Ext.form.field.HtmlEditor}
39274 label            {@link Ext.form.Label}
39275 numberfield      {@link Ext.form.field.Number}
39276 radio            {@link Ext.form.field.Radio}
39277 radiogroup       {@link Ext.form.RadioGroup}
39278 textarea         {@link Ext.form.field.TextArea}
39279 textfield        {@link Ext.form.field.Text}
39280 timefield        {@link Ext.form.field.Time}
39281 trigger          {@link Ext.form.field.Trigger}
39282
39283 Chart components
39284 ---------------------------------------
39285 chart            {@link Ext.chart.Chart}
39286 barchart         {@link Ext.chart.series.Bar}
39287 columnchart      {@link Ext.chart.series.Column}
39288 linechart        {@link Ext.chart.series.Line}
39289 piechart         {@link Ext.chart.series.Pie}
39290
39291 </pre><p>
39292  * It should not usually be necessary to instantiate a Component because there are provided subclasses which implement specialized Component
39293  * use cases which over most application needs. However it is possible to instantiate a base Component, and it will be renderable,
39294  * or will particpate in layouts as the child item of a Container:
39295 {@img Ext.Component/Ext.Component.png Ext.Component component}
39296 <pre><code>
39297     Ext.create('Ext.Component', {
39298         html: 'Hello world!',
39299         width: 300,
39300         height: 200,
39301         padding: 20,
39302         style: {
39303             color: '#FFFFFF',
39304             backgroundColor:'#000000'
39305         },
39306         renderTo: Ext.getBody()
39307     });
39308 </code></pre>
39309  *</p>
39310  *<p>The Component above creates its encapsulating <code>div</code> upon render, and use the configured HTML as content. More complex
39311  * internal structure may be created using the {@link #renderTpl} configuration, although to display database-derived mass
39312  * data, it is recommended that an ExtJS data-backed Component such as a {Ext.view.DataView DataView}, or {Ext.grid.Panel GridPanel},
39313  * or {@link Ext.tree.Panel TreePanel} be used.</p>
39314  * @constructor
39315  * @param {Ext.core.Element/String/Object} config The configuration options may be specified as either:
39316  * <div class="mdetail-params"><ul>
39317  * <li><b>an element</b> :
39318  * <p class="sub-desc">it is set as the internal element and its id used as the component id</p></li>
39319  * <li><b>a string</b> :
39320  * <p class="sub-desc">it is assumed to be the id of an existing element and is used as the component id</p></li>
39321  * <li><b>anything else</b> :
39322  * <p class="sub-desc">it is assumed to be a standard config object and is applied to the component</p></li>
39323  * </ul></div>
39324  */
39325
39326 Ext.define('Ext.Component', {
39327
39328     /* Begin Definitions */
39329
39330     alias: ['widget.component', 'widget.box'],
39331
39332     extend: 'Ext.AbstractComponent',
39333
39334     requires: [
39335         'Ext.util.DelayedTask'
39336     ],
39337
39338     uses: [
39339         'Ext.Layer',
39340         'Ext.resizer.Resizer',
39341         'Ext.util.ComponentDragger'
39342     ],
39343
39344     mixins: {
39345         floating: 'Ext.util.Floating'
39346     },
39347
39348     statics: {
39349         // Collapse/expand directions
39350         DIRECTION_TOP: 'top',
39351         DIRECTION_RIGHT: 'right',
39352         DIRECTION_BOTTOM: 'bottom',
39353         DIRECTION_LEFT: 'left'
39354     },
39355
39356     /* End Definitions */
39357
39358     /**
39359      * @cfg {Mixed} resizable
39360      * <p>Specify as <code>true</code> to apply a {@link Ext.resizer.Resizer Resizer} to this Component
39361      * after rendering.</p>
39362      * <p>May also be specified as a config object to be passed to the constructor of {@link Ext.resizer.Resizer Resizer}
39363      * to override any defaults. By default the Component passes its minimum and maximum size, and uses
39364      * <code>{@link Ext.resizer.Resizer#dynamic}: false</code></p>
39365      */
39366
39367     /**
39368      * @cfg {String} resizeHandles
39369      * A valid {@link Ext.resizer.Resizer} handles config string (defaults to 'all').  Only applies when resizable = true.
39370      */
39371     resizeHandles: 'all',
39372
39373     /**
39374      * @cfg {Boolean} autoScroll
39375      * <code>true</code> to use overflow:'auto' on the components layout element and show scroll bars automatically when
39376      * necessary, <code>false</code> to clip any overflowing content (defaults to <code>false</code>).
39377      */
39378
39379     /**
39380      * @cfg {Boolean} floating
39381      * <p>Specify as true to float the Component outside of the document flow using CSS absolute positioning.</p>
39382      * <p>Components such as {@link Ext.window.Window Window}s and {@link Ext.menu.Menu Menu}s are floating
39383      * by default.</p>
39384      * <p>Floating Components that are programatically {@link Ext.Component#render rendered} will register themselves with the global
39385      * {@link Ext.WindowManager ZIndexManager}</p>
39386      * <h3 class="pa">Floating Components as child items of a Container</h3>
39387      * <p>A floating Component may be used as a child item of a Container. This just allows the floating Component to seek a ZIndexManager by
39388      * examining the ownerCt chain.</p>
39389      * <p>When configured as floating, Components acquire, at render time, a {@link Ext.ZIndexManager ZIndexManager} which manages a stack
39390      * of related floating Components. The ZIndexManager brings a single floating Component to the top of its stack when
39391      * the Component's {@link #toFront} method is called.</p>
39392      * <p>The ZIndexManager is found by traversing up the {@link #ownerCt} chain to find an ancestor which itself is floating. This is so that
39393      * descendant floating Components of floating <i>Containers</i> (Such as a ComboBox dropdown within a Window) can have its zIndex managed relative
39394      * to any siblings, but always <b>above</b> that floating ancestor Container.</p>
39395      * <p>If no floating ancestor is found, a floating Component registers itself with the default {@link Ext.WindowManager ZIndexManager}.</p>
39396      * <p>Floating components <i>do not participate in the Container's layout</i>. Because of this, they are not rendered until you explicitly
39397      * {@link #show} them.</p>
39398      * <p>After rendering, the ownerCt reference is deleted, and the {@link #floatParent} property is set to the found floating ancestor Container.
39399      * If no floating ancestor Container was found the {@link #floatParent} property will not be set.</p>
39400      */
39401     floating: false,
39402
39403     /**
39404      * @cfg {Boolean} toFrontOnShow
39405      * <p>True to automatically call {@link #toFront} when the {@link #show} method is called
39406      * on an already visible, floating component (default is <code>true</code>).</p>
39407      */
39408     toFrontOnShow: true,
39409
39410     /**
39411      * <p>Optional. Only present for {@link #floating} Components after they have been rendered.</p>
39412      * <p>A reference to the ZIndexManager which is managing this Component's z-index.</p>
39413      * <p>The {@link Ext.ZIndexManager ZIndexManager} maintains a stack of floating Component z-indices, and also provides a single modal
39414      * mask which is insert just beneath the topmost visible modal floating Component.</p>
39415      * <p>Floating Components may be {@link #toFront brought to the front} or {@link #toBack sent to the back} of the z-index stack.</p>
39416      * <p>This defaults to the global {@link Ext.WindowManager ZIndexManager} for floating Components that are programatically
39417      * {@link Ext.Component#render rendered}.</p>
39418      * <p>For {@link #floating} Components which are added to a Container, the ZIndexManager is acquired from the first ancestor Container found
39419      * which is floating, or if not found the global {@link Ext.WindowManager ZIndexManager} is used.</p>
39420      * <p>See {@link #floating} and {@link #floatParent}</p>
39421      * @property zIndexManager
39422      * @type Ext.ZIndexManager
39423      */
39424
39425      /**
39426       * <p>Optional. Only present for {@link #floating} Components which were inserted as descendant items of floating Containers.</p>
39427       * <p>Floating Components that are programatically {@link Ext.Component#render rendered} will not have a <code>floatParent</code> property.</p>
39428       * <p>For {@link #floating} Components which are child items of a Container, the floatParent will be the floating ancestor Container which is
39429       * responsible for the base z-index value of all its floating descendants. It provides a {@link Ext.ZIndexManager ZIndexManager} which provides
39430       * z-indexing services for all its descendant floating Components.</p>
39431       * <p>For example, the dropdown {@link Ext.view.BoundList BoundList} of a ComboBox which is in a Window will have the Window as its
39432       * <code>floatParent</code></p>
39433       * <p>See {@link #floating} and {@link #zIndexManager}</p>
39434       * @property floatParent
39435       * @type Ext.Container
39436       */
39437
39438     /**
39439      * @cfg {Mixed} draggable
39440      * <p>Specify as true to make a {@link #floating} Component draggable using the Component's encapsulating element as the drag handle.</p>
39441      * <p>This may also be specified as a config object for the {@link Ext.util.ComponentDragger ComponentDragger} which is instantiated to perform dragging.</p>
39442      * <p>For example to create a Component which may only be dragged around using a certain internal element as the drag handle,
39443      * use the delegate option:</p>
39444      * <code><pre>
39445 new Ext.Component({
39446     constrain: true,
39447     floating:true,
39448     style: {
39449         backgroundColor: '#fff',
39450         border: '1px solid black'
39451     },
39452     html: '&lt;h1 style="cursor:move"&gt;The title&lt;/h1&gt;&lt;p&gt;The content&lt;/p&gt;',
39453     draggable: {
39454         delegate: 'h1'
39455     }
39456 }).show();
39457 </pre></code>
39458      */
39459
39460     /**
39461      * @cfg {Boolean} maintainFlex
39462      * <p><b>Only valid when a sibling element of a {@link Ext.resizer.Splitter Splitter} within a {@link Ext.layout.container.VBox VBox} or
39463      * {@link Ext.layout.container.HBox HBox} layout.</b></p>
39464      * <p>Specifies that if an immediate sibling Splitter is moved, the Component on the <i>other</i> side is resized, and this
39465      * Component maintains its configured {@link Ext.layout.container.Box#flex flex} value.</p>
39466      */
39467
39468     hideMode: 'display',
39469     // Deprecate 5.0
39470     hideParent: false,
39471
39472     ariaRole: 'presentation',
39473
39474     bubbleEvents: [],
39475
39476     actionMode: 'el',
39477     monPropRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
39478
39479     //renderTpl: new Ext.XTemplate(
39480     //    '<div id="{id}" class="{baseCls} {cls} {cmpCls}<tpl if="typeof ui !== \'undefined\'"> {uiBase}-{ui}</tpl>"<tpl if="typeof style !== \'undefined\'"> style="{style}"</tpl>></div>', {
39481     //        compiled: true,
39482     //        disableFormats: true
39483     //    }
39484     //),
39485     constructor: function(config) {
39486         config = config || {};
39487         if (config.initialConfig) {
39488
39489             // Being initialized from an Ext.Action instance...
39490             if (config.isAction) {
39491                 this.baseAction = config;
39492             }
39493             config = config.initialConfig;
39494             // component cloning / action set up
39495         }
39496         else if (config.tagName || config.dom || Ext.isString(config)) {
39497             // element object
39498             config = {
39499                 applyTo: config,
39500                 id: config.id || config
39501             };
39502         }
39503
39504         this.callParent([config]);
39505
39506         // If we were configured from an instance of Ext.Action, (or configured with a baseAction option),
39507         // register this Component as one of its items
39508         if (this.baseAction){
39509             this.baseAction.addComponent(this);
39510         }
39511     },
39512
39513     initComponent: function() {
39514         var me = this;
39515
39516         if (me.listeners) {
39517             me.on(me.listeners);
39518             delete me.listeners;
39519         }
39520         me.enableBubble(me.bubbleEvents);
39521         me.mons = [];
39522     },
39523
39524     // private
39525     afterRender: function() {
39526         var me = this,
39527             resizable = me.resizable;
39528
39529         if (me.floating) {
39530             me.makeFloating(me.floating);
39531         } else {
39532             me.el.setVisibilityMode(Ext.core.Element[me.hideMode.toUpperCase()]);
39533         }
39534
39535         me.setAutoScroll(me.autoScroll);
39536         me.callParent();
39537
39538         if (!(me.x && me.y) && (me.pageX || me.pageY)) {
39539             me.setPagePosition(me.pageX, me.pageY);
39540         }
39541
39542         if (resizable) {
39543             me.initResizable(resizable);
39544         }
39545
39546         if (me.draggable) {
39547             me.initDraggable();
39548         }
39549
39550         me.initAria();
39551     },
39552
39553     initAria: function() {
39554         var actionEl = this.getActionEl(),
39555             role = this.ariaRole;
39556         if (role) {
39557             actionEl.dom.setAttribute('role', role);
39558         }
39559     },
39560
39561     /**
39562      * Sets the overflow on the content element of the component.
39563      * @param {Boolean} scroll True to allow the Component to auto scroll.
39564      * @return {Ext.Component} this
39565      */
39566     setAutoScroll : function(scroll){
39567         var me = this,
39568             targetEl;
39569         scroll = !!scroll;
39570         if (me.rendered) {
39571             targetEl = me.getTargetEl();
39572             targetEl.setStyle('overflow', scroll ? 'auto' : '');
39573             if (scroll && (Ext.isIE6 || Ext.isIE7)) {
39574                 // The scrollable container element must be non-statically positioned or IE6/7 will make
39575                 // positioned children stay in place rather than scrolling with the rest of the content
39576                 targetEl.position();
39577             }
39578         }
39579         me.autoScroll = scroll;
39580         return me;
39581     },
39582
39583     // private
39584     makeFloating : function(cfg){
39585         this.mixins.floating.constructor.call(this, cfg);
39586     },
39587
39588     initResizable: function(resizable) {
39589         resizable = Ext.apply({
39590             target: this,
39591             dynamic: false,
39592             constrainTo: this.constrainTo,
39593             handles: this.resizeHandles
39594         }, resizable);
39595         resizable.target = this;
39596         this.resizer = Ext.create('Ext.resizer.Resizer', resizable);
39597     },
39598
39599     getDragEl: function() {
39600         return this.el;
39601     },
39602
39603     initDraggable: function() {
39604         var me = this,
39605             ddConfig = Ext.applyIf({
39606                 el: this.getDragEl(),
39607                 constrainTo: me.constrainTo || (me.floatParent ? me.floatParent.getTargetEl() : me.el.dom.parentNode)
39608             }, this.draggable);
39609
39610         // Add extra configs if Component is specified to be constrained
39611         if (me.constrain || me.constrainDelegate) {
39612             ddConfig.constrain = me.constrain;
39613             ddConfig.constrainDelegate = me.constrainDelegate;
39614         }
39615
39616         this.dd = Ext.create('Ext.util.ComponentDragger', this, ddConfig);
39617     },
39618
39619     /**
39620      * Sets the left and top of the component.  To set the page XY position instead, use {@link #setPagePosition}.
39621      * This method fires the {@link #move} event.
39622      * @param {Number} left The new left
39623      * @param {Number} top The new top
39624      * @param {Mixed} animate If true, the Component is <i>animated</i> into its new position. You may also pass an animation configuration.
39625      * @return {Ext.Component} this
39626      */
39627     setPosition: function(x, y, animate) {
39628         var me = this,
39629             el = me.el,
39630             to = {},
39631             adj, adjX, adjY, xIsNumber, yIsNumber;
39632
39633         if (Ext.isArray(x)) {
39634             animate = y;
39635             y = x[1];
39636             x = x[0];
39637         }
39638         me.x = x;
39639         me.y = y;
39640
39641         if (!me.rendered) {
39642             return me;
39643         }
39644
39645         adj = me.adjustPosition(x, y);
39646         adjX = adj.x;
39647         adjY = adj.y;
39648         xIsNumber = Ext.isNumber(adjX);
39649         yIsNumber = Ext.isNumber(adjY);
39650
39651         if (xIsNumber || yIsNumber) {
39652             if (animate) {
39653                 if (xIsNumber) {
39654                     to.left = adjX;
39655                 }
39656                 if (yIsNumber) {
39657                     to.top = adjY;
39658                 }
39659
39660                 me.stopAnimation();
39661                 me.animate(Ext.apply({
39662                     duration: 1000,
39663                     listeners: {
39664                         afteranimate: Ext.Function.bind(me.afterSetPosition, me, [adjX, adjY])
39665                     },
39666                     to: to
39667                 }, animate));
39668             }
39669             else {
39670                 if (!xIsNumber) {
39671                     el.setTop(adjY);
39672                 }
39673                 else if (!yIsNumber) {
39674                     el.setLeft(adjX);
39675                 }
39676                 else {
39677                     el.setLeftTop(adjX, adjY);
39678                 }
39679                 me.afterSetPosition(adjX, adjY);
39680             }
39681         }
39682         return me;
39683     },
39684
39685     /**
39686      * @private Template method called after a Component has been positioned.
39687      */
39688     afterSetPosition: function(ax, ay) {
39689         this.onPosition(ax, ay);
39690         this.fireEvent('move', this, ax, ay);
39691     },
39692
39693     showAt: function(x, y, animate) {
39694         // A floating Component is positioned relative to its ownerCt if any.
39695         if (this.floating) {
39696             this.setPosition(x, y, animate);
39697         } else {
39698             this.setPagePosition(x, y, animate);
39699         }
39700         this.show();
39701     },
39702
39703     /**
39704      * Sets the page XY position of the component.  To set the left and top instead, use {@link #setPosition}.
39705      * This method fires the {@link #move} event.
39706      * @param {Number} x The new x position
39707      * @param {Number} y The new y position
39708      * @param {Mixed} animate If passed, the Component is <i>animated</i> into its new position. If this parameter
39709      * is a number, it is used as the animation duration in milliseconds.
39710      * @return {Ext.Component} this
39711      */
39712     setPagePosition: function(x, y, animate) {
39713         var me = this,
39714             p;
39715
39716         if (Ext.isArray(x)) {
39717             y = x[1];
39718             x = x[0];
39719         }
39720         me.pageX = x;
39721         me.pageY = y;
39722         if (me.floating && me.floatParent) {
39723             // Floating Components being positioned in their ownerCt have to be made absolute
39724             p = me.floatParent.getTargetEl().getViewRegion();
39725             if (Ext.isNumber(x) && Ext.isNumber(p.left)) {
39726                 x -= p.left;
39727             }
39728             if (Ext.isNumber(y) && Ext.isNumber(p.top)) {
39729                 y -= p.top;
39730             }
39731             me.setPosition(x, y, animate);
39732         }
39733         else {
39734             p = me.el.translatePoints(x, y);
39735             me.setPosition(p.left, p.top, animate);
39736         }
39737         return me;
39738     },
39739
39740     /**
39741      * Gets the current box measurements of the component's underlying element.
39742      * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
39743      * @return {Object} box An object in the format {x, y, width, height}
39744      */
39745     getBox : function(local){
39746         var pos = this.getPosition(local);
39747         var s = this.getSize();
39748         s.x = pos[0];
39749         s.y = pos[1];
39750         return s;
39751     },
39752
39753     /**
39754      * Sets the current box measurements of the component's underlying element.
39755      * @param {Object} box An object in the format {x, y, width, height}
39756      * @return {Ext.Component} this
39757      */
39758     updateBox : function(box){
39759         this.setSize(box.width, box.height);
39760         this.setPagePosition(box.x, box.y);
39761         return this;
39762     },
39763
39764     // Include margins
39765     getOuterSize: function() {
39766         var el = this.el;
39767         return {
39768             width: el.getWidth() + el.getMargin('lr'),
39769             height: el.getHeight() + el.getMargin('tb')
39770         };
39771     },
39772
39773     // private
39774     adjustSize: function(w, h) {
39775         if (this.autoWidth) {
39776             w = 'auto';
39777         }
39778
39779         if (this.autoHeight) {
39780             h = 'auto';
39781         }
39782
39783         return {
39784             width: w,
39785             height: h
39786         };
39787     },
39788
39789     // private
39790     adjustPosition: function(x, y) {
39791
39792         // Floating Components being positioned in their ownerCt have to be made absolute
39793         if (this.floating && this.floatParent) {
39794             var o = this.floatParent.getTargetEl().getViewRegion();
39795             x += o.left;
39796             y += o.top;
39797         }
39798
39799         return {
39800             x: x,
39801             y: y
39802         };
39803     },
39804
39805     /**
39806      * Gets the current XY position of the component's underlying element.
39807      * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
39808      * @return {Array} The XY position of the element (e.g., [100, 200])
39809      */
39810     getPosition: function(local) {
39811         var el = this.el,
39812             xy;
39813
39814         if (local === true) {
39815             return [el.getLeft(true), el.getTop(true)];
39816         }
39817         xy = this.xy || el.getXY();
39818
39819         // Floating Components in an ownerCt have to have their positions made relative
39820         if (this.floating && this.floatParent) {
39821             var o = this.floatParent.getTargetEl().getViewRegion();
39822             xy[0] -= o.left;
39823             xy[1] -= o.top;
39824         }
39825         return xy;
39826     },
39827
39828     // Todo: add in xtype prefix support
39829     getId: function() {
39830         return this.id || (this.id = (this.getXType() || 'ext-comp') + '-' + this.getAutoId());
39831     },
39832
39833     onEnable: function() {
39834         var actionEl = this.getActionEl();
39835         actionEl.dom.removeAttribute('aria-disabled');
39836         actionEl.dom.disabled = false;
39837         this.callParent();
39838     },
39839
39840     onDisable: function() {
39841         var actionEl = this.getActionEl();
39842         actionEl.dom.setAttribute('aria-disabled', true);
39843         actionEl.dom.disabled = true;
39844         this.callParent();
39845     },
39846
39847     /**
39848      * <p>Shows this Component, rendering it first if {@link #autoRender} or {{@link "floating} are <code>true</code>.</p>
39849      * <p>After being shown, a {@link #floating} Component (such as a {@link Ext.window.Window}), is activated it and brought to the front of
39850      * its {@link #ZIndexManager z-index stack}.</p>
39851      * @param {String/Element} animateTarget Optional, and <b>only valid for {@link #floating} Components such as
39852      * {@link Ext.window.Window Window}s or {@link Ext.tip.ToolTip ToolTip}s, or regular Components which have been configured
39853      * with <code>floating: true</code>.</b> The target from which the Component should
39854      * animate from while opening (defaults to null with no animation)
39855      * @param {Function} callback (optional) A callback function to call after the Component is displayed. Only necessary if animation was specified.
39856      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to this Component.
39857      * @return {Component} this
39858      */
39859     show: function(animateTarget, cb, scope) {
39860         if (this.rendered && this.isVisible()) {
39861             if (this.toFrontOnShow && this.floating) {
39862                 this.toFront();
39863             }
39864         } else if (this.fireEvent('beforeshow', this) !== false) {
39865             this.hidden = false;
39866
39867             // Render on first show if there is an autoRender config, or if this is a floater (Window, Menu, BoundList etc).
39868             if (!this.rendered && (this.autoRender || this.floating)) {
39869                 this.doAutoRender();
39870             }
39871             if (this.rendered) {
39872                 this.beforeShow();
39873                 this.onShow.apply(this, arguments);
39874
39875                 // Notify any owning Container unless it's suspended.
39876                 // Floating Components do not participate in layouts.
39877                 if (this.ownerCt && !this.floating && !(this.ownerCt.suspendLayout || this.ownerCt.layout.layoutBusy)) {
39878                     this.ownerCt.doLayout();
39879                 }
39880                 this.afterShow.apply(this, arguments);
39881             }
39882         }
39883         return this;
39884     },
39885
39886     beforeShow: Ext.emptyFn,
39887
39888     // Private. Override in subclasses where more complex behaviour is needed.
39889     onShow: function() {
39890         var me = this;
39891
39892         me.el.show();
39893         if (this.floating && this.constrain) {
39894             this.doConstrain();
39895         }
39896         me.callParent(arguments);
39897     },
39898
39899     afterShow: function(animateTarget, cb, scope) {
39900         var me = this,
39901             fromBox,
39902             toBox,
39903             ghostPanel;
39904
39905         // Default to configured animate target if none passed
39906         animateTarget = animateTarget || me.animateTarget;
39907
39908         // Need to be able to ghost the Component
39909         if (!me.ghost) {
39910             animateTarget = null;
39911         }
39912         // If we're animating, kick of an animation of the ghost from the target to the *Element* current box
39913         if (animateTarget) {
39914             animateTarget = animateTarget.el ? animateTarget.el : Ext.get(animateTarget);
39915             toBox = me.el.getBox();
39916             fromBox = animateTarget.getBox();
39917             fromBox.width += 'px';
39918             fromBox.height += 'px';
39919             toBox.width += 'px';
39920             toBox.height += 'px';
39921             me.el.addCls(Ext.baseCSSPrefix + 'hide-offsets');
39922             ghostPanel = me.ghost();
39923             ghostPanel.el.stopAnimation();
39924
39925             ghostPanel.el.animate({
39926                 from: fromBox,
39927                 to: toBox,
39928                 listeners: {
39929                     afteranimate: function() {
39930                         delete ghostPanel.componentLayout.lastComponentSize;
39931                         me.unghost();
39932                         me.el.removeCls(Ext.baseCSSPrefix + 'hide-offsets');
39933                         if (me.floating) {
39934                             me.toFront();
39935                         }
39936                         Ext.callback(cb, scope || me);
39937                     }
39938                 }
39939             });
39940         }
39941         else {
39942             if (me.floating) {
39943                 me.toFront();
39944             }
39945             Ext.callback(cb, scope || me);
39946         }
39947         me.fireEvent('show', me);
39948     },
39949
39950     /**
39951      * Hides this Component, setting it to invisible using the configured {@link #hideMode}.
39952      * @param {String/Element/Component} animateTarget Optional, and <b>only valid for {@link #floating} Components such as
39953      * {@link Ext.window.Window Window}s or {@link Ext.tip.ToolTip ToolTip}s, or regular Components which have been configured
39954      * with <code>floating: true</code>.</b>.
39955      * The target to which the Component should animate while hiding (defaults to null with no animation)
39956      * @param {Function} callback (optional) A callback function to call after the Component is hidden.
39957      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to this Component.
39958      * @return {Ext.Component} this
39959      */
39960     hide: function() {
39961
39962         // Clear the flag which is set if a floatParent was hidden while this is visible.
39963         // If a hide operation was subsequently called, that pending show must be hidden.
39964         this.showOnParentShow = false;
39965
39966         if (!(this.rendered && !this.isVisible()) && this.fireEvent('beforehide', this) !== false) {
39967             this.hidden = true;
39968             if (this.rendered) {
39969                 this.onHide.apply(this, arguments);
39970
39971                 // Notify any owning Container unless it's suspended.
39972                 // Floating Components do not participate in layouts.
39973                 if (this.ownerCt && !this.floating && !(this.ownerCt.suspendLayout || this.ownerCt.layout.layoutBusy)) {
39974                     this.ownerCt.doLayout();
39975                 }
39976             }
39977         }
39978         return this;
39979     },
39980
39981     // Possibly animate down to a target element.
39982     onHide: function(animateTarget, cb, scope) {
39983         var me = this,
39984             ghostPanel,
39985             toBox;
39986
39987         // Default to configured animate target if none passed
39988         animateTarget = animateTarget || me.animateTarget;
39989
39990         // Need to be able to ghost the Component
39991         if (!me.ghost) {
39992             animateTarget = null;
39993         }
39994         // If we're animating, kick off an animation of the ghost down to the target
39995         if (animateTarget) {
39996             animateTarget = animateTarget.el ? animateTarget.el : Ext.get(animateTarget);
39997             ghostPanel = me.ghost();
39998             ghostPanel.el.stopAnimation();
39999             toBox = animateTarget.getBox();
40000             toBox.width += 'px';
40001             toBox.height += 'px';
40002             ghostPanel.el.animate({
40003                 to: toBox,
40004                 listeners: {
40005                     afteranimate: function() {
40006                         delete ghostPanel.componentLayout.lastComponentSize;
40007                         ghostPanel.el.hide();
40008                         me.afterHide(cb, scope);
40009                     }
40010                 }
40011             });
40012         }
40013         me.el.hide();
40014         if (!animateTarget) {
40015             me.afterHide(cb, scope);
40016         }
40017     },
40018
40019     afterHide: function(cb, scope) {
40020         Ext.callback(cb, scope || this);
40021         this.fireEvent('hide', this);
40022     },
40023
40024     /**
40025      * @private
40026      * Template method to contribute functionality at destroy time.
40027      */
40028     onDestroy: function() {
40029         var me = this;
40030
40031         // Ensure that any ancillary components are destroyed.
40032         if (me.rendered) {
40033             Ext.destroy(
40034                 me.proxy,
40035                 me.resizer
40036             );
40037             // Different from AbstractComponent
40038             if (me.actionMode == 'container' || me.removeMode == 'container') {
40039                 me.container.remove();
40040             }
40041         }
40042         me.callParent();
40043     },
40044
40045     deleteMembers: function() {
40046         var args = arguments,
40047             len = args.length,
40048             i = 0;
40049         for (; i < len; ++i) {
40050             delete this[args[i]];
40051         }
40052     },
40053
40054     /**
40055      * Try to focus this component.
40056      * @param {Boolean} selectText (optional) If applicable, true to also select the text in this component
40057      * @param {Boolean/Number} delay (optional) Delay the focus this number of milliseconds (true for 10 milliseconds).
40058      * @return {Ext.Component} this
40059      */
40060     focus: function(selectText, delay) {
40061         var me = this,
40062                 focusEl;
40063
40064         if (delay) {
40065             me.focusTask.delay(Ext.isNumber(delay) ? delay: 10, null, me, [selectText, false]);
40066             return me;
40067         }
40068
40069         if (me.rendered && !me.isDestroyed) {
40070             // getFocusEl could return a Component.
40071             focusEl = me.getFocusEl();
40072             focusEl.focus();
40073             if (focusEl.dom && selectText === true) {
40074                 focusEl.dom.select();
40075             }
40076
40077             // Focusing a floating Component brings it to the front of its stack.
40078             // this is performed by its zIndexManager. Pass preventFocus true to avoid recursion.
40079             if (me.floating) {
40080                 me.toFront(true);
40081             }
40082         }
40083         return me;
40084     },
40085
40086     /**
40087      * @private
40088      * Returns the focus holder element associated with this Component. By default, this is the Component's encapsulating
40089      * element. Subclasses which use embedded focusable elements (such as Window and Button) should override this for use
40090      * by the {@link #focus} method.
40091      * @returns {Ext.core.Element} the focus holing element.
40092      */
40093     getFocusEl: function() {
40094         return this.el;
40095     },
40096
40097     // private
40098     blur: function() {
40099         if (this.rendered) {
40100             this.getFocusEl().blur();
40101         }
40102         return this;
40103     },
40104
40105     getEl: function() {
40106         return this.el;
40107     },
40108
40109     // Deprecate 5.0
40110     getResizeEl: function() {
40111         return this.el;
40112     },
40113
40114     // Deprecate 5.0
40115     getPositionEl: function() {
40116         return this.el;
40117     },
40118
40119     // Deprecate 5.0
40120     getActionEl: function() {
40121         return this.el;
40122     },
40123
40124     // Deprecate 5.0
40125     getVisibilityEl: function() {
40126         return this.el;
40127     },
40128
40129     // Deprecate 5.0
40130     onResize: Ext.emptyFn,
40131
40132     // private
40133     getBubbleTarget: function() {
40134         return this.ownerCt;
40135     },
40136
40137     // private
40138     getContentTarget: function() {
40139         return this.el;
40140     },
40141
40142     /**
40143      * Clone the current component using the original config values passed into this instance by default.
40144      * @param {Object} overrides A new config containing any properties to override in the cloned version.
40145      * An id property can be passed on this object, otherwise one will be generated to avoid duplicates.
40146      * @return {Ext.Component} clone The cloned copy of this component
40147      */
40148     cloneConfig: function(overrides) {
40149         overrides = overrides || {};
40150         var id = overrides.id || Ext.id();
40151         var cfg = Ext.applyIf(overrides, this.initialConfig);
40152         cfg.id = id;
40153
40154         var self = Ext.getClass(this);
40155
40156         // prevent dup id
40157         return new self(cfg);
40158     },
40159
40160     /**
40161      * Gets the xtype for this component as registered with {@link Ext.ComponentManager}. For a list of all
40162      * available xtypes, see the {@link Ext.Component} header. Example usage:
40163      * <pre><code>
40164 var t = new Ext.form.field.Text();
40165 alert(t.getXType());  // alerts 'textfield'
40166 </code></pre>
40167      * @return {String} The xtype
40168      */
40169     getXType: function() {
40170         return this.self.xtype;
40171     },
40172
40173     /**
40174      * Find a container above this component at any level by a custom function. If the passed function returns
40175      * true, the container will be returned.
40176      * @param {Function} fn The custom function to call with the arguments (container, this component).
40177      * @return {Ext.container.Container} The first Container for which the custom function returns true
40178      */
40179     findParentBy: function(fn) {
40180         var p;
40181
40182         // Iterate up the ownerCt chain until there's no ownerCt, or we find an ancestor which matches using the selector function.
40183         for (p = this.ownerCt; p && !fn(p, this); p = p.ownerCt);
40184         return p || null;
40185     },
40186
40187     /**
40188      * <p>Find a container above this component at any level by xtype or class</p>
40189      * <p>See also the {@link Ext.Component#up up} method.</p>
40190      * @param {String/Class} xtype The xtype string for a component, or the class of the component directly
40191      * @return {Ext.container.Container} The first Container which matches the given xtype or class
40192      */
40193     findParentByType: function(xtype) {
40194         return Ext.isFunction(xtype) ?
40195             this.findParentBy(function(p) {
40196                 return p.constructor === xtype;
40197             })
40198         :
40199             this.up(xtype);
40200     },
40201
40202     /**
40203      * Bubbles up the component/container heirarchy, calling the specified function with each component. The scope (<i>this</i>) of
40204      * function call will be the scope provided or the current component. The arguments to the function
40205      * will be the args provided or the current component. If the function returns false at any point,
40206      * the bubble is stopped.
40207      * @param {Function} fn The function to call
40208      * @param {Object} scope (optional) The scope of the function (defaults to current node)
40209      * @param {Array} args (optional) The args to call the function with (default to passing the current component)
40210      * @return {Ext.Component} this
40211      */
40212     bubble: function(fn, scope, args) {
40213         var p = this;
40214         while (p) {
40215             if (fn.apply(scope || p, args || [p]) === false) {
40216                 break;
40217             }
40218             p = p.ownerCt;
40219         }
40220         return this;
40221     },
40222
40223     getProxy: function() {
40224         if (!this.proxy) {
40225             this.proxy = this.el.createProxy(Ext.baseCSSPrefix + 'proxy-el', Ext.getBody(), true);
40226         }
40227         return this.proxy;
40228     }
40229
40230 }, function() {
40231
40232     // A single focus delayer for all Components.
40233     this.prototype.focusTask = Ext.create('Ext.util.DelayedTask', this.prototype.focus);
40234
40235 });
40236
40237 /**
40238 * @class Ext.layout.container.Container
40239 * @extends Ext.layout.container.AbstractContainer
40240 * @private
40241 * <p>This class is intended to be extended or created via the <tt><b>{@link Ext.container.Container#layout layout}</b></tt>
40242 * configuration property.  See <tt><b>{@link Ext.container.Container#layout}</b></tt> for additional details.</p>
40243 */
40244 Ext.define('Ext.layout.container.Container', {
40245
40246     /* Begin Definitions */
40247
40248     extend: 'Ext.layout.container.AbstractContainer',
40249     alternateClassName: 'Ext.layout.ContainerLayout',
40250     
40251     /* End Definitions */
40252
40253     layoutItem: function(item, box) {
40254         box = box || {};
40255         if (item.componentLayout.initialized !== true) {
40256             this.setItemSize(item, box.width || item.width || undefined, box.height || item.height || undefined);
40257             // item.doComponentLayout(box.width || item.width || undefined, box.height || item.height || undefined);
40258         }
40259     },
40260
40261     getLayoutTargetSize : function() {
40262         var target = this.getTarget(),
40263             ret;
40264
40265         if (target) {
40266             ret = target.getViewSize();
40267
40268             // IE in will sometimes return a width of 0 on the 1st pass of getViewSize.
40269             // Use getStyleSize to verify the 0 width, the adjustment pass will then work properly
40270             // with getViewSize
40271             if (Ext.isIE && ret.width == 0){
40272                 ret = target.getStyleSize();
40273             }
40274
40275             ret.width -= target.getPadding('lr');
40276             ret.height -= target.getPadding('tb');
40277         }
40278         return ret;
40279     },
40280
40281     beforeLayout: function() {
40282         if (this.owner.beforeLayout(arguments) !== false) {
40283             return this.callParent(arguments);
40284         }
40285         else {
40286             return false;
40287         }
40288     },
40289
40290     afterLayout: function() {
40291         this.owner.afterLayout(arguments);
40292         this.callParent(arguments);
40293     },
40294
40295     /**
40296      * @protected
40297      * Returns all items that are rendered
40298      * @return {Array} All matching items
40299      */
40300     getRenderedItems: function() {
40301         var me = this,
40302             target = me.getTarget(),
40303             items = me.getLayoutItems(),
40304             ln = items.length,
40305             renderedItems = [],
40306             i, item;
40307
40308         for (i = 0; i < ln; i++) {
40309             item = items[i];
40310             if (item.rendered && me.isValidParent(item, target, i)) {
40311                 renderedItems.push(item);
40312             }
40313         }
40314
40315         return renderedItems;
40316     },
40317
40318     /**
40319      * @protected
40320      * Returns all items that are both rendered and visible
40321      * @return {Array} All matching items
40322      */
40323     getVisibleItems: function() {
40324         var target   = this.getTarget(),
40325             items = this.getLayoutItems(),
40326             ln = items.length,
40327             visibleItems = [],
40328             i, item;
40329
40330         for (i = 0; i < ln; i++) {
40331             item = items[i];
40332             if (item.rendered && this.isValidParent(item, target, i) && item.hidden !== true) {
40333                 visibleItems.push(item);
40334             }
40335         }
40336
40337         return visibleItems;
40338     }
40339 });
40340 /**
40341  * @class Ext.layout.container.Auto
40342  * @extends Ext.layout.container.Container
40343  *
40344  * <p>The AutoLayout is the default layout manager delegated by {@link Ext.container.Container} to
40345  * render any child Components when no <tt>{@link Ext.container.Container#layout layout}</tt> is configured into
40346  * a <tt>{@link Ext.container.Container Container}.</tt>.  AutoLayout provides only a passthrough of any layout calls
40347  * to any child containers.</p>
40348  * {@img Ext.layout.container.Auto/Ext.layout.container.Auto.png Ext.layout.container.Auto container layout}
40349  * Example usage:
40350         Ext.create('Ext.Panel', {
40351                 width: 500,
40352                 height: 280,
40353                 title: "AutoLayout Panel",
40354                 layout: 'auto',
40355                 renderTo: document.body,
40356                 items: [{
40357                         xtype: 'panel',
40358                         title: 'Top Inner Panel',
40359                         width: '75%',
40360                         height: 90
40361                 },{
40362                         xtype: 'panel',
40363                         title: 'Bottom Inner Panel',
40364                         width: '75%',
40365                         height: 90
40366                 }]
40367         });
40368  */
40369
40370 Ext.define('Ext.layout.container.Auto', {
40371
40372     /* Begin Definitions */
40373
40374     alias: ['layout.auto', 'layout.autocontainer'],
40375
40376     extend: 'Ext.layout.container.Container',
40377
40378     /* End Definitions */
40379
40380     type: 'autocontainer',
40381
40382     fixedLayout: false,
40383
40384     bindToOwnerCtComponent: true,
40385
40386     // @private
40387     onLayout : function(owner, target) {
40388         var me = this,
40389             items = me.getLayoutItems(),
40390             ln = items.length,
40391             i;
40392
40393         // Ensure the Container is only primed with the clear element if there are child items.
40394         if (ln) {
40395             // Auto layout uses natural HTML flow to arrange the child items.
40396             // To ensure that all browsers (I'm looking at you IE!) add the bottom margin of the last child to the
40397             // containing element height, we create a zero-sized element with style clear:both to force a "new line"
40398             if (!me.clearEl) {
40399                 me.clearEl = me.getRenderTarget().createChild({
40400                     cls: Ext.baseCSSPrefix + 'clear',
40401                     role: 'presentation'
40402                 });
40403             }
40404
40405             // Auto layout allows CSS to size its child items.
40406             for (i = 0; i < ln; i++) {
40407                 me.setItemSize(items[i]);
40408             }
40409         }
40410     }
40411 });
40412 /**
40413  * @class Ext.container.AbstractContainer
40414  * @extends Ext.Component
40415  * <p>An abstract base class which provides shared methods for Containers across the Sencha product line.</p>
40416  * Please refer to sub class's documentation
40417  */
40418 Ext.define('Ext.container.AbstractContainer', {
40419
40420     /* Begin Definitions */
40421
40422     extend: 'Ext.Component',
40423
40424     requires: [
40425         'Ext.util.MixedCollection',
40426         'Ext.layout.container.Auto',
40427         'Ext.ZIndexManager'
40428     ],
40429
40430     /* End Definitions */
40431     /**
40432      * @cfg {String/Object} layout
40433      * <p><b>*Important</b>: In order for child items to be correctly sized and
40434      * positioned, typically a layout manager <b>must</b> be specified through
40435      * the <code>layout</code> configuration option.</p>
40436      * <br><p>The sizing and positioning of child {@link #items} is the responsibility of
40437      * the Container's layout manager which creates and manages the type of layout
40438      * you have in mind.  For example:</p>
40439      * <p>If the {@link #layout} configuration is not explicitly specified for
40440      * a general purpose container (e.g. Container or Panel) the
40441      * {@link Ext.layout.container.Auto default layout manager} will be used
40442      * which does nothing but render child components sequentially into the
40443      * Container (no sizing or positioning will be performed in this situation).</p>
40444      * <br><p><b><code>layout</code></b> may be specified as either as an Object or
40445      * as a String:</p><div><ul class="mdetail-params">
40446      *
40447      * <li><u>Specify as an Object</u></li>
40448      * <div><ul class="mdetail-params">
40449      * <li>Example usage:</li>
40450      * <pre><code>
40451 layout: {
40452     type: 'vbox',
40453     align: 'left'
40454 }
40455        </code></pre>
40456      *
40457      * <li><code><b>type</b></code></li>
40458      * <br/><p>The layout type to be used for this container.  If not specified,
40459      * a default {@link Ext.layout.container.Auto} will be created and used.</p>
40460      * <br/><p>Valid layout <code>type</code> values are:</p>
40461      * <div class="sub-desc"><ul class="mdetail-params">
40462      * <li><code><b>{@link Ext.layout.container.Auto Auto}</b></code> &nbsp;&nbsp;&nbsp; <b>Default</b></li>
40463      * <li><code><b>{@link Ext.layout.container.Card card}</b></code></li>
40464      * <li><code><b>{@link Ext.layout.container.Fit fit}</b></code></li>
40465      * <li><code><b>{@link Ext.layout.container.HBox hbox}</b></code></li>
40466      * <li><code><b>{@link Ext.layout.container.VBox vbox}</b></code></li>
40467      * <li><code><b>{@link Ext.layout.container.Anchor anchor}</b></code></li>
40468      * <li><code><b>{@link Ext.layout.container.Table table}</b></code></li>
40469      * </ul></div>
40470      *
40471      * <li>Layout specific configuration properties</li>
40472      * <br/><p>Additional layout specific configuration properties may also be
40473      * specified. For complete details regarding the valid config options for
40474      * each layout type, see the layout class corresponding to the <code>type</code>
40475      * specified.</p>
40476      *
40477      * </ul></div>
40478      *
40479      * <li><u>Specify as a String</u></li>
40480      * <div><ul class="mdetail-params">
40481      * <li>Example usage:</li>
40482      * <pre><code>
40483 layout: {
40484     type: 'vbox',
40485     padding: '5',
40486     align: 'left'
40487 }
40488        </code></pre>
40489      * <li><code><b>layout</b></code></li>
40490      * <br/><p>The layout <code>type</code> to be used for this container (see list
40491      * of valid layout type values above).</p><br/>
40492      * <br/><p>Additional layout specific configuration properties. For complete
40493      * details regarding the valid config options for each layout type, see the
40494      * layout class corresponding to the <code>layout</code> specified.</p>
40495      * </ul></div></ul></div>
40496      */
40497
40498     /**
40499      * @cfg {String/Number} activeItem
40500      * A string component id or the numeric index of the component that should be initially activated within the
40501      * container's layout on render.  For example, activeItem: 'item-1' or activeItem: 0 (index 0 = the first
40502      * item in the container's collection).  activeItem only applies to layout styles that can display
40503      * items one at a time (like {@link Ext.layout.container.Card} and {@link Ext.layout.container.Fit}).
40504      */
40505     /**
40506      * @cfg {Object/Array} items
40507      * <p>A single item, or an array of child Components to be added to this container</p>
40508      * <p><b>Unless configured with a {@link #layout}, a Container simply renders child Components serially into
40509      * its encapsulating element and performs no sizing or positioning upon them.</b><p>
40510      * <p>Example:</p>
40511      * <pre><code>
40512 // specifying a single item
40513 items: {...},
40514 layout: 'fit',    // The single items is sized to fit
40515
40516 // specifying multiple items
40517 items: [{...}, {...}],
40518 layout: 'hbox', // The items are arranged horizontally
40519        </code></pre>
40520      * <p>Each item may be:</p>
40521      * <ul>
40522      * <li>A {@link Ext.Component Component}</li>
40523      * <li>A Component configuration object</li>
40524      * </ul>
40525      * <p>If a configuration object is specified, the actual type of Component to be
40526      * instantiated my be indicated by using the {@link Ext.Component#xtype xtype} option.</p>
40527      * <p>Every Component class has its own {@link Ext.Component#xtype xtype}.</p>
40528      * <p>If an {@link Ext.Component#xtype xtype} is not explicitly
40529      * specified, the {@link #defaultType} for the Container is used, which by default is usually <code>panel</code>.</p>
40530      * <p><b>Notes</b>:</p>
40531      * <p>Ext uses lazy rendering. Child Components will only be rendered
40532      * should it become necessary. Items are automatically laid out when they are first
40533      * shown (no sizing is done while hidden), or in response to a {@link #doLayout} call.</p>
40534      * <p>Do not specify <code>{@link Ext.panel.Panel#contentEl contentEl}</code> or 
40535      * <code>{@link Ext.panel.Panel#html html}</code> with <code>items</code>.</p>
40536      */
40537     /**
40538      * @cfg {Object|Function} defaults
40539      * <p>This option is a means of applying default settings to all added items whether added through the {@link #items}
40540      * config or via the {@link #add} or {@link #insert} methods.</p>
40541      * <p>If an added item is a config object, and <b>not</b> an instantiated Component, then the default properties are
40542      * unconditionally applied. If the added item <b>is</b> an instantiated Component, then the default properties are
40543      * applied conditionally so as not to override existing properties in the item.</p>
40544      * <p>If the defaults option is specified as a function, then the function will be called using this Container as the
40545      * scope (<code>this</code> reference) and passing the added item as the first parameter. Any resulting object
40546      * from that call is then applied to the item as default properties.</p>
40547      * <p>For example, to automatically apply padding to the body of each of a set of
40548      * contained {@link Ext.panel.Panel} items, you could pass: <code>defaults: {bodyStyle:'padding:15px'}</code>.</p>
40549      * <p>Usage:</p><pre><code>
40550 defaults: {               // defaults are applied to items, not the container
40551     autoScroll:true
40552 },
40553 items: [
40554     {
40555         xtype: 'panel',   // defaults <b>do not</b> have precedence over
40556         id: 'panel1',     // options in config objects, so the defaults
40557         autoScroll: false // will not be applied here, panel1 will be autoScroll:false
40558     },
40559     new Ext.panel.Panel({       // defaults <b>do</b> have precedence over options
40560         id: 'panel2',     // options in components, so the defaults
40561         autoScroll: false // will be applied here, panel2 will be autoScroll:true.
40562     })
40563 ]</code></pre>
40564      */
40565
40566     /** @cfg {Boolean} suspendLayout
40567      * If true, suspend calls to doLayout.  Useful when batching multiple adds to a container and not passing them
40568      * as multiple arguments or an array.
40569      */
40570     suspendLayout : false,
40571
40572     /** @cfg {Boolean} autoDestroy
40573      * If true the container will automatically destroy any contained component that is removed from it, else
40574      * destruction must be handled manually.
40575      * Defaults to true.
40576      */
40577     autoDestroy : true,
40578
40579      /** @cfg {String} defaultType
40580       * <p>The default {@link Ext.Component xtype} of child Components to create in this Container when
40581       * a child item is specified as a raw configuration object, rather than as an instantiated Component.</p>
40582       * <p>Defaults to <code>'panel'</code>.</p>
40583       */
40584     defaultType: 'panel',
40585
40586     isContainer : true,
40587
40588     baseCls: Ext.baseCSSPrefix + 'container',
40589
40590     /**
40591      * @cfg {Array} bubbleEvents
40592      * <p>An array of events that, when fired, should be bubbled to any parent container.
40593      * See {@link Ext.util.Observable#enableBubble}.
40594      * Defaults to <code>['add', 'remove']</code>.
40595      */
40596     bubbleEvents: ['add', 'remove'],
40597     
40598     // @private
40599     initComponent : function(){
40600         var me = this;
40601         me.addEvents(
40602             /**
40603              * @event afterlayout
40604              * Fires when the components in this container are arranged by the associated layout manager.
40605              * @param {Ext.container.Container} this
40606              * @param {ContainerLayout} layout The ContainerLayout implementation for this container
40607              */
40608             'afterlayout',
40609             /**
40610              * @event beforeadd
40611              * Fires before any {@link Ext.Component} is added or inserted into the container.
40612              * A handler can return false to cancel the add.
40613              * @param {Ext.container.Container} this
40614              * @param {Ext.Component} component The component being added
40615              * @param {Number} index The index at which the component will be added to the container's items collection
40616              */
40617             'beforeadd',
40618             /**
40619              * @event beforeremove
40620              * Fires before any {@link Ext.Component} is removed from the container.  A handler can return
40621              * false to cancel the remove.
40622              * @param {Ext.container.Container} this
40623              * @param {Ext.Component} component The component being removed
40624              */
40625             'beforeremove',
40626             /**
40627              * @event add
40628              * @bubbles
40629              * Fires after any {@link Ext.Component} is added or inserted into the container.
40630              * @param {Ext.container.Container} this
40631              * @param {Ext.Component} component The component that was added
40632              * @param {Number} index The index at which the component was added to the container's items collection
40633              */
40634             'add',
40635             /**
40636              * @event remove
40637              * @bubbles
40638              * Fires after any {@link Ext.Component} is removed from the container.
40639              * @param {Ext.container.Container} this
40640              * @param {Ext.Component} component The component that was removed
40641              */
40642             'remove',
40643             /**
40644              * @event beforecardswitch
40645              * Fires before this container switches the active card. This event
40646              * is only available if this container uses a CardLayout. Note that
40647              * TabPanel and Carousel both get a CardLayout by default, so both
40648              * will have this event.
40649              * A handler can return false to cancel the card switch.
40650              * @param {Ext.container.Container} this
40651              * @param {Ext.Component} newCard The card that will be switched to
40652              * @param {Ext.Component} oldCard The card that will be switched from
40653              * @param {Number} index The index of the card that will be switched to
40654              * @param {Boolean} animated True if this cardswitch will be animated
40655              */
40656             'beforecardswitch',
40657             /**
40658              * @event cardswitch
40659              * Fires after this container switches the active card. If the card
40660              * is switched using an animation, this event will fire after the
40661              * animation has finished. This event is only available if this container
40662              * uses a CardLayout. Note that TabPanel and Carousel both get a CardLayout
40663              * by default, so both will have this event.
40664              * @param {Ext.container.Container} this
40665              * @param {Ext.Component} newCard The card that has been switched to
40666              * @param {Ext.Component} oldCard The card that has been switched from
40667              * @param {Number} index The index of the card that has been switched to
40668              * @param {Boolean} animated True if this cardswitch was animated
40669              */
40670             'cardswitch'
40671         );
40672
40673         // layoutOnShow stack
40674         me.layoutOnShow = Ext.create('Ext.util.MixedCollection');
40675         me.callParent();
40676         me.initItems();
40677     },
40678
40679     // @private
40680     initItems : function() {
40681         var me = this,
40682             items = me.items;
40683
40684         /**
40685          * The MixedCollection containing all the child items of this container.
40686          * @property items
40687          * @type Ext.util.MixedCollection
40688          */
40689         me.items = Ext.create('Ext.util.MixedCollection', false, me.getComponentId);
40690
40691         if (items) {
40692             if (!Ext.isArray(items)) {
40693                 items = [items];
40694             }
40695
40696             me.add(items);
40697         }
40698     },
40699
40700     // @private
40701     afterRender : function() {
40702         this.getLayout();
40703         this.callParent();
40704     },
40705
40706     // @private
40707     setLayout : function(layout) {
40708         var currentLayout = this.layout;
40709
40710         if (currentLayout && currentLayout.isLayout && currentLayout != layout) {
40711             currentLayout.setOwner(null);
40712         }
40713
40714         this.layout = layout;
40715         layout.setOwner(this);
40716     },
40717
40718     /**
40719      * Returns the {@link Ext.layout.container.AbstractContainer layout} instance currently associated with this Container.
40720      * If a layout has not been instantiated yet, that is done first
40721      * @return {Ext.layout.container.AbstractContainer} The layout
40722      */
40723     getLayout : function() {
40724         var me = this;
40725         if (!me.layout || !me.layout.isLayout) {
40726             me.setLayout(Ext.layout.Layout.create(me.layout, 'autocontainer'));
40727         }
40728
40729         return me.layout;
40730     },
40731
40732     /**
40733      * Manually force this container's layout to be recalculated.  The framwork uses this internally to refresh layouts
40734      * form most cases.
40735      * @return {Ext.container.Container} this
40736      */
40737     doLayout : function() {
40738         var me = this,
40739             layout = me.getLayout();
40740
40741         if (me.rendered && layout && !me.suspendLayout) {
40742             // If either dimension is being auto-set, then it requires a ComponentLayout to be run.
40743             if ((!Ext.isNumber(me.width) || !Ext.isNumber(me.height)) && me.componentLayout.type !== 'autocomponent') {
40744                 // Only run the ComponentLayout if it is not already in progress
40745                 if (me.componentLayout.layoutBusy !== true) {
40746                     me.doComponentLayout();
40747                     if (me.componentLayout.layoutCancelled === true) {
40748                         layout.layout();
40749                     }
40750                 }
40751             }
40752             // Both dimensions defined, run a ContainerLayout
40753             else {
40754                 // Only run the ContainerLayout if it is not already in progress
40755                 if (layout.layoutBusy !== true) {
40756                     layout.layout();
40757                 }
40758             }
40759         }
40760
40761         return me;
40762     },
40763
40764     // @private
40765     afterLayout : function(layout) {
40766         this.fireEvent('afterlayout', this, layout);
40767     },
40768
40769     // @private
40770     prepareItems : function(items, applyDefaults) {
40771         if (!Ext.isArray(items)) {
40772             items = [items];
40773         }
40774
40775         // Make sure defaults are applied and item is initialized
40776         var i = 0,
40777             len = items.length,
40778             item;
40779
40780         for (; i < len; i++) {
40781             item = items[i];
40782             if (applyDefaults) {
40783                 item = this.applyDefaults(item);
40784             }
40785             items[i] = this.lookupComponent(item);
40786         }
40787         return items;
40788     },
40789
40790     // @private
40791     applyDefaults : function(config) {
40792         var defaults = this.defaults;
40793
40794         if (defaults) {
40795             if (Ext.isFunction(defaults)) {
40796                 defaults = defaults.call(this, config);
40797             }
40798
40799             if (Ext.isString(config)) {
40800                 config = Ext.ComponentManager.get(config);
40801                 Ext.applyIf(config, defaults);
40802             } else if (!config.isComponent) {
40803                 Ext.applyIf(config, defaults);
40804             } else {
40805                 Ext.applyIf(config, defaults);
40806             }
40807         }
40808
40809         return config;
40810     },
40811
40812     // @private
40813     lookupComponent : function(comp) {
40814         return Ext.isString(comp) ? Ext.ComponentManager.get(comp) : this.createComponent(comp);
40815     },
40816
40817     // @private
40818     createComponent : function(config, defaultType) {
40819         // // add in ownerCt at creation time but then immediately
40820         // // remove so that onBeforeAdd can handle it
40821         // var component = Ext.create(Ext.apply({ownerCt: this}, config), defaultType || this.defaultType);
40822         //
40823         // delete component.initialConfig.ownerCt;
40824         // delete component.ownerCt;
40825
40826         return Ext.ComponentManager.create(config, defaultType || this.defaultType);
40827     },
40828
40829     // @private - used as the key lookup function for the items collection
40830     getComponentId : function(comp) {
40831         return comp.getItemId();
40832     },
40833
40834     /**
40835
40836 Adds {@link Ext.Component Component}(s) to this Container.
40837
40838 ##Description:##
40839
40840 - Fires the {@link #beforeadd} event before adding.
40841 - The Container's {@link #defaults default config values} will be applied
40842   accordingly (see `{@link #defaults}` for details).
40843 - Fires the `{@link #add}` event after the component has been added.
40844
40845 ##Notes:##
40846
40847 If the Container is __already rendered__ when `add`
40848 is called, it will render the newly added Component into its content area.
40849
40850 __**If**__ the Container was configured with a size-managing {@link #layout} manager, the Container
40851 will recalculate its internal layout at this time too.
40852
40853 Note that the default layout manager simply renders child Components sequentially into the content area and thereafter performs no sizing.
40854
40855 If adding multiple new child Components, pass them as an array to the `add` method, so that only one layout recalculation is performed.
40856
40857     tb = new {@link Ext.toolbar.Toolbar}({
40858         renderTo: document.body
40859     });  // toolbar is rendered
40860     tb.add([{text:'Button 1'}, {text:'Button 2'}]); // add multiple items. ({@link #defaultType} for {@link Ext.toolbar.Toolbar Toolbar} is 'button')
40861
40862 ##Warning:## 
40863
40864 Components directly managed by the BorderLayout layout manager
40865 may not be removed or added.  See the Notes for {@link Ext.layout.container.Border BorderLayout}
40866 for more details.
40867
40868      * @param {...Object/Array} Component
40869      * Either one or more Components to add or an Array of Components to add.
40870      * See `{@link #items}` for additional information.
40871      *
40872      * @return {Ext.Component/Array} The Components that were added.
40873      * @markdown
40874      */
40875     add : function() {
40876         var me = this,
40877             args = Array.prototype.slice.call(arguments),
40878             hasMultipleArgs,
40879             items,
40880             results = [],
40881             i,
40882             ln,
40883             item,
40884             index = -1,
40885             cmp;
40886
40887         if (typeof args[0] == 'number') {
40888             index = args.shift();
40889         }
40890
40891         hasMultipleArgs = args.length > 1;
40892         if (hasMultipleArgs || Ext.isArray(args[0])) {
40893
40894             items = hasMultipleArgs ? args : args[0];
40895             // Suspend Layouts while we add multiple items to the container
40896             me.suspendLayout = true;
40897             for (i = 0, ln = items.length; i < ln; i++) {
40898                 item = items[i];
40899                 
40900                 if (!item) {
40901                     Ext.Error.raise("Trying to add a null item as a child of Container with itemId/id: " + me.getItemId());
40902                 }
40903                 
40904                 if (index != -1) {
40905                     item = me.add(index + i, item);
40906                 } else {
40907                     item = me.add(item);
40908                 }
40909                 results.push(item);
40910             }
40911             // Resume Layouts now that all items have been added and do a single layout for all the items just added
40912             me.suspendLayout = false;
40913             me.doLayout();
40914             return results;
40915         }
40916
40917         cmp = me.prepareItems(args[0], true)[0];
40918
40919         // Floating Components are not added into the items collection
40920         // But they do get an upward ownerCt link so that they can traverse
40921         // up to their z-index parent.
40922         if (cmp.floating) {
40923             cmp.onAdded(me, index);
40924         } else {
40925             index = (index !== -1) ? index : me.items.length;
40926             if (me.fireEvent('beforeadd', me, cmp, index) !== false && me.onBeforeAdd(cmp) !== false) {
40927                 me.items.insert(index, cmp);
40928                 cmp.onAdded(me, index);
40929                 me.onAdd(cmp, index);
40930                 me.fireEvent('add', me, cmp, index);
40931             }
40932             me.doLayout();
40933         }
40934         return cmp;
40935     },
40936
40937     /**
40938      * @private
40939      * <p>Called by Component#doAutoRender</p>
40940      * <p>Register a Container configured <code>floating: true</code> with this Container's {@link Ext.ZIndexManager ZIndexManager}.</p>
40941      * <p>Components added in ths way will not participate in the layout, but will be rendered
40942      * upon first show in the way that {@link Ext.window.Window Window}s are.</p>
40943      * <p></p>
40944      */
40945     registerFloatingItem: function(cmp) {
40946         var me = this;
40947         if (!me.floatingItems) {
40948             me.floatingItems = Ext.create('Ext.ZIndexManager', me);
40949         }
40950         me.floatingItems.register(cmp);
40951     },
40952
40953     onAdd : Ext.emptyFn,
40954     onRemove : Ext.emptyFn,
40955
40956     /**
40957      * Inserts a Component into this Container at a specified index. Fires the
40958      * {@link #beforeadd} event before inserting, then fires the {@link #add} event after the
40959      * Component has been inserted.
40960      * @param {Number} index The index at which the Component will be inserted
40961      * into the Container's items collection
40962      * @param {Ext.Component} component The child Component to insert.<br><br>
40963      * Ext uses lazy rendering, and will only render the inserted Component should
40964      * it become necessary.<br><br>
40965      * A Component config object may be passed in order to avoid the overhead of
40966      * constructing a real Component object if lazy rendering might mean that the
40967      * inserted Component will not be rendered immediately. To take advantage of
40968      * this 'lazy instantiation', set the {@link Ext.Component#xtype} config
40969      * property to the registered type of the Component wanted.<br><br>
40970      * For a list of all available xtypes, see {@link Ext.Component}.
40971      * @return {Ext.Component} component The Component (or config object) that was
40972      * inserted with the Container's default config values applied.
40973      */
40974     insert : function(index, comp) {
40975         return this.add(index, comp);
40976     },
40977
40978     /**
40979      * Moves a Component within the Container
40980      * @param {Number} fromIdx The index the Component you wish to move is currently at.
40981      * @param {Number} toIdx The new index for the Component.
40982      * @return {Ext.Component} component The Component (or config object) that was moved.
40983      */
40984     move : function(fromIdx, toIdx) {
40985         var items = this.items,
40986             item;
40987         item = items.removeAt(fromIdx);
40988         if (item === false) {
40989             return false;
40990         }
40991         items.insert(toIdx, item);
40992         this.doLayout();
40993         return item;
40994     },
40995
40996     // @private
40997     onBeforeAdd : function(item) {
40998         var me = this;
40999         
41000         if (item.ownerCt) {
41001             item.ownerCt.remove(item, false);
41002         }
41003
41004         if (me.border === false || me.border === 0) {
41005             item.border = (item.border === true);
41006         }
41007     },
41008
41009     /**
41010      * Removes a component from this container.  Fires the {@link #beforeremove} event before removing, then fires
41011      * the {@link #remove} event after the component has been removed.
41012      * @param {Component/String} component The component reference or id to remove.
41013      * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
41014      * Defaults to the value of this Container's {@link #autoDestroy} config.
41015      * @return {Ext.Component} component The Component that was removed.
41016      */
41017     remove : function(comp, autoDestroy) {
41018         var me = this,
41019             c = me.getComponent(comp);
41020             if (Ext.isDefined(Ext.global.console) && !c) {
41021                 console.warn("Attempted to remove a component that does not exist. Ext.container.Container: remove takes an argument of the component to remove. cmp.remove() is incorrect usage.");
41022             }
41023
41024         if (c && me.fireEvent('beforeremove', me, c) !== false) {
41025             me.doRemove(c, autoDestroy);
41026             me.fireEvent('remove', me, c);
41027         }
41028
41029         return c;
41030     },
41031
41032     // @private
41033     doRemove : function(component, autoDestroy) {
41034         var me = this,
41035             layout = me.layout,
41036             hasLayout = layout && me.rendered;
41037
41038         me.items.remove(component);
41039         component.onRemoved();
41040
41041         if (hasLayout) {
41042             layout.onRemove(component);
41043         }
41044
41045         me.onRemove(component, autoDestroy);
41046
41047         if (autoDestroy === true || (autoDestroy !== false && me.autoDestroy)) {
41048             component.destroy();
41049         }
41050
41051         if (hasLayout && !autoDestroy) {
41052             layout.afterRemove(component);
41053         }
41054
41055         if (!me.destroying) {
41056             me.doLayout();
41057         }
41058     },
41059
41060     /**
41061      * Removes all components from this container.
41062      * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
41063      * Defaults to the value of this Container's {@link #autoDestroy} config.
41064      * @return {Array} Array of the destroyed components
41065      */
41066     removeAll : function(autoDestroy) {
41067         var me = this,
41068             removeItems = me.items.items.slice(),
41069             items = [],
41070             i = 0,
41071             len = removeItems.length,
41072             item;
41073
41074         // Suspend Layouts while we remove multiple items from the container
41075         me.suspendLayout = true;
41076         for (; i < len; i++) {
41077             item = removeItems[i];
41078             me.remove(item, autoDestroy);
41079
41080             if (item.ownerCt !== me) {
41081                 items.push(item);
41082             }
41083         }
41084
41085         // Resume Layouts now that all items have been removed and do a single layout
41086         me.suspendLayout = false;
41087         me.doLayout();
41088         return items;
41089     },
41090
41091     // Used by ComponentQuery to retrieve all of the items
41092     // which can potentially be considered a child of this Container.
41093     // This should be overriden by components which have child items
41094     // that are not contained in items. For example dockedItems, menu, etc
41095     // IMPORTANT note for maintainers:
41096     //  Items are returned in tree traversal order. Each item is appended to the result array
41097     //  followed by the results of that child's getRefItems call.
41098     //  Floating child items are appended after internal child items.
41099     getRefItems : function(deep) {
41100         var me = this,
41101             items = me.items.items,
41102             len = items.length,
41103             i = 0,
41104             item,
41105             result = [];
41106
41107         for (; i < len; i++) {
41108             item = items[i];
41109             result.push(item);
41110             if (deep && item.getRefItems) {
41111                 result.push.apply(result, item.getRefItems(true));
41112             }
41113         }
41114
41115         // Append floating items to the list.
41116         // These will only be present after they are rendered.
41117         if (me.floatingItems && me.floatingItems.accessList) {
41118             result.push.apply(result, me.floatingItems.accessList);
41119         }
41120
41121         return result;
41122     },
41123
41124     /**
41125      * Cascades down the component/container heirarchy from this component (passed in the first call), calling the specified function with
41126      * each component. The scope (<code>this</code> reference) of the
41127      * function call will be the scope provided or the current component. The arguments to the function
41128      * will be the args provided or the current component. If the function returns false at any point,
41129      * the cascade is stopped on that branch.
41130      * @param {Function} fn The function to call
41131      * @param {Object} scope (optional) The scope of the function (defaults to current component)
41132      * @param {Array} args (optional) The args to call the function with. The current component always passed as the last argument.
41133      * @return {Ext.Container} this
41134      */
41135     cascade : function(fn, scope, origArgs){
41136         var me = this,
41137             cs = me.items ? me.items.items : [],
41138             len = cs.length,
41139             i = 0,
41140             c,
41141             args = origArgs ? origArgs.concat(me) : [me],
41142             componentIndex = args.length - 1;
41143
41144         if (fn.apply(scope || me, args) !== false) {
41145             for(; i < len; i++){
41146                 c = cs[i];
41147                 if (c.cascade) {
41148                     c.cascade(fn, scope, origArgs);
41149                 } else {
41150                     args[componentIndex] = c;
41151                     fn.apply(scope || cs, args);
41152                 }
41153             }
41154         }
41155         return this;
41156     },
41157
41158     /**
41159      * Examines this container's <code>{@link #items}</code> <b>property</b>
41160      * and gets a direct child component of this container.
41161      * @param {String/Number} comp This parameter may be any of the following:
41162      * <div><ul class="mdetail-params">
41163      * <li>a <b><code>String</code></b> : representing the <code>{@link Ext.Component#itemId itemId}</code>
41164      * or <code>{@link Ext.Component#id id}</code> of the child component </li>
41165      * <li>a <b><code>Number</code></b> : representing the position of the child component
41166      * within the <code>{@link #items}</code> <b>property</b></li>
41167      * </ul></div>
41168      * <p>For additional information see {@link Ext.util.MixedCollection#get}.
41169      * @return Ext.Component The component (if found).
41170      */
41171     getComponent : function(comp) {
41172         if (Ext.isObject(comp)) {
41173             comp = comp.getItemId();
41174         }
41175
41176         return this.items.get(comp);
41177     },
41178
41179     /**
41180      * Retrieves all descendant components which match the passed selector.
41181      * Executes an Ext.ComponentQuery.query using this container as its root.
41182      * @param {String} selector Selector complying to an Ext.ComponentQuery selector
41183      * @return {Array} Ext.Component's which matched the selector
41184      */
41185     query : function(selector) {
41186         return Ext.ComponentQuery.query(selector, this);
41187     },
41188
41189     /**
41190      * Retrieves the first direct child of this container which matches the passed selector.
41191      * The passed in selector must comply with an Ext.ComponentQuery selector.
41192      * @param {String} selector An Ext.ComponentQuery selector
41193      * @return Ext.Component
41194      */
41195     child : function(selector) {
41196         return this.query('> ' + selector)[0] || null;
41197     },
41198
41199     /**
41200      * Retrieves the first descendant of this container which matches the passed selector.
41201      * The passed in selector must comply with an Ext.ComponentQuery selector.
41202      * @param {String} selector An Ext.ComponentQuery selector
41203      * @return Ext.Component
41204      */
41205     down : function(selector) {
41206         return this.query(selector)[0] || null;
41207     },
41208
41209     // inherit docs
41210     show : function() {
41211         this.callParent(arguments);
41212         this.performDeferredLayouts();
41213         return this;
41214     },
41215
41216     // Lay out any descendant containers who queued a layout operation during the time this was hidden
41217     // This is also called by Panel after it expands because descendants of a collapsed Panel allso queue any layout ops.
41218     performDeferredLayouts: function() {
41219         var layoutCollection = this.layoutOnShow,
41220             ln = layoutCollection.getCount(),
41221             i = 0,
41222             needsLayout,
41223             item;
41224
41225         for (; i < ln; i++) {
41226             item = layoutCollection.get(i);
41227             needsLayout = item.needsLayout;
41228
41229             if (Ext.isObject(needsLayout)) {
41230                 item.doComponentLayout(needsLayout.width, needsLayout.height, needsLayout.isSetSize, needsLayout.ownerCt);
41231             }
41232         }
41233         layoutCollection.clear();
41234     },    
41235     
41236     //@private
41237     // Enable all immediate children that was previously disabled
41238     onEnable: function() {
41239         Ext.Array.each(this.query('[isFormField]'), function(item) {
41240             if (item.resetDisable) {
41241                 item.enable();
41242                 delete item.resetDisable;             
41243             }
41244         });
41245         this.callParent();
41246     },
41247     
41248     // @private
41249     // Disable all immediate children that was previously disabled
41250     onDisable: function() {
41251         Ext.Array.each(this.query('[isFormField]'), function(item) {
41252             if (item.resetDisable !== false && !item.disabled) {
41253                 item.disable();
41254                 item.resetDisable = true;
41255             }
41256         });
41257         this.callParent();
41258     },
41259
41260     /**
41261      * Occurs before componentLayout is run. Returning false from this method will prevent the containerLayout
41262      * from being executed.
41263      */
41264     beforeLayout: function() {
41265         return true;
41266     },
41267
41268     // @private
41269     beforeDestroy : function() {
41270         var me = this,
41271             items = me.items,
41272             c;
41273
41274         if (items) {
41275             while ((c = items.first())) {
41276                 me.doRemove(c, true);
41277             }
41278         }
41279
41280         Ext.destroy(
41281             me.layout,
41282             me.floatingItems
41283         );
41284         me.callParent();
41285     }
41286 });
41287 /**
41288  * @class Ext.container.Container
41289  * @extends Ext.container.AbstractContainer
41290  * <p>Base class for any {@link Ext.Component} that may contain other Components. Containers handle the
41291  * basic behavior of containing items, namely adding, inserting and removing items.</p>
41292  *
41293  * <p>The most commonly used Container classes are {@link Ext.panel.Panel}, {@link Ext.window.Window} and {@link Ext.tab.Panel}.
41294  * If you do not need the capabilities offered by the aforementioned classes you can create a lightweight
41295  * Container to be encapsulated by an HTML element to your specifications by using the
41296  * <code><b>{@link Ext.Component#autoEl autoEl}</b></code> config option.</p>
41297  *
41298  * {@img Ext.Container/Ext.Container.png Ext.Container component} 
41299  * <p>The code below illustrates how to explicitly create a Container:<pre><code>
41300 // explicitly create a Container
41301 Ext.create('Ext.container.Container', {
41302     layout: {
41303         type: 'hbox'
41304     },
41305     width: 400,
41306     renderTo: Ext.getBody(),
41307     border: 1,
41308     style: {borderColor:'#000000', borderStyle:'solid', borderWidth:'1px'},
41309     defaults: {
41310         labelWidth: 80,
41311         // implicitly create Container by specifying xtype
41312         xtype: 'datefield',
41313         flex: 1,
41314         style: {
41315             padding: '10px'
41316         }
41317     },
41318     items: [{
41319         xtype: 'datefield',
41320         name: 'startDate',
41321         fieldLabel: 'Start date'
41322     },{
41323         xtype: 'datefield',
41324         name: 'endDate',
41325         fieldLabel: 'End date'
41326     }]
41327 });
41328 </code></pre></p>
41329  *
41330  * <p><u><b>Layout</b></u></p>
41331  * <p>Container classes delegate the rendering of child Components to a layout
41332  * manager class which must be configured into the Container using the
41333  * <code><b>{@link #layout}</b></code> configuration property.</p>
41334  * <p>When either specifying child <code>{@link #items}</code> of a Container,
41335  * or dynamically {@link #add adding} Components to a Container, remember to
41336  * consider how you wish the Container to arrange those child elements, and
41337  * whether those child elements need to be sized using one of Ext's built-in
41338  * <b><code>{@link #layout}</code></b> schemes. By default, Containers use the
41339  * {@link Ext.layout.container.Auto Auto} scheme which only
41340  * renders child components, appending them one after the other inside the
41341  * Container, and <b>does not apply any sizing</b> at all.</p>
41342  * <p>A common mistake is when a developer neglects to specify a
41343  * <b><code>{@link #layout}</code></b> (e.g. widgets like GridPanels or
41344  * TreePanels are added to Containers for which no <code><b>{@link #layout}</b></code>
41345  * has been specified). If a Container is left to use the default
41346  * {Ext.layout.container.Auto Auto} scheme, none of its
41347  * child components will be resized, or changed in any way when the Container
41348  * is resized.</p>
41349  * <p>Certain layout managers allow dynamic addition of child components.
41350  * Those that do include {@link Ext.layout.container.Card},
41351  * {@link Ext.layout.container.Anchor}, {@link Ext.layout.container.VBox}, {@link Ext.layout.container.HBox}, and
41352  * {@link Ext.layout.container.Table}. For example:<pre><code>
41353 //  Create the GridPanel.
41354 var myNewGrid = new Ext.grid.Panel({
41355     store: myStore,
41356     headers: myHeaders,
41357     title: 'Results', // the title becomes the title of the tab
41358 });
41359
41360 myTabPanel.add(myNewGrid); // {@link Ext.tab.Panel} implicitly uses {@link Ext.layout.container.Card Card}
41361 myTabPanel.{@link Ext.tab.Panel#setActiveTab setActiveTab}(myNewGrid);
41362  * </code></pre></p>
41363  * <p>The example above adds a newly created GridPanel to a TabPanel. Note that
41364  * a TabPanel uses {@link Ext.layout.container.Card} as its layout manager which
41365  * means all its child items are sized to {@link Ext.layout.container.Fit fit}
41366  * exactly into its client area.
41367  * <p><b><u>Overnesting is a common problem</u></b>.
41368  * An example of overnesting occurs when a GridPanel is added to a TabPanel
41369  * by wrapping the GridPanel <i>inside</i> a wrapping Panel (that has no
41370  * <code><b>{@link #layout}</b></code> specified) and then add that wrapping Panel
41371  * to the TabPanel. The point to realize is that a GridPanel <b>is</b> a
41372  * Component which can be added directly to a Container. If the wrapping Panel
41373  * has no <code><b>{@link #layout}</b></code> configuration, then the overnested
41374  * GridPanel will not be sized as expected.<p>
41375  *
41376  * <p><u><b>Adding via remote configuration</b></u></p>
41377  *
41378  * <p>A server side script can be used to add Components which are generated dynamically on the server.
41379  * An example of adding a GridPanel to a TabPanel where the GridPanel is generated by the server
41380  * based on certain parameters:
41381  * </p><pre><code>
41382 // execute an Ajax request to invoke server side script:
41383 Ext.Ajax.request({
41384     url: 'gen-invoice-grid.php',
41385     // send additional parameters to instruct server script
41386     params: {
41387         startDate: Ext.getCmp('start-date').getValue(),
41388         endDate: Ext.getCmp('end-date').getValue()
41389     },
41390     // process the response object to add it to the TabPanel:
41391     success: function(xhr) {
41392         var newComponent = eval(xhr.responseText); // see discussion below
41393         myTabPanel.add(newComponent); // add the component to the TabPanel
41394         myTabPanel.setActiveTab(newComponent);
41395     },
41396     failure: function() {
41397         Ext.Msg.alert("Grid create failed", "Server communication failure");
41398     }
41399 });
41400 </code></pre>
41401  * <p>The server script needs to return a JSON representation of a configuration object, which, when decoded
41402  * will return a config object with an {@link Ext.Component#xtype xtype}. The server might return the following
41403  * JSON:</p><pre><code>
41404 {
41405     "xtype": 'grid',
41406     "title": 'Invoice Report',
41407     "store": {
41408         "model": 'Invoice',
41409         "proxy": {
41410             "type": 'ajax',
41411             "url": 'get-invoice-data.php',
41412             "reader": {
41413                 "type": 'json'
41414                 "record": 'transaction',
41415                 "idProperty": 'id',
41416                 "totalRecords": 'total'
41417             })
41418         },
41419         "autoLoad": {
41420             "params": {
41421                 "startDate": '01/01/2008',
41422                 "endDate": '01/31/2008'
41423             }
41424         }
41425     },
41426     "headers": [
41427         {"header": "Customer", "width": 250, "dataIndex": 'customer', "sortable": true},
41428         {"header": "Invoice Number", "width": 120, "dataIndex": 'invNo', "sortable": true},
41429         {"header": "Invoice Date", "width": 100, "dataIndex": 'date', "renderer": Ext.util.Format.dateRenderer('M d, y'), "sortable": true},
41430         {"header": "Value", "width": 120, "dataIndex": 'value', "renderer": 'usMoney', "sortable": true}
41431     ]
41432 }
41433 </code></pre>
41434  * <p>When the above code fragment is passed through the <code>eval</code> function in the success handler
41435  * of the Ajax request, the result will be a config object which, when added to a Container, will cause instantiation
41436  * of a GridPanel. <b>Be sure that the Container is configured with a layout which sizes and positions the child items to your requirements.</b></p>
41437  * <p>Note: since the code above is <i>generated</i> by a server script, the <code>autoLoad</code> params for
41438  * the Store, the user's preferred date format, the metadata to allow generation of the Model layout, and the ColumnModel
41439  * can all be generated into the code since these are all known on the server.</p>
41440  *
41441  * @xtype container
41442  */
41443 Ext.define('Ext.container.Container', {
41444     extend: 'Ext.container.AbstractContainer',
41445     alias: 'widget.container',
41446     alternateClassName: 'Ext.Container',
41447
41448     /**
41449      * Return the immediate child Component in which the passed element is located.
41450      * @param el The element to test.
41451      * @return {Component} The child item which contains the passed element.
41452      */
41453     getChildByElement: function(el) {
41454         var item,
41455             itemEl,
41456             i = 0,
41457             it = this.items.items,
41458             ln = it.length;
41459
41460         el = Ext.getDom(el);
41461         for (; i < ln; i++) {
41462             item = it[i];
41463             itemEl = item.getEl();
41464             if ((itemEl.dom === el) || itemEl.contains(el)) {
41465                 return item;
41466             }
41467         }
41468         return null;
41469     }
41470 });
41471
41472 /**
41473  * @class Ext.toolbar.Fill
41474  * @extends Ext.Component
41475  * A non-rendering placeholder item which instructs the Toolbar's Layout to begin using
41476  * the right-justified button container.
41477  *
41478  * {@img Ext.toolbar.Fill/Ext.toolbar.Fill.png Toolbar Fill}
41479  * Example usage:
41480 <pre><code>
41481     Ext.create('Ext.panel.Panel', {
41482         title: 'Toolbar Fill Example',
41483         width: 300,
41484         height: 200,
41485         tbar : [
41486             'Item 1',
41487             {xtype: 'tbfill'}, // or '->'
41488             'Item 2'
41489         ],
41490         renderTo: Ext.getBody()
41491     });
41492 </code></pre>
41493  * @constructor
41494  * Creates a new Fill
41495  * @xtype tbfill
41496  */
41497 Ext.define('Ext.toolbar.Fill', {
41498     extend: 'Ext.Component',
41499     alias: 'widget.tbfill',
41500     alternateClassName: 'Ext.Toolbar.Fill',
41501     isFill : true,
41502     flex: 1
41503 });
41504 /**
41505  * @class Ext.toolbar.Item
41506  * @extends Ext.Component
41507  * The base class that other non-interacting Toolbar Item classes should extend in order to
41508  * get some basic common toolbar item functionality.
41509  * @constructor
41510  * Creates a new Item
41511  * @param {HTMLElement} el
41512  * @xtype tbitem
41513  */
41514 Ext.define('Ext.toolbar.Item', {
41515     extend: 'Ext.Component',
41516     alias: 'widget.tbitem',
41517     alternateClassName: 'Ext.Toolbar.Item',
41518     enable:Ext.emptyFn,
41519     disable:Ext.emptyFn,
41520     focus:Ext.emptyFn
41521     /**
41522      * @cfg {String} overflowText Text to be used for the menu if the item is overflowed.
41523      */
41524 });
41525 /**
41526  * @class Ext.toolbar.Separator
41527  * @extends Ext.toolbar.Item
41528  * A simple class that adds a vertical separator bar between toolbar items
41529  * (css class:<tt>'x-toolbar-separator'</tt>). 
41530  * {@img Ext.toolbar.Separator/Ext.toolbar.Separator.png Toolbar Separator}
41531  * Example usage:
41532  * <pre><code>
41533     Ext.create('Ext.panel.Panel', {
41534         title: 'Toolbar Seperator Example',
41535         width: 300,
41536         height: 200,
41537         tbar : [
41538             'Item 1',
41539             {xtype: 'tbseparator'}, // or '-'
41540             'Item 2'
41541         ],
41542         renderTo: Ext.getBody()
41543     }); 
41544 </code></pre>
41545  * @constructor
41546  * Creates a new Separator
41547  * @xtype tbseparator
41548  */
41549 Ext.define('Ext.toolbar.Separator', {
41550     extend: 'Ext.toolbar.Item',
41551     alias: 'widget.tbseparator',
41552     alternateClassName: 'Ext.Toolbar.Separator',
41553     baseCls: Ext.baseCSSPrefix + 'toolbar-separator',
41554     focusable: false
41555 });
41556 /**
41557  * @class Ext.menu.Manager
41558  * Provides a common registry of all menus on a page.
41559  * @singleton
41560  */
41561 Ext.define('Ext.menu.Manager', {
41562     singleton: true,
41563     requires: [
41564         'Ext.util.MixedCollection',
41565         'Ext.util.KeyMap'
41566     ],
41567     alternateClassName: 'Ext.menu.MenuMgr',
41568
41569     uses: ['Ext.menu.Menu'],
41570
41571     menus: {},
41572     groups: {},
41573     attached: false,
41574     lastShow: new Date(),
41575
41576     init: function() {
41577         var me = this;
41578         
41579         me.active = Ext.create('Ext.util.MixedCollection');
41580         Ext.getDoc().addKeyListener(27, function() {
41581             if (me.active.length > 0) {
41582                 me.hideAll();
41583             }
41584         }, me);
41585     },
41586
41587     /**
41588      * Hides all menus that are currently visible
41589      * @return {Boolean} success True if any active menus were hidden.
41590      */
41591     hideAll: function() {
41592         var active = this.active,
41593             c;
41594         if (active && active.length > 0) {
41595             c = active.clone();
41596             c.each(function(m) {
41597                 m.hide();
41598             });
41599             return true;
41600         }
41601         return false;
41602     },
41603
41604     onHide: function(m) {
41605         var me = this,
41606             active = me.active;
41607         active.remove(m);
41608         if (active.length < 1) {
41609             Ext.getDoc().un('mousedown', me.onMouseDown, me);
41610             me.attached = false;
41611         }
41612     },
41613
41614     onShow: function(m) {
41615         var me = this,
41616             active   = me.active,
41617             last     = active.last(),
41618             attached = me.attached,
41619             menuEl   = m.getEl(),
41620             zIndex;
41621
41622         me.lastShow = new Date();
41623         active.add(m);
41624         if (!attached) {
41625             Ext.getDoc().on('mousedown', me.onMouseDown, me);
41626             me.attached = true;
41627         }
41628         m.toFront();
41629     },
41630
41631     onBeforeHide: function(m) {
41632         if (m.activeChild) {
41633             m.activeChild.hide();
41634         }
41635         if (m.autoHideTimer) {
41636             clearTimeout(m.autoHideTimer);
41637             delete m.autoHideTimer;
41638         }
41639     },
41640
41641     onBeforeShow: function(m) {
41642         var active = this.active,
41643             parentMenu = m.parentMenu;
41644             
41645         active.remove(m);
41646         if (!parentMenu && !m.allowOtherMenus) {
41647             this.hideAll();
41648         }
41649         else if (parentMenu && parentMenu.activeChild && m != parentMenu.activeChild) {
41650             parentMenu.activeChild.hide();
41651         }
41652     },
41653
41654     // private
41655     onMouseDown: function(e) {
41656         var me = this,
41657             active = me.active,
41658             lastShow = me.lastShow;
41659
41660         if (Ext.Date.getElapsed(lastShow) > 50 && active.length > 0 && !e.getTarget('.' + Ext.baseCSSPrefix + 'menu')) {
41661             me.hideAll();
41662         }
41663     },
41664
41665     // private
41666     register: function(menu) {
41667         var me = this;
41668
41669         if (!me.active) {
41670             me.init();
41671         }
41672
41673         if (menu.floating) {
41674             me.menus[menu.id] = menu;
41675             menu.on({
41676                 beforehide: me.onBeforeHide,
41677                 hide: me.onHide,
41678                 beforeshow: me.onBeforeShow,
41679                 show: me.onShow,
41680                 scope: me
41681             });
41682         }
41683     },
41684
41685     /**
41686      * Returns a {@link Ext.menu.Menu} object
41687      * @param {String/Object} menu The string menu id, an existing menu object reference, or a Menu config that will
41688      * be used to generate and return a new Menu this.
41689      * @return {Ext.menu.Menu} The specified menu, or null if none are found
41690      */
41691     get: function(menu) {
41692         var menus = this.menus;
41693         
41694         if (typeof menu == 'string') { // menu id
41695             if (!menus) {  // not initialized, no menus to return
41696                 return null;
41697             }
41698             return menus[menu];
41699         } else if (menu.isMenu) {  // menu instance
41700             return menu;
41701         } else if (Ext.isArray(menu)) { // array of menu items
41702             return Ext.create('Ext.menu.Menu', {items:menu});
41703         } else { // otherwise, must be a config
41704             return Ext.ComponentManager.create(menu, 'menu');
41705         }
41706     },
41707
41708     // private
41709     unregister: function(menu) {
41710         var me = this,
41711             menus = me.menus,
41712             active = me.active;
41713
41714         delete menus[menu.id];
41715         active.remove(menu);
41716         menu.un({
41717             beforehide: me.onBeforeHide,
41718             hide: me.onHide,
41719             beforeshow: me.onBeforeShow,
41720             show: me.onShow,
41721             scope: me
41722         });
41723     },
41724
41725     // private
41726     registerCheckable: function(menuItem) {
41727         var groups  = this.groups,
41728             groupId = menuItem.group;
41729
41730         if (groupId) {
41731             if (!groups[groupId]) {
41732                 groups[groupId] = [];
41733             }
41734
41735             groups[groupId].push(menuItem);
41736         }
41737     },
41738
41739     // private
41740     unregisterCheckable: function(menuItem) {
41741         var groups  = this.groups,
41742             groupId = menuItem.group;
41743
41744         if (groupId) {
41745             Ext.Array.remove(groups[groupId], menuItem);
41746         }
41747     },
41748
41749     onCheckChange: function(menuItem, state) {
41750         var groups  = this.groups,
41751             groupId = menuItem.group,
41752             i       = 0,
41753             group, ln, curr;
41754
41755         if (groupId && state) {
41756             group = groups[groupId];
41757             ln = group.length;
41758             for (; i < ln; i++) {
41759                 curr = group[i];
41760                 if (curr != menuItem) {
41761                     curr.setChecked(false);
41762                 }
41763             }
41764         }
41765     }
41766 });
41767 /**
41768  * @class Ext.button.Button
41769  * @extends Ext.Component
41770
41771 Create simple buttons with this component. Customisations include {@link #config-iconAlign aligned}
41772 {@link #config-iconCls icons}, {@link #config-menu dropdown menus}, {@link #config-tooltip tooltips}
41773 and {@link #config-scale sizing options}. Specify a {@link #config-handler handler} to run code when
41774 a user clicks the button, or use {@link #config-listeners listeners} for other events such as
41775 {@link #events-mouseover mouseover}.
41776
41777 {@img Ext.button.Button/Ext.button.Button1.png Ext.button.Button component}
41778 Example usage:
41779
41780     Ext.create('Ext.Button', {
41781         text: 'Click me',
41782         renderTo: Ext.getBody(),        
41783         handler: function() {
41784             alert('You clicked the button!')
41785         }
41786     });
41787
41788 The {@link #handler} configuration can also be updated dynamically using the {@link #setHandler} method.
41789 Example usage:
41790
41791     Ext.create('Ext.Button', {
41792         text    : 'Dyanmic Handler Button',
41793         renderTo: Ext.getBody(),
41794         handler : function() {
41795             //this button will spit out a different number every time you click it.
41796             //so firstly we must check if that number is already set:
41797             if (this.clickCount) {
41798                 //looks like the property is already set, so lets just add 1 to that number and alert the user
41799                 this.clickCount++;
41800                 alert('You have clicked the button "' + this.clickCount + '" times.\n\nTry clicking it again..');
41801             } else {
41802                 //if the clickCount property is not set, we will set it and alert the user
41803                 this.clickCount = 1;
41804                 alert('You just clicked the button for the first time!\n\nTry pressing it again..');
41805             }
41806         }
41807     });
41808
41809 A button within a container:
41810
41811     Ext.create('Ext.Container', {
41812         renderTo: Ext.getBody(),
41813         items   : [
41814             {
41815                 xtype: 'button',
41816                 text : 'My Button'
41817             }
41818         ]
41819     });
41820
41821 A useful option of Button is the {@link #scale} configuration. This configuration has three different options:
41822 * `'small'`
41823 * `'medium'`
41824 * `'large'`
41825
41826 {@img Ext.button.Button/Ext.button.Button2.png Ext.button.Button component}
41827 Example usage:
41828
41829     Ext.create('Ext.Button', {
41830         renderTo: document.body,
41831         text    : 'Click me',
41832         scale   : 'large'
41833     });
41834
41835 Buttons can also be toggled. To enable this, you simple set the {@link #enableToggle} property to `true`.
41836 {@img Ext.button.Button/Ext.button.Button3.png Ext.button.Button component}
41837 Example usage:
41838
41839     Ext.create('Ext.Button', {
41840         renderTo: Ext.getBody(),
41841         text: 'Click Me',
41842         enableToggle: true
41843     });
41844
41845 You can assign a menu to a button by using the {@link #menu} configuration. This standard configuration can either be a reference to a {@link Ext.menu.Menu menu}
41846 object, a {@link Ext.menu.Menu menu} id or a {@link Ext.menu.Menu menu} config blob. When assigning a menu to a button, an arrow is automatically added to the button.
41847 You can change the alignment of the arrow using the {@link #arrowAlign} configuration on button.
41848 {@img Ext.button.Button/Ext.button.Button4.png Ext.button.Button component}
41849 Example usage:
41850
41851     Ext.create('Ext.Button', {
41852         text      : 'Menu button',
41853         renderTo  : Ext.getBody(),        
41854         arrowAlign: 'bottom',
41855         menu      : [
41856             {text: 'Item 1'},
41857             {text: 'Item 2'},
41858             {text: 'Item 3'},
41859             {text: 'Item 4'}
41860         ]
41861     });
41862
41863 Using listeners, you can easily listen to events fired by any component, using the {@link #listeners} configuration or using the {@link #addListener} method.
41864 Button has a variety of different listeners:
41865 * `click`
41866 * `toggle`
41867 * `mouseover`
41868 * `mouseout`
41869 * `mouseshow`
41870 * `menuhide`
41871 * `menutriggerover`
41872 * `menutriggerout`
41873
41874 Example usage:
41875
41876     Ext.create('Ext.Button', {
41877         text     : 'Button',
41878         renderTo : Ext.getBody(),
41879         listeners: {
41880             click: function() {
41881                 //this == the button, as we are in the local scope
41882                 this.setText('I was clicked!');
41883             },
41884             mouseover: function() {
41885                 //set a new config which says we moused over, if not already set
41886                 if (!this.mousedOver) {
41887                     this.mousedOver = true;
41888                     alert('You moused over a button!\n\nI wont do this again.');
41889                 }
41890             }
41891         }
41892     });
41893
41894  * @constructor
41895  * Create a new button
41896  * @param {Object} config The config object
41897  * @xtype button
41898  * @markdown
41899  * @docauthor Robert Dougan <rob@sencha.com>
41900  */
41901 Ext.define('Ext.button.Button', {
41902
41903     /* Begin Definitions */
41904     alias: 'widget.button',
41905     extend: 'Ext.Component',
41906
41907     requires: [
41908         'Ext.menu.Manager',
41909         'Ext.util.ClickRepeater',
41910         'Ext.layout.component.Button',
41911         'Ext.util.TextMetrics',
41912         'Ext.util.KeyMap'
41913     ],
41914
41915     alternateClassName: 'Ext.Button',
41916     /* End Definitions */
41917
41918     isButton: true,
41919     componentLayout: 'button',
41920
41921     /**
41922      * Read-only. True if this button is hidden
41923      * @type Boolean
41924      */
41925     hidden: false,
41926
41927     /**
41928      * Read-only. True if this button is disabled
41929      * @type Boolean
41930      */
41931     disabled: false,
41932
41933     /**
41934      * Read-only. True if this button is pressed (only if enableToggle = true)
41935      * @type Boolean
41936      */
41937     pressed: false,
41938
41939     /**
41940      * @cfg {String} text The button text to be used as innerHTML (html tags are accepted)
41941      */
41942
41943     /**
41944      * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image
41945      * CSS property of the button by default, so if you want a mixed icon/text button, set cls:'x-btn-text-icon')
41946      */
41947
41948     /**
41949      * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event).
41950      * The handler is passed the following parameters:<div class="mdetail-params"><ul>
41951      * <li><code>b</code> : Button<div class="sub-desc">This Button.</div></li>
41952      * <li><code>e</code> : EventObject<div class="sub-desc">The click event.</div></li>
41953      * </ul></div>
41954      */
41955
41956     /**
41957      * @cfg {Number} minWidth The minimum width for this button (used to give a set of buttons a common width).
41958      * See also {@link Ext.panel.Panel}.<tt>{@link Ext.panel.Panel#minButtonWidth minButtonWidth}</tt>.
41959      */
41960
41961     /**
41962      * @cfg {String/Object} tooltip The tooltip for the button - can be a string to be used as innerHTML (html tags are accepted) or QuickTips config object
41963      */
41964
41965     /**
41966      * @cfg {Boolean} hidden True to start hidden (defaults to false)
41967      */
41968
41969     /**
41970      * @cfg {Boolean} disabled True to start disabled (defaults to false)
41971      */
41972
41973     /**
41974      * @cfg {Boolean} pressed True to start pressed (only if enableToggle = true)
41975      */
41976
41977     /**
41978      * @cfg {String} toggleGroup The group this toggle button is a member of (only 1 per group can be pressed)
41979      */
41980
41981     /**
41982      * @cfg {Boolean/Object} repeat True to repeat fire the click event while the mouse is down. This can also be
41983      * a {@link Ext.util.ClickRepeater ClickRepeater} config object (defaults to false).
41984      */
41985
41986     /**
41987      * @cfg {Number} tabIndex Set a DOM tabIndex for this button (defaults to undefined)
41988      */
41989
41990     /**
41991      * @cfg {Boolean} allowDepress
41992      * False to not allow a pressed Button to be depressed (defaults to undefined). Only valid when {@link #enableToggle} is true.
41993      */
41994
41995     /**
41996      * @cfg {Boolean} enableToggle
41997      * True to enable pressed/not pressed toggling (defaults to false)
41998      */
41999     enableToggle: false,
42000
42001     /**
42002      * @cfg {Function} toggleHandler
42003      * Function called when a Button with {@link #enableToggle} set to true is clicked. Two arguments are passed:<ul class="mdetail-params">
42004      * <li><b>button</b> : Ext.button.Button<div class="sub-desc">this Button object</div></li>
42005      * <li><b>state</b> : Boolean<div class="sub-desc">The next state of the Button, true means pressed.</div></li>
42006      * </ul>
42007      */
42008
42009     /**
42010      * @cfg {Mixed} menu
42011      * Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
42012      */
42013
42014     /**
42015      * @cfg {String} menuAlign
42016      * The position to align the menu to (see {@link Ext.core.Element#alignTo} for more details, defaults to 'tl-bl?').
42017      */
42018     menuAlign: 'tl-bl?',
42019
42020     /**
42021      * @cfg {String} overflowText If used in a {@link Ext.toolbar.Toolbar Toolbar}, the
42022      * text to be used if this item is shown in the overflow menu. See also
42023      * {@link Ext.toolbar.Item}.<code>{@link Ext.toolbar.Item#overflowText overflowText}</code>.
42024      */
42025
42026     /**
42027      * @cfg {String} iconCls
42028      * A css class which sets a background image to be used as the icon for this button
42029      */
42030
42031     /**
42032      * @cfg {String} type
42033      * submit, reset or button - defaults to 'button'
42034      */
42035     type: 'button',
42036
42037     /**
42038      * @cfg {String} clickEvent
42039      * The DOM event that will fire the handler of the button. This can be any valid event name (dblclick, contextmenu).
42040      * Defaults to <tt>'click'</tt>.
42041      */
42042     clickEvent: 'click',
42043     
42044     /**
42045      * @cfg {Boolean} preventDefault
42046      * True to prevent the default action when the {@link #clickEvent} is processed. Defaults to true.
42047      */
42048     preventDefault: true,
42049
42050     /**
42051      * @cfg {Boolean} handleMouseEvents
42052      * False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
42053      */
42054     handleMouseEvents: true,
42055
42056     /**
42057      * @cfg {String} tooltipType
42058      * The type of tooltip to use. Either 'qtip' (default) for QuickTips or 'title' for title attribute.
42059      */
42060     tooltipType: 'qtip',
42061
42062     /**
42063      * @cfg {String} baseCls
42064      * The base CSS class to add to all buttons. (Defaults to 'x-btn')
42065      */
42066     baseCls: Ext.baseCSSPrefix + 'btn',
42067
42068     /**
42069      * @cfg {String} pressedCls
42070      * The CSS class to add to a button when it is in the pressed state. (Defaults to 'x-btn-pressed')
42071      */
42072     pressedCls: 'pressed',
42073     
42074     /**
42075      * @cfg {String} overCls
42076      * The CSS class to add to a button when it is in the over (hovered) state. (Defaults to 'x-btn-over')
42077      */
42078     overCls: 'over',
42079     
42080     /**
42081      * @cfg {String} focusCls
42082      * The CSS class to add to a button when it is in the focussed state. (Defaults to 'x-btn-focus')
42083      */
42084     focusCls: 'focus',
42085     
42086     /**
42087      * @cfg {String} menuActiveCls
42088      * The CSS class to add to a button when it's menu is active. (Defaults to 'x-btn-menu-active')
42089      */
42090     menuActiveCls: 'menu-active',
42091
42092     ariaRole: 'button',
42093
42094     // inherited
42095     renderTpl:
42096         '<em class="{splitCls}">' +
42097             '<tpl if="href">' +
42098                 '<a href="{href}" target="{target}"<tpl if="tabIndex"> tabIndex="{tabIndex}"</tpl> role="link">' +
42099                     '<span class="{baseCls}-inner">{text}</span>' +
42100                 '</a>' +
42101             '</tpl>' +
42102             '<tpl if="!href">' +
42103                 '<button type="{type}" hidefocus="true"' +
42104                     // the autocomplete="off" is required to prevent Firefox from remembering
42105                     // the button's disabled state between page reloads.
42106                     '<tpl if="tabIndex"> tabIndex="{tabIndex}"</tpl> role="button" autocomplete="off">' +
42107                     '<span class="{baseCls}-inner" style="{innerSpanStyle}">{text}</span>' +
42108                 '</button>' +
42109             '</tpl>' +
42110         '</em>' ,
42111
42112     /**
42113      * @cfg {String} scale
42114      * <p>(Optional) The size of the Button. Three values are allowed:</p>
42115      * <ul class="mdetail-params">
42116      * <li>'small'<div class="sub-desc">Results in the button element being 16px high.</div></li>
42117      * <li>'medium'<div class="sub-desc">Results in the button element being 24px high.</div></li>
42118      * <li>'large'<div class="sub-desc">Results in the button element being 32px high.</div></li>
42119      * </ul>
42120      * <p>Defaults to <b><tt>'small'</tt></b>.</p>
42121      */
42122     scale: 'small',
42123     
42124     /**
42125      * @private An array of allowed scales.
42126      */
42127     allowedScales: ['small', 'medium', 'large'],
42128     
42129     /**
42130      * @cfg {Object} scope The scope (<tt><b>this</b></tt> reference) in which the
42131      * <code>{@link #handler}</code> and <code>{@link #toggleHandler}</code> is
42132      * executed. Defaults to this Button.
42133      */
42134
42135     /**
42136      * @cfg {String} iconAlign
42137      * <p>(Optional) The side of the Button box to render the icon. Four values are allowed:</p>
42138      * <ul class="mdetail-params">
42139      * <li>'top'<div class="sub-desc"></div></li>
42140      * <li>'right'<div class="sub-desc"></div></li>
42141      * <li>'bottom'<div class="sub-desc"></div></li>
42142      * <li>'left'<div class="sub-desc"></div></li>
42143      * </ul>
42144      * <p>Defaults to <b><tt>'left'</tt></b>.</p>
42145      */
42146     iconAlign: 'left',
42147
42148     /**
42149      * @cfg {String} arrowAlign
42150      * <p>(Optional) The side of the Button box to render the arrow if the button has an associated {@link #menu}.
42151      * Two values are allowed:</p>
42152      * <ul class="mdetail-params">
42153      * <li>'right'<div class="sub-desc"></div></li>
42154      * <li>'bottom'<div class="sub-desc"></div></li>
42155      * </ul>
42156      * <p>Defaults to <b><tt>'right'</tt></b>.</p>
42157      */
42158     arrowAlign: 'right',
42159
42160     /**
42161      * @cfg {String} arrowCls
42162      * <p>(Optional) The className used for the inner arrow element if the button has a menu.</p>
42163      */
42164     arrowCls: 'arrow',
42165
42166     /**
42167      * @cfg {Ext.Template} template (Optional)
42168      * <p>A {@link Ext.Template Template} used to create the Button's DOM structure.</p>
42169      * Instances, or subclasses which need a different DOM structure may provide a different
42170      * template layout in conjunction with an implementation of {@link #getTemplateArgs}.
42171      * @type Ext.Template
42172      * @property template
42173      */
42174
42175     /**
42176      * @cfg {String} cls
42177      * A CSS class string to apply to the button's main element.
42178      */
42179
42180     /**
42181      * @property menu
42182      * @type Menu
42183      * The {@link Ext.menu.Menu Menu} object associated with this Button when configured with the {@link #menu} config option.
42184      */
42185
42186     /**
42187      * @cfg {Boolean} autoWidth
42188      * By default, if a width is not specified the button will attempt to stretch horizontally to fit its content.
42189      * If the button is being managed by a width sizing layout (hbox, fit, anchor), set this to false to prevent
42190      * the button from doing this automatic sizing.
42191      * Defaults to <tt>undefined</tt>.
42192      */
42193      
42194     maskOnDisable: false,
42195
42196     // inherit docs
42197     initComponent: function() {
42198         var me = this;
42199         me.callParent(arguments);
42200
42201         me.addEvents(
42202             /**
42203              * @event click
42204              * Fires when this button is clicked
42205              * @param {Button} this
42206              * @param {EventObject} e The click event
42207              */
42208             'click',
42209
42210             /**
42211              * @event toggle
42212              * Fires when the 'pressed' state of this button changes (only if enableToggle = true)
42213              * @param {Button} this
42214              * @param {Boolean} pressed
42215              */
42216             'toggle',
42217
42218             /**
42219              * @event mouseover
42220              * Fires when the mouse hovers over the button
42221              * @param {Button} this
42222              * @param {Event} e The event object
42223              */
42224             'mouseover',
42225
42226             /**
42227              * @event mouseout
42228              * Fires when the mouse exits the button
42229              * @param {Button} this
42230              * @param {Event} e The event object
42231              */
42232             'mouseout',
42233
42234             /**
42235              * @event menushow
42236              * If this button has a menu, this event fires when it is shown
42237              * @param {Button} this
42238              * @param {Menu} menu
42239              */
42240             'menushow',
42241
42242             /**
42243              * @event menuhide
42244              * If this button has a menu, this event fires when it is hidden
42245              * @param {Button} this
42246              * @param {Menu} menu
42247              */
42248             'menuhide',
42249
42250             /**
42251              * @event menutriggerover
42252              * If this button has a menu, this event fires when the mouse enters the menu triggering element
42253              * @param {Button} this
42254              * @param {Menu} menu
42255              * @param {EventObject} e
42256              */
42257             'menutriggerover',
42258
42259             /**
42260              * @event menutriggerout
42261              * If this button has a menu, this event fires when the mouse leaves the menu triggering element
42262              * @param {Button} this
42263              * @param {Menu} menu
42264              * @param {EventObject} e
42265              */
42266             'menutriggerout'
42267         );
42268
42269         if (me.menu) {
42270             // Flag that we'll have a splitCls
42271             me.split = true;
42272
42273             // retrieve menu by id or instantiate instance if needed
42274             me.menu = Ext.menu.Manager.get(me.menu);
42275             me.menu.ownerCt = me;
42276         }
42277
42278         // Accept url as a synonym for href
42279         if (me.url) {
42280             me.href = me.url;
42281         }
42282
42283         // preventDefault defaults to false for links
42284         if (me.href && !me.hasOwnProperty('preventDefault')) {
42285             me.preventDefault = false;
42286         }
42287
42288         if (Ext.isString(me.toggleGroup)) {
42289             me.enableToggle = true;
42290         }
42291
42292     },
42293
42294     // private
42295     initAria: function() {
42296         this.callParent();
42297         var actionEl = this.getActionEl();
42298         if (this.menu) {
42299             actionEl.dom.setAttribute('aria-haspopup', true);
42300         }
42301     },
42302
42303     // inherit docs
42304     getActionEl: function() {
42305         return this.btnEl;
42306     },
42307
42308     // inherit docs
42309     getFocusEl: function() {
42310         return this.btnEl;
42311     },
42312
42313     // private
42314     setButtonCls: function() {
42315         var me = this,
42316             el = me.el,
42317             cls = [];
42318
42319         if (me.useSetClass) {
42320             if (!Ext.isEmpty(me.oldCls)) {
42321                 me.removeClsWithUI(me.oldCls);
42322                 me.removeClsWithUI(me.pressedCls);
42323             }
42324             
42325             // Check whether the button has an icon or not, and if it has an icon, what is th alignment
42326             if (me.iconCls || me.icon) {
42327                 if (me.text) {
42328                     cls.push('icon-text-' + me.iconAlign);
42329                 } else {
42330                     cls.push('icon');
42331                 }
42332             } else if (me.text) {
42333                 cls.push('noicon');
42334             }
42335             
42336             me.oldCls = cls;
42337             me.addClsWithUI(cls);
42338             me.addClsWithUI(me.pressed ? me.pressedCls : null);
42339         }
42340     },
42341     
42342     // private
42343     onRender: function(ct, position) {
42344         // classNames for the button
42345         var me = this,
42346             repeater, btn;
42347             
42348         // Apply the renderData to the template args
42349         Ext.applyIf(me.renderData, me.getTemplateArgs());
42350
42351         // Extract the button and the button wrapping element
42352         Ext.applyIf(me.renderSelectors, {
42353             btnEl  : me.href ? 'a' : 'button',
42354             btnWrap: 'em',
42355             btnInnerEl: '.' + me.baseCls + '-inner'
42356         });
42357         
42358         if (me.scale) {
42359             me.ui = me.ui + '-' + me.scale;
42360         }
42361
42362         // Render internal structure
42363         me.callParent(arguments);
42364
42365         // If it is a split button + has a toolip for the arrow
42366         if (me.split && me.arrowTooltip) {
42367             me.arrowEl.dom[me.tooltipType] = me.arrowTooltip;
42368         }
42369
42370         // Add listeners to the focus and blur events on the element
42371         me.mon(me.btnEl, {
42372             scope: me,
42373             focus: me.onFocus,
42374             blur : me.onBlur
42375         });
42376
42377         // Set btn as a local variable for easy access
42378         btn = me.el;
42379
42380         if (me.icon) {
42381             me.setIcon(me.icon);
42382         }
42383
42384         if (me.iconCls) {
42385             me.setIconCls(me.iconCls);
42386         }
42387
42388         if (me.tooltip) {
42389             me.setTooltip(me.tooltip, true);
42390         }
42391
42392         // Add the mouse events to the button
42393         if (me.handleMouseEvents) {
42394             me.mon(btn, {
42395                 scope: me,
42396                 mouseover: me.onMouseOver,
42397                 mouseout: me.onMouseOut,
42398                 mousedown: me.onMouseDown
42399             });
42400
42401             if (me.split) {
42402                 me.mon(btn, {
42403                     mousemove: me.onMouseMove,
42404                     scope: me
42405                 });
42406             }
42407         }
42408
42409         // Check if the button has a menu
42410         if (me.menu) {
42411             me.mon(me.menu, {
42412                 scope: me,
42413                 show: me.onMenuShow,
42414                 hide: me.onMenuHide
42415             });
42416
42417             me.keyMap = Ext.create('Ext.util.KeyMap', me.el, {
42418                 key: Ext.EventObject.DOWN,
42419                 handler: me.onDownKey,
42420                 scope: me
42421             });
42422         }
42423
42424         // Check if it is a repeat button
42425         if (me.repeat) {
42426             repeater = Ext.create('Ext.util.ClickRepeater', btn, Ext.isObject(me.repeat) ? me.repeat: {});
42427             me.mon(repeater, 'click', me.onRepeatClick, me);
42428         } else {
42429             me.mon(btn, me.clickEvent, me.onClick, me);
42430         }
42431
42432         // Register the button in the toggle manager
42433         Ext.ButtonToggleManager.register(me);
42434     },
42435
42436     /**
42437      * <p>This method returns an object which provides substitution parameters for the {@link #renderTpl XTemplate} used
42438      * to create this Button's DOM structure.</p>
42439      * <p>Instances or subclasses which use a different Template to create a different DOM structure may need to provide their
42440      * own implementation of this method.</p>
42441      * <p>The default implementation which provides data for the default {@link #template} returns an Object containing the
42442      * following properties:</p><div class="mdetail-params"><ul>
42443      * <li><code>type</code> : The &lt;button&gt;'s {@link #type}</li>
42444      * <li><code>splitCls</code> : A CSS class to determine the presence and position of an arrow icon. (<code>'x-btn-arrow'</code> or <code>'x-btn-arrow-bottom'</code> or <code>''</code>)</li>
42445      * <li><code>cls</code> : A CSS class name applied to the Button's main &lt;tbody&gt; element which determines the button's scale and icon alignment.</li>
42446      * <li><code>text</code> : The {@link #text} to display ion the Button.</li>
42447      * <li><code>tabIndex</code> : The tab index within the input flow.</li>
42448      * </ul></div>
42449      * @return {Array} Substitution data for a Template.
42450     */
42451     getTemplateArgs: function() {
42452         var me = this,
42453             persistentPadding = me.getPersistentBtnPadding(),
42454             innerSpanStyle = '';
42455
42456         // Create negative margin offsets to counteract persistent button padding if needed
42457         if (Math.max.apply(Math, persistentPadding) > 0) {
42458             innerSpanStyle = 'margin:' + Ext.Array.map(persistentPadding, function(pad) {
42459                 return -pad + 'px';
42460             }).join(' ');
42461         }
42462
42463         return {
42464             href     : me.getHref(),
42465             target   : me.target || '_blank',
42466             type     : me.type,
42467             splitCls : me.getSplitCls(),
42468             cls      : me.cls,
42469             text     : me.text || '&#160;',
42470             tabIndex : me.tabIndex,
42471             innerSpanStyle: innerSpanStyle
42472         };
42473     },
42474
42475     /**
42476      * @private
42477      * If there is a configured href for this Button, returns the href with parameters appended.
42478      * @returns The href string with parameters appended.
42479      */
42480     getHref: function() {
42481         var me = this;
42482         return me.href ? Ext.urlAppend(me.href, me.params + Ext.Object.toQueryString(Ext.apply(Ext.apply({}, me.baseParams)))) : false;
42483     },
42484
42485     /**
42486      * <p><b>Only valid if the Button was originally configured with a {@link #url}</b></p>
42487      * <p>Sets the href of the link dynamically according to the params passed, and any {@link #baseParams} configured.</p>
42488      * @param {Object} Parameters to use in the href URL.
42489      */
42490     setParams: function(p) {
42491         this.params = p;
42492         this.btnEl.dom.href = this.getHref();
42493     },
42494
42495     getSplitCls: function() {
42496         var me = this;
42497         return me.split ? (me.baseCls + '-' + me.arrowCls) + ' ' + (me.baseCls + '-' + me.arrowCls + '-' + me.arrowAlign) : '';
42498     },
42499
42500     // private
42501     afterRender: function() {
42502         var me = this;
42503         me.useSetClass = true;
42504         me.setButtonCls();
42505         me.doc = Ext.getDoc();
42506         this.callParent(arguments);
42507     },
42508
42509     /**
42510      * Sets the CSS class that provides a background image to use as the button's icon.  This method also changes
42511      * the value of the {@link #iconCls} config internally.
42512      * @param {String} cls The CSS class providing the icon image
42513      * @return {Ext.button.Button} this
42514      */
42515     setIconCls: function(cls) {
42516         var me = this,
42517             btnInnerEl = me.btnInnerEl;
42518         if (btnInnerEl) {
42519             // Remove the previous iconCls from the button
42520             btnInnerEl.removeCls(me.iconCls);
42521             btnInnerEl.addCls(cls || '');
42522             me.setButtonCls();
42523         }
42524         me.iconCls = cls;
42525         return me;
42526     },
42527
42528     /**
42529      * Sets the tooltip for this Button.
42530      * @param {String/Object} tooltip. This may be:<div class="mdesc-details"><ul>
42531      * <li><b>String</b> : A string to be used as innerHTML (html tags are accepted) to show in a tooltip</li>
42532      * <li><b>Object</b> : A configuration object for {@link Ext.tip.QuickTipManager#register}.</li>
42533      * </ul></div>
42534      * @return {Ext.button.Button} this
42535      */
42536     setTooltip: function(tooltip, initial) {
42537         var me = this;
42538
42539         if (me.rendered) {
42540             if (!initial) {
42541                 me.clearTip();
42542             }
42543             if (Ext.isObject(tooltip)) {
42544                 Ext.tip.QuickTipManager.register(Ext.apply({
42545                     target: me.btnEl.id
42546                 },
42547                 tooltip));
42548                 me.tooltip = tooltip;
42549             } else {
42550                 me.btnEl.dom.setAttribute('data-' + this.tooltipType, tooltip);
42551             }
42552         } else {
42553             me.tooltip = tooltip;
42554         }
42555         return me;
42556     },
42557
42558     // private
42559     getRefItems: function(deep){
42560         var menu = this.menu,
42561             items;
42562
42563         if (menu) {
42564             items = menu.getRefItems(deep);
42565             items.unshift(menu);
42566         }
42567         return items || [];
42568     },
42569
42570     // private
42571     clearTip: function() {
42572         if (Ext.isObject(this.tooltip)) {
42573             Ext.tip.QuickTipManager.unregister(this.btnEl);
42574         }
42575     },
42576
42577     // private
42578     beforeDestroy: function() {
42579         var me = this;
42580         if (me.rendered) {
42581             me.clearTip();
42582         }
42583         if (me.menu && me.destroyMenu !== false) {
42584             Ext.destroy(me.btnEl, me.btnInnerEl, me.menu);
42585         }
42586         Ext.destroy(me.repeater);
42587     },
42588
42589     // private
42590     onDestroy: function() {
42591         var me = this;
42592         if (me.rendered) {
42593             me.doc.un('mouseover', me.monitorMouseOver, me);
42594             me.doc.un('mouseup', me.onMouseUp, me);
42595             delete me.doc;
42596             delete me.btnEl;
42597             delete me.btnInnerEl;
42598             Ext.ButtonToggleManager.unregister(me);
42599             
42600             Ext.destroy(me.keyMap);
42601             delete me.keyMap;
42602         }
42603         me.callParent();
42604     },
42605
42606     /**
42607      * Assigns this Button's click handler
42608      * @param {Function} handler The function to call when the button is clicked
42609      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function is executed.
42610      * Defaults to this Button.
42611      * @return {Ext.button.Button} this
42612      */
42613     setHandler: function(handler, scope) {
42614         this.handler = handler;
42615         this.scope = scope;
42616         return this;
42617     },
42618
42619     /**
42620      * Sets this Button's text
42621      * @param {String} text The button text
42622      * @return {Ext.button.Button} this
42623      */
42624     setText: function(text) {
42625         var me = this;
42626         me.text = text;
42627         if (me.el) {
42628             me.btnInnerEl.update(text || '&#160;');
42629             me.setButtonCls();
42630         }
42631         me.doComponentLayout();
42632         return me;
42633     },
42634
42635     /**
42636      * Sets the background image (inline style) of the button.  This method also changes
42637      * the value of the {@link #icon} config internally.
42638      * @param {String} icon The path to an image to display in the button
42639      * @return {Ext.button.Button} this
42640      */
42641     setIcon: function(icon) {
42642         var me = this,
42643             btnInnerEl = me.btnInnerEl;
42644         me.icon = icon;
42645         if (btnInnerEl) {
42646             btnInnerEl.setStyle('background-image', icon ? 'url(' + icon + ')': '');
42647             me.setButtonCls();
42648         }
42649         return me;
42650     },
42651
42652     /**
42653      * Gets the text for this Button
42654      * @return {String} The button text
42655      */
42656     getText: function() {
42657         return this.text;
42658     },
42659
42660     /**
42661      * If a state it passed, it becomes the pressed state otherwise the current state is toggled.
42662      * @param {Boolean} state (optional) Force a particular state
42663      * @param {Boolean} supressEvent (optional) True to stop events being fired when calling this method.
42664      * @return {Ext.button.Button} this
42665      */
42666     toggle: function(state, suppressEvent) {
42667         var me = this;
42668         state = state === undefined ? !me.pressed: !!state;
42669         if (state !== me.pressed) {
42670             if (me.rendered) {
42671                 me[state ? 'addClsWithUI': 'removeClsWithUI'](me.pressedCls);
42672             }
42673             me.btnEl.dom.setAttribute('aria-pressed', state);
42674             me.pressed = state;
42675             if (!suppressEvent) {
42676                 me.fireEvent('toggle', me, state);
42677                 Ext.callback(me.toggleHandler, me.scope || me, [me, state]);
42678             }
42679         }
42680         return me;
42681     },
42682
42683     /**
42684      * Show this button's menu (if it has one)
42685      */
42686     showMenu: function() {
42687         var me = this;
42688         if (me.rendered && me.menu) {
42689             if (me.tooltip) {
42690                 Ext.tip.QuickTipManager.getQuickTip().cancelShow(me.btnEl);
42691             }
42692             if (me.menu.isVisible()) {
42693                 me.menu.hide();
42694             }
42695
42696             me.menu.showBy(me.el, me.menuAlign);
42697         }
42698         return me;
42699     },
42700
42701     /**
42702      * Hide this button's menu (if it has one)
42703      */
42704     hideMenu: function() {
42705         if (this.hasVisibleMenu()) {
42706             this.menu.hide();
42707         }
42708         return this;
42709     },
42710
42711     /**
42712      * Returns true if the button has a menu and it is visible
42713      * @return {Boolean}
42714      */
42715     hasVisibleMenu: function() {
42716         var menu = this.menu;
42717         return menu && menu.rendered && menu.isVisible();
42718     },
42719
42720     // private
42721     onRepeatClick: function(repeat, e) {
42722         this.onClick(e);
42723     },
42724
42725     // private
42726     onClick: function(e) {
42727         var me = this;
42728         if (me.preventDefault || (me.disabled && me.getHref()) && e) {
42729             e.preventDefault();
42730         }
42731         if (e.button !== 0) {
42732             return;
42733         }
42734         if (!me.disabled) {
42735             if (me.enableToggle && (me.allowDepress !== false || !me.pressed)) {
42736                 me.toggle();
42737             }
42738             if (me.menu && !me.hasVisibleMenu() && !me.ignoreNextClick) {
42739                 me.showMenu();
42740             }
42741             me.fireEvent('click', me, e);
42742             if (me.handler) {
42743                 me.handler.call(me.scope || me, me, e);
42744             }
42745             me.onBlur();
42746         }
42747     },
42748
42749     /**
42750      * @private mouseover handler called when a mouseover event occurs anywhere within the encapsulating element.
42751      * The targets are interrogated to see what is being entered from where.
42752      * @param e
42753      */
42754     onMouseOver: function(e) {
42755         var me = this;
42756         if (!me.disabled && !e.within(me.el, true, true)) {
42757             me.onMouseEnter(e);
42758         }
42759     },
42760
42761     /**
42762      * @private mouseout handler called when a mouseout event occurs anywhere within the encapsulating element -
42763      * or the mouse leaves the encapsulating element.
42764      * The targets are interrogated to see what is being exited to where.
42765      * @param e
42766      */
42767     onMouseOut: function(e) {
42768         var me = this;
42769         if (!e.within(me.el, true, true)) {
42770             if (me.overMenuTrigger) {
42771                 me.onMenuTriggerOut(e);
42772             }
42773             me.onMouseLeave(e);
42774         }
42775     },
42776
42777     /**
42778      * @private mousemove handler called when the mouse moves anywhere within the encapsulating element.
42779      * The position is checked to determine if the mouse is entering or leaving the trigger area. Using
42780      * mousemove to check this is more resource intensive than we'd like, but it is necessary because
42781      * the trigger area does not line up exactly with sub-elements so we don't always get mouseover/out
42782      * events when needed. In the future we should consider making the trigger a separate element that
42783      * is absolutely positioned and sized over the trigger area.
42784      */
42785     onMouseMove: function(e) {
42786         var me = this,
42787             el = me.el,
42788             over = me.overMenuTrigger,
42789             overlap, btnSize;
42790
42791         if (me.split) {
42792             if (me.arrowAlign === 'right') {
42793                 overlap = e.getX() - el.getX();
42794                 btnSize = el.getWidth();
42795             } else {
42796                 overlap = e.getY() - el.getY();
42797                 btnSize = el.getHeight();
42798             }
42799
42800             if (overlap > (btnSize - me.getTriggerSize())) {
42801                 if (!over) {
42802                     me.onMenuTriggerOver(e);
42803                 }
42804             } else {
42805                 if (over) {
42806                     me.onMenuTriggerOut(e);
42807                 }
42808             }
42809         }
42810     },
42811
42812     /**
42813      * @private Measures the size of the trigger area for menu and split buttons. Will be a width for
42814      * a right-aligned trigger and a height for a bottom-aligned trigger. Cached after first measurement.
42815      */
42816     getTriggerSize: function() {
42817         var me = this,
42818             size = me.triggerSize,
42819             side, sideFirstLetter, undef;
42820             
42821         if (size === undef) {
42822             side = me.arrowAlign;
42823             sideFirstLetter = side.charAt(0);
42824             size = me.triggerSize = me.el.getFrameWidth(sideFirstLetter) + me.btnWrap.getFrameWidth(sideFirstLetter) + (me.frameSize && me.frameSize[side] || 0);
42825         }
42826         return size;
42827     },
42828
42829     /**
42830      * @private virtual mouseenter handler called when it is detected that the mouseout event
42831      * signified the mouse entering the encapsulating element.
42832      * @param e
42833      */
42834     onMouseEnter: function(e) {
42835         var me = this;
42836         me.addClsWithUI(me.overCls);
42837         me.fireEvent('mouseover', me, e);
42838     },
42839
42840     /**
42841      * @private virtual mouseleave handler called when it is detected that the mouseover event
42842      * signified the mouse entering the encapsulating element.
42843      * @param e
42844      */
42845     onMouseLeave: function(e) {
42846         var me = this;
42847         me.removeClsWithUI(me.overCls);
42848         me.fireEvent('mouseout', me, e);
42849     },
42850
42851     /**
42852      * @private virtual mouseenter handler called when it is detected that the mouseover event
42853      * signified the mouse entering the arrow area of the button - the <em>.
42854      * @param e
42855      */
42856     onMenuTriggerOver: function(e) {
42857         var me = this;
42858         me.overMenuTrigger = true;
42859         me.fireEvent('menutriggerover', me, me.menu, e);
42860     },
42861
42862     /**
42863      * @private virtual mouseleave handler called when it is detected that the mouseout event
42864      * signified the mouse leaving the arrow area of the button - the <em>.
42865      * @param e
42866      */
42867     onMenuTriggerOut: function(e) {
42868         var me = this;
42869         delete me.overMenuTrigger;
42870         me.fireEvent('menutriggerout', me, me.menu, e);
42871     },
42872     
42873     // inherit docs
42874     enable : function(silent) {
42875         var me = this;
42876
42877         me.callParent(arguments);
42878         
42879         me.removeClsWithUI('disabled');
42880
42881         return me;
42882     },
42883
42884     // inherit docs
42885     disable : function(silent) {
42886         var me = this;
42887         
42888         me.callParent(arguments);
42889         
42890         me.addClsWithUI('disabled');
42891
42892         return me;
42893     },
42894     
42895     /**
42896      * Method to change the scale of the button. See {@link #scale} for allowed configurations.
42897      * @param {String} scale The scale to change to.
42898      */
42899     setScale: function(scale) {
42900         var me = this,
42901             ui = me.ui.replace('-' + me.scale, '');
42902         
42903         //check if it is an allowed scale
42904         if (!Ext.Array.contains(me.allowedScales, scale)) {
42905             throw('#setScale: scale must be an allowed scale (' + me.allowedScales.join(', ') + ')');
42906         }
42907         
42908         me.scale = scale;
42909         me.setUI(ui);
42910     },
42911     
42912     // inherit docs
42913     setUI: function(ui) {
42914         var me = this;
42915         
42916         //we need to append the scale to the UI, if not already done
42917         if (me.scale && !ui.match(me.scale)) {
42918             ui = ui + '-' + me.scale;
42919         }
42920         
42921         me.callParent([ui]);
42922         
42923         // Set all the state classNames, as they need to include the UI
42924         // me.disabledCls += ' ' + me.baseCls + '-' + me.ui + '-disabled';
42925     },
42926     
42927     // private
42928     onFocus: function(e) {
42929         var me = this;
42930         if (!me.disabled) {
42931             me.addClsWithUI(me.focusCls);
42932         }
42933     },
42934
42935     // private
42936     onBlur: function(e) {
42937         var me = this;
42938         me.removeClsWithUI(me.focusCls);
42939     },
42940
42941     // private
42942     onMouseDown: function(e) {
42943         var me = this;
42944         if (!me.disabled && e.button === 0) {
42945             me.addClsWithUI(me.pressedCls);
42946             me.doc.on('mouseup', me.onMouseUp, me);
42947         }
42948     },
42949     // private
42950     onMouseUp: function(e) {
42951         var me = this;
42952         if (e.button === 0) {
42953             if (!me.pressed) {
42954                 me.removeClsWithUI(me.pressedCls);
42955             }
42956             me.doc.un('mouseup', me.onMouseUp, me);
42957         }
42958     },
42959     // private
42960     onMenuShow: function(e) {
42961         var me = this;
42962         me.ignoreNextClick = 0;
42963         me.addClsWithUI(me.menuActiveCls);
42964         me.fireEvent('menushow', me, me.menu);
42965     },
42966
42967     // private
42968     onMenuHide: function(e) {
42969         var me = this;
42970         me.removeClsWithUI(me.menuActiveCls);
42971         me.ignoreNextClick = Ext.defer(me.restoreClick, 250, me);
42972         me.fireEvent('menuhide', me, me.menu);
42973     },
42974
42975     // private
42976     restoreClick: function() {
42977         this.ignoreNextClick = 0;
42978     },
42979
42980     // private
42981     onDownKey: function() {
42982         var me = this;
42983
42984         if (!me.disabled) {
42985             if (me.menu) {
42986                 me.showMenu();
42987             }
42988         }
42989     },
42990
42991     /**
42992      * @private Some browsers (notably Safari and older Chromes on Windows) add extra "padding" inside the button
42993      * element that cannot be removed. This method returns the size of that padding with a one-time detection.
42994      * @return Array [top, right, bottom, left]
42995      */
42996     getPersistentBtnPadding: function() {
42997         var cls = Ext.button.Button,
42998             padding = cls.persistentPadding,
42999             btn, leftTop, btnEl, btnInnerEl;
43000
43001         if (!padding) {
43002             padding = cls.persistentPadding = [0, 0, 0, 0]; //set early to prevent recursion
43003
43004             if (!Ext.isIE) { //short-circuit IE as it sometimes gives false positive for padding
43005                 // Create auto-size button offscreen and measure its insides
43006                 btn = Ext.create('Ext.button.Button', {
43007                     renderTo: Ext.getBody(),
43008                     text: 'test',
43009                     style: 'position:absolute;top:-999px;'
43010                 });
43011                 btnEl = btn.btnEl;
43012                 btnInnerEl = btn.btnInnerEl;
43013                 btnEl.setSize(null, null); //clear any hard dimensions on the button el to see what it does naturally
43014
43015                 leftTop = btnInnerEl.getOffsetsTo(btnEl);
43016                 padding[0] = leftTop[1];
43017                 padding[1] = btnEl.getWidth() - btnInnerEl.getWidth() - leftTop[0];
43018                 padding[2] = btnEl.getHeight() - btnInnerEl.getHeight() - leftTop[1];
43019                 padding[3] = leftTop[0];
43020
43021                 btn.destroy();
43022             }
43023         }
43024
43025         return padding;
43026     }
43027
43028 }, function() {
43029     var groups = {},
43030         g, i, l;
43031
43032     function toggleGroup(btn, state) {
43033         if (state) {
43034             g = groups[btn.toggleGroup];
43035             for (i = 0, l = g.length; i < l; i++) {
43036                 if (g[i] !== btn) {
43037                     g[i].toggle(false);
43038                 }
43039             }
43040         }
43041     }
43042     // Private utility class used by Button
43043     Ext.ButtonToggleManager = {
43044         register: function(btn) {
43045             if (!btn.toggleGroup) {
43046                 return;
43047             }
43048             var group = groups[btn.toggleGroup];
43049             if (!group) {
43050                 group = groups[btn.toggleGroup] = [];
43051             }
43052             group.push(btn);
43053             btn.on('toggle', toggleGroup);
43054         },
43055
43056         unregister: function(btn) {
43057             if (!btn.toggleGroup) {
43058                 return;
43059             }
43060             var group = groups[btn.toggleGroup];
43061             if (group) {
43062                 Ext.Array.remove(group, btn);
43063                 btn.un('toggle', toggleGroup);
43064             }
43065         },
43066
43067         /**
43068         * Gets the pressed button in the passed group or null
43069         * @param {String} group
43070         * @return Button
43071         */
43072         getPressed: function(group) {
43073             var g = groups[group],
43074                 i = 0,
43075                 len;
43076             if (g) {
43077                 for (len = g.length; i < len; i++) {
43078                     if (g[i].pressed === true) {
43079                         return g[i];
43080                     }
43081                 }
43082             }
43083             return null;
43084         }
43085     };
43086 });
43087
43088 /**
43089  * @class Ext.layout.container.boxOverflow.Menu
43090  * @extends Ext.layout.container.boxOverflow.None
43091  * @private
43092  */
43093 Ext.define('Ext.layout.container.boxOverflow.Menu', {
43094
43095     /* Begin Definitions */
43096
43097     extend: 'Ext.layout.container.boxOverflow.None',
43098     requires: ['Ext.toolbar.Separator', 'Ext.button.Button'],
43099     alternateClassName: 'Ext.layout.boxOverflow.Menu',
43100     
43101     /* End Definitions */
43102
43103     /**
43104      * @cfg {String} afterCtCls
43105      * CSS class added to the afterCt element. This is the element that holds any special items such as scrollers,
43106      * which must always be present at the rightmost edge of the Container
43107      */
43108
43109     /**
43110      * @property noItemsMenuText
43111      * @type String
43112      * HTML fragment to render into the toolbar overflow menu if there are no items to display
43113      */
43114     noItemsMenuText : '<div class="' + Ext.baseCSSPrefix + 'toolbar-no-items">(None)</div>',
43115
43116     constructor: function(layout) {
43117         var me = this;
43118
43119         me.callParent(arguments);
43120
43121         // Before layout, we need to re-show all items which we may have hidden due to a previous overflow.
43122         layout.beforeLayout = Ext.Function.createInterceptor(layout.beforeLayout, this.clearOverflow, this);
43123
43124         me.afterCtCls = me.afterCtCls || Ext.baseCSSPrefix + 'box-menu-' + layout.parallelAfter;
43125         /**
43126          * @property menuItems
43127          * @type Array
43128          * Array of all items that are currently hidden and should go into the dropdown menu
43129          */
43130         me.menuItems = [];
43131     },
43132
43133     handleOverflow: function(calculations, targetSize) {
43134         var me = this,
43135             layout = me.layout,
43136             methodName = 'get' + layout.parallelPrefixCap,
43137             newSize = {},
43138             posArgs = [null, null];
43139
43140         me.callParent(arguments);
43141         this.createMenu(calculations, targetSize);
43142         newSize[layout.perpendicularPrefix] = targetSize[layout.perpendicularPrefix];
43143         newSize[layout.parallelPrefix] = targetSize[layout.parallelPrefix] - me.afterCt[methodName]();
43144
43145         // Center the menuTrigger button.
43146         // TODO: Should we emulate align: 'middle' like this, or should we 'stretchmax' the menuTrigger?
43147         posArgs[layout.perpendicularSizeIndex] = (calculations.meta.maxSize - me.menuTrigger['get' + layout.perpendicularPrefixCap]()) / 2;
43148         me.menuTrigger.setPosition.apply(me.menuTrigger, posArgs);
43149
43150         return { targetSize: newSize };
43151     },
43152
43153     /**
43154      * @private
43155      * Called by the layout, when it determines that there is no overflow.
43156      * Also called as an interceptor to the layout's onLayout method to reshow
43157      * previously hidden overflowing items.
43158      */
43159     clearOverflow: function(calculations, targetSize) {
43160         var me = this,
43161             newWidth = targetSize ? targetSize.width + (me.afterCt ? me.afterCt.getWidth() : 0) : 0,
43162             items = me.menuItems,
43163             i = 0,
43164             length = items.length,
43165             item;
43166
43167         me.hideTrigger();
43168         for (; i < length; i++) {
43169             items[i].show();
43170         }
43171         items.length = 0;
43172
43173         return targetSize ? {
43174             targetSize: {
43175                 height: targetSize.height,
43176                 width : newWidth
43177             }
43178         } : null;
43179     },
43180
43181     /**
43182      * @private
43183      */
43184     showTrigger: function() {
43185         this.menuTrigger.show();
43186     },
43187
43188     /**
43189      * @private
43190      */
43191     hideTrigger: function() {
43192         if (this.menuTrigger != undefined) {
43193             this.menuTrigger.hide();
43194         }
43195     },
43196
43197     /**
43198      * @private
43199      * Called before the overflow menu is shown. This constructs the menu's items, caching them for as long as it can.
43200      */
43201     beforeMenuShow: function(menu) {
43202         var me = this,
43203             items = me.menuItems,
43204             i = 0,
43205             len   = items.length,
43206             item,
43207             prev;
43208
43209         var needsSep = function(group, prev){
43210             return group.isXType('buttongroup') && !(prev instanceof Ext.toolbar.Separator);
43211         };
43212
43213         me.clearMenu();
43214         menu.removeAll();
43215
43216         for (; i < len; i++) {
43217             item = items[i];
43218
43219             // Do not show a separator as a first item
43220             if (!i && (item instanceof Ext.toolbar.Separator)) {
43221                 continue;
43222             }
43223             if (prev && (needsSep(item, prev) || needsSep(prev, item))) {
43224                 menu.add('-');
43225             }
43226
43227             me.addComponentToMenu(menu, item);
43228             prev = item;
43229         }
43230
43231         // put something so the menu isn't empty if no compatible items found
43232         if (menu.items.length < 1) {
43233             menu.add(me.noItemsMenuText);
43234         }
43235     },
43236     
43237     /**
43238      * @private
43239      * Returns a menu config for a given component. This config is used to create a menu item
43240      * to be added to the expander menu
43241      * @param {Ext.Component} component The component to create the config for
43242      * @param {Boolean} hideOnClick Passed through to the menu item
43243      */
43244     createMenuConfig : function(component, hideOnClick) {
43245         var config = Ext.apply({}, component.initialConfig),
43246             group  = component.toggleGroup;
43247
43248         Ext.copyTo(config, component, [
43249             'iconCls', 'icon', 'itemId', 'disabled', 'handler', 'scope', 'menu'
43250         ]);
43251
43252         Ext.apply(config, {
43253             text       : component.overflowText || component.text,
43254             hideOnClick: hideOnClick,
43255             destroyMenu: false
43256         });
43257
43258         if (group || component.enableToggle) {
43259             Ext.apply(config, {
43260                 group  : group,
43261                 checked: component.pressed,
43262                 listeners: {
43263                     checkchange: function(item, checked){
43264                         component.toggle(checked);
43265                     }
43266                 }
43267             });
43268         }
43269
43270         delete config.ownerCt;
43271         delete config.xtype;
43272         delete config.id;
43273         return config;
43274     },
43275
43276     /**
43277      * @private
43278      * Adds the given Toolbar item to the given menu. Buttons inside a buttongroup are added individually.
43279      * @param {Ext.menu.Menu} menu The menu to add to
43280      * @param {Ext.Component} component The component to add
43281      */
43282     addComponentToMenu : function(menu, component) {
43283         var me = this;
43284         if (component instanceof Ext.toolbar.Separator) {
43285             menu.add('-');
43286         } else if (component.isComponent) {
43287             if (component.isXType('splitbutton')) {
43288                 menu.add(me.createMenuConfig(component, true));
43289
43290             } else if (component.isXType('button')) {
43291                 menu.add(me.createMenuConfig(component, !component.menu));
43292
43293             } else if (component.isXType('buttongroup')) {
43294                 component.items.each(function(item){
43295                      me.addComponentToMenu(menu, item);
43296                 });
43297             } else {
43298                 menu.add(Ext.create(Ext.getClassName(component), me.createMenuConfig(component)));
43299             }
43300         }
43301     },
43302
43303     /**
43304      * @private
43305      * Deletes the sub-menu of each item in the expander menu. Submenus are created for items such as
43306      * splitbuttons and buttongroups, where the Toolbar item cannot be represented by a single menu item
43307      */
43308     clearMenu : function() {
43309         var menu = this.moreMenu;
43310         if (menu && menu.items) {
43311             menu.items.each(function(item) {
43312                 if (item.menu) {
43313                     delete item.menu;
43314                 }
43315             });
43316         }
43317     },
43318
43319     /**
43320      * @private
43321      * Creates the overflow trigger and menu used when enableOverflow is set to true and the items
43322      * in the layout are too wide to fit in the space available
43323      */
43324     createMenu: function(calculations, targetSize) {
43325         var me = this,
43326             layout = me.layout,
43327             startProp = layout.parallelBefore,
43328             sizeProp = layout.parallelPrefix,
43329             available = targetSize[sizeProp],
43330             boxes = calculations.boxes,
43331             i = 0,
43332             len = boxes.length,
43333             box;
43334
43335         if (!me.menuTrigger) {
43336             me.createInnerElements();
43337
43338             /**
43339              * @private
43340              * @property menu
43341              * @type Ext.menu.Menu
43342              * The expand menu - holds items for every item that cannot be shown
43343              * because the container is currently not large enough.
43344              */
43345             me.menu = Ext.create('Ext.menu.Menu', {
43346                 hideMode: 'offsets',
43347                 listeners: {
43348                     scope: me,
43349                     beforeshow: me.beforeMenuShow
43350                 }
43351             });
43352
43353             /**
43354              * @private
43355              * @property menuTrigger
43356              * @type Ext.button.Button
43357              * The expand button which triggers the overflow menu to be shown
43358              */
43359             me.menuTrigger = Ext.create('Ext.button.Button', {
43360                 ownerCt : me.layout.owner, // To enable the Menu to ascertain a valid zIndexManager owner in the same tree
43361                 iconCls : Ext.baseCSSPrefix + layout.owner.getXType() + '-more-icon',
43362                 ui      : layout.owner instanceof Ext.toolbar.Toolbar ? 'default-toolbar' : 'default',
43363                 menu    : me.menu,
43364                 getSplitCls: function() { return '';},
43365                 renderTo: me.afterCt
43366             });
43367         }
43368         me.showTrigger();
43369         available -= me.afterCt.getWidth();
43370
43371         // Hide all items which are off the end, and store them to allow them to be restored
43372         // before each layout operation.
43373         me.menuItems.length = 0;
43374         for (; i < len; i++) {
43375             box = boxes[i];
43376             if (box[startProp] + box[sizeProp] > available) {
43377                 me.menuItems.push(box.component);
43378                 box.component.hide();
43379             }
43380         }
43381     },
43382
43383     /**
43384      * @private
43385      * Creates the beforeCt, innerCt and afterCt elements if they have not already been created
43386      * @param {Ext.container.Container} container The Container attached to this Layout instance
43387      * @param {Ext.core.Element} target The target Element
43388      */
43389     createInnerElements: function() {
43390         var me = this,
43391             target = me.layout.getRenderTarget();
43392
43393         if (!this.afterCt) {
43394             target.addCls(Ext.baseCSSPrefix + me.layout.direction + '-box-overflow-body');
43395             this.afterCt  = target.insertSibling({cls: Ext.layout.container.Box.prototype.innerCls + ' ' + this.afterCtCls}, 'before');
43396         }
43397     },
43398
43399     /**
43400      * @private
43401      */
43402     destroy: function() {
43403         Ext.destroy(this.menu, this.menuTrigger);
43404     }
43405 });
43406 /**
43407  * @class Ext.util.Region
43408  * @extends Object
43409  *
43410  * Represents a rectangular region and provides a number of utility methods
43411  * to compare regions.
43412  */
43413
43414 Ext.define('Ext.util.Region', {
43415
43416     /* Begin Definitions */
43417
43418     requires: ['Ext.util.Offset'],
43419
43420     statics: {
43421         /**
43422          * @static
43423          * @param {Mixed} el A string, DomElement or Ext.core.Element representing an element
43424          * on the page.
43425          * @returns {Ext.util.Region} region
43426          * Retrieves an Ext.util.Region for a particular element.
43427          */
43428         getRegion: function(el) {
43429             return Ext.fly(el).getPageBox(true);
43430         },
43431
43432         /**
43433          * @static
43434          * @param {Object} o An object with top, right, bottom, left properties
43435          * @return {Ext.util.Region} region The region constructed based on the passed object
43436          */
43437         from: function(o) {
43438             return new this(o.top, o.right, o.bottom, o.left);
43439         }
43440     },
43441
43442     /* End Definitions */
43443
43444     /**
43445      * @constructor
43446      * @param {Number} top Top
43447      * @param {Number} right Right
43448      * @param {Number} bottom Bottom
43449      * @param {Number} left Left
43450      */
43451     constructor : function(t, r, b, l) {
43452         var me = this;
43453         me.y = me.top = me[1] = t;
43454         me.right = r;
43455         me.bottom = b;
43456         me.x = me.left = me[0] = l;
43457     },
43458
43459     /**
43460      * Checks if this region completely contains the region that is passed in.
43461      * @param {Ext.util.Region} region
43462      */
43463     contains : function(region) {
43464         var me = this;
43465         return (region.x >= me.x &&
43466                 region.right <= me.right &&
43467                 region.y >= me.y &&
43468                 region.bottom <= me.bottom);
43469
43470     },
43471
43472     /**
43473      * Checks if this region intersects the region passed in.
43474      * @param {Ext.util.Region} region
43475      * @return {Ext.util.Region/Boolean} Returns the intersected region or false if there is no intersection.
43476      */
43477     intersect : function(region) {
43478         var me = this,
43479             t = Math.max(me.y, region.y),
43480             r = Math.min(me.right, region.right),
43481             b = Math.min(me.bottom, region.bottom),
43482             l = Math.max(me.x, region.x);
43483
43484         if (b > t && r > l) {
43485             return new this.self(t, r, b, l);
43486         }
43487         else {
43488             return false;
43489         }
43490     },
43491
43492     /**
43493      * Returns the smallest region that contains the current AND targetRegion.
43494      * @param {Ext.util.Region} region
43495      */
43496     union : function(region) {
43497         var me = this,
43498             t = Math.min(me.y, region.y),
43499             r = Math.max(me.right, region.right),
43500             b = Math.max(me.bottom, region.bottom),
43501             l = Math.min(me.x, region.x);
43502
43503         return new this.self(t, r, b, l);
43504     },
43505
43506     /**
43507      * Modifies the current region to be constrained to the targetRegion.
43508      * @param {Ext.util.Region} targetRegion
43509      */
43510     constrainTo : function(r) {
43511         var me = this,
43512             constrain = Ext.Number.constrain;
43513         me.top = me.y = constrain(me.top, r.y, r.bottom);
43514         me.bottom = constrain(me.bottom, r.y, r.bottom);
43515         me.left = me.x = constrain(me.left, r.x, r.right);
43516         me.right = constrain(me.right, r.x, r.right);
43517         return me;
43518     },
43519
43520     /**
43521      * Modifies the current region to be adjusted by offsets.
43522      * @param {Number} top top offset
43523      * @param {Number} right right offset
43524      * @param {Number} bottom bottom offset
43525      * @param {Number} left left offset
43526      */
43527     adjust : function(t, r, b, l) {
43528         var me = this;
43529         me.top = me.y += t;
43530         me.left = me.x += l;
43531         me.right += r;
43532         me.bottom += b;
43533         return me;
43534     },
43535
43536     /**
43537      * Get the offset amount of a point outside the region
43538      * @param {String} axis optional
43539      * @param {Ext.util.Point} p the point
43540      * @return {Ext.util.Offset}
43541      */
43542     getOutOfBoundOffset: function(axis, p) {
43543         if (!Ext.isObject(axis)) {
43544             if (axis == 'x') {
43545                 return this.getOutOfBoundOffsetX(p);
43546             } else {
43547                 return this.getOutOfBoundOffsetY(p);
43548             }
43549         } else {
43550             p = axis;
43551             var d = Ext.create('Ext.util.Offset');
43552             d.x = this.getOutOfBoundOffsetX(p.x);
43553             d.y = this.getOutOfBoundOffsetY(p.y);
43554             return d;
43555         }
43556
43557     },
43558
43559     /**
43560      * Get the offset amount on the x-axis
43561      * @param {Number} p the offset
43562      * @return {Number}
43563      */
43564     getOutOfBoundOffsetX: function(p) {
43565         if (p <= this.x) {
43566             return this.x - p;
43567         } else if (p >= this.right) {
43568             return this.right - p;
43569         }
43570
43571         return 0;
43572     },
43573
43574     /**
43575      * Get the offset amount on the y-axis
43576      * @param {Number} p the offset
43577      * @return {Number}
43578      */
43579     getOutOfBoundOffsetY: function(p) {
43580         if (p <= this.y) {
43581             return this.y - p;
43582         } else if (p >= this.bottom) {
43583             return this.bottom - p;
43584         }
43585
43586         return 0;
43587     },
43588
43589     /**
43590      * Check whether the point / offset is out of bound
43591      * @param {String} axis optional
43592      * @param {Ext.util.Point/Number} p the point / offset
43593      * @return {Boolean}
43594      */
43595     isOutOfBound: function(axis, p) {
43596         if (!Ext.isObject(axis)) {
43597             if (axis == 'x') {
43598                 return this.isOutOfBoundX(p);
43599             } else {
43600                 return this.isOutOfBoundY(p);
43601             }
43602         } else {
43603             p = axis;
43604             return (this.isOutOfBoundX(p.x) || this.isOutOfBoundY(p.y));
43605         }
43606     },
43607
43608     /**
43609      * Check whether the offset is out of bound in the x-axis
43610      * @param {Number} p the offset
43611      * @return {Boolean}
43612      */
43613     isOutOfBoundX: function(p) {
43614         return (p < this.x || p > this.right);
43615     },
43616
43617     /**
43618      * Check whether the offset is out of bound in the y-axis
43619      * @param {Number} p the offset
43620      * @return {Boolean}
43621      */
43622     isOutOfBoundY: function(p) {
43623         return (p < this.y || p > this.bottom);
43624     },
43625
43626     /*
43627      * Restrict a point within the region by a certain factor.
43628      * @param {String} axis Optional
43629      * @param {Ext.util.Point/Ext.util.Offset/Object} p
43630      * @param {Number} factor
43631      * @return {Ext.util.Point/Ext.util.Offset/Object/Number}
43632      */
43633     restrict: function(axis, p, factor) {
43634         if (Ext.isObject(axis)) {
43635             var newP;
43636
43637             factor = p;
43638             p = axis;
43639
43640             if (p.copy) {
43641                 newP = p.copy();
43642             }
43643             else {
43644                 newP = {
43645                     x: p.x,
43646                     y: p.y
43647                 };
43648             }
43649
43650             newP.x = this.restrictX(p.x, factor);
43651             newP.y = this.restrictY(p.y, factor);
43652             return newP;
43653         } else {
43654             if (axis == 'x') {
43655                 return this.restrictX(p, factor);
43656             } else {
43657                 return this.restrictY(p, factor);
43658             }
43659         }
43660     },
43661
43662     /*
43663      * Restrict an offset within the region by a certain factor, on the x-axis
43664      * @param {Number} p
43665      * @param {Number} factor The factor, optional, defaults to 1
43666      * @return
43667      */
43668     restrictX : function(p, factor) {
43669         if (!factor) {
43670             factor = 1;
43671         }
43672
43673         if (p <= this.x) {
43674             p -= (p - this.x) * factor;
43675         }
43676         else if (p >= this.right) {
43677             p -= (p - this.right) * factor;
43678         }
43679         return p;
43680     },
43681
43682     /*
43683      * Restrict an offset within the region by a certain factor, on the y-axis
43684      * @param {Number} p
43685      * @param {Number} factor The factor, optional, defaults to 1
43686      */
43687     restrictY : function(p, factor) {
43688         if (!factor) {
43689             factor = 1;
43690         }
43691
43692         if (p <= this.y) {
43693             p -= (p - this.y) * factor;
43694         }
43695         else if (p >= this.bottom) {
43696             p -= (p - this.bottom) * factor;
43697         }
43698         return p;
43699     },
43700
43701     /*
43702      * Get the width / height of this region
43703      * @return {Object} an object with width and height properties
43704      */
43705     getSize: function() {
43706         return {
43707             width: this.right - this.x,
43708             height: this.bottom - this.y
43709         };
43710     },
43711
43712     /**
43713      * Copy a new instance
43714      * @return {Ext.util.Region}
43715      */
43716     copy: function() {
43717         return new this.self(this.y, this.right, this.bottom, this.x);
43718     },
43719
43720     /**
43721      * Copy the values of another Region to this Region
43722      * @param {Region} The region to copy from.
43723      * @return {Ext.util.Point} this This point
43724      */
43725     copyFrom: function(p) {
43726         var me = this;
43727         me.top = me.y = me[1] = p.y;
43728         me.right = p.right;
43729         me.bottom = p.bottom;
43730         me.left = me.x = me[0] = p.x;
43731
43732         return this;
43733     },
43734
43735     /**
43736      * Dump this to an eye-friendly string, great for debugging
43737      * @return {String}
43738      */
43739     toString: function() {
43740         return "Region[" + this.top + "," + this.right + "," + this.bottom + "," + this.left + "]";
43741     },
43742
43743
43744     /**
43745      * Translate this region by the given offset amount
43746      * @param {Ext.util.Offset/Object} offset Object containing the <code>x</code> and <code>y</code> properties.
43747      * Or the x value is using the two argument form.
43748      * @param {Number} The y value unless using an Offset object.
43749      * @return {Ext.util.Region} this This Region
43750      */
43751     translateBy: function(x, y) {
43752         if (arguments.length == 1) {
43753             y = x.y;
43754             x = x.x;
43755         }
43756         var me = this;
43757         me.top = me.y += y;
43758         me.right += x;
43759         me.bottom += y;
43760         me.left = me.x += x;
43761
43762         return me;
43763     },
43764
43765     /**
43766      * Round all the properties of this region
43767      * @return {Ext.util.Region} this This Region
43768      */
43769     round: function() {
43770         var me = this;
43771         me.top = me.y = Math.round(me.y);
43772         me.right = Math.round(me.right);
43773         me.bottom = Math.round(me.bottom);
43774         me.left = me.x = Math.round(me.x);
43775
43776         return me;
43777     },
43778
43779     /**
43780      * Check whether this region is equivalent to the given region
43781      * @param {Ext.util.Region} region The region to compare with
43782      * @return {Boolean}
43783      */
43784     equals: function(region) {
43785         return (this.top == region.top && this.right == region.right && this.bottom == region.bottom && this.left == region.left);
43786     }
43787 });
43788
43789 /*
43790  * This is a derivative of the similarly named class in the YUI Library.
43791  * The original license:
43792  * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
43793  * Code licensed under the BSD License:
43794  * http://developer.yahoo.net/yui/license.txt
43795  */
43796
43797
43798 /**
43799  * @class Ext.dd.DragDropManager
43800  * DragDropManager is a singleton that tracks the element interaction for
43801  * all DragDrop items in the window.  Generally, you will not call
43802  * this class directly, but it does have helper methods that could
43803  * be useful in your DragDrop implementations.
43804  * @singleton
43805  */
43806 Ext.define('Ext.dd.DragDropManager', {
43807     singleton: true,
43808
43809     requires: ['Ext.util.Region'],
43810
43811     uses: ['Ext.tip.QuickTipManager'],
43812
43813     // shorter ClassName, to save bytes and use internally
43814     alternateClassName: ['Ext.dd.DragDropMgr', 'Ext.dd.DDM'],
43815     
43816     /**
43817      * Two dimensional Array of registered DragDrop objects.  The first
43818      * dimension is the DragDrop item group, the second the DragDrop
43819      * object.
43820      * @property ids
43821      * @type String[]
43822      * @private
43823      * @static
43824      */
43825     ids: {},
43826
43827     /**
43828      * Array of element ids defined as drag handles.  Used to determine
43829      * if the element that generated the mousedown event is actually the
43830      * handle and not the html element itself.
43831      * @property handleIds
43832      * @type String[]
43833      * @private
43834      * @static
43835      */
43836     handleIds: {},
43837
43838     /**
43839      * the DragDrop object that is currently being dragged
43840      * @property dragCurrent
43841      * @type DragDrop
43842      * @private
43843      * @static
43844      **/
43845     dragCurrent: null,
43846
43847     /**
43848      * the DragDrop object(s) that are being hovered over
43849      * @property dragOvers
43850      * @type Array
43851      * @private
43852      * @static
43853      */
43854     dragOvers: {},
43855
43856     /**
43857      * the X distance between the cursor and the object being dragged
43858      * @property deltaX
43859      * @type int
43860      * @private
43861      * @static
43862      */
43863     deltaX: 0,
43864
43865     /**
43866      * the Y distance between the cursor and the object being dragged
43867      * @property deltaY
43868      * @type int
43869      * @private
43870      * @static
43871      */
43872     deltaY: 0,
43873
43874     /**
43875      * Flag to determine if we should prevent the default behavior of the
43876      * events we define. By default this is true, but this can be set to
43877      * false if you need the default behavior (not recommended)
43878      * @property preventDefault
43879      * @type boolean
43880      * @static
43881      */
43882     preventDefault: true,
43883
43884     /**
43885      * Flag to determine if we should stop the propagation of the events
43886      * we generate. This is true by default but you may want to set it to
43887      * false if the html element contains other features that require the
43888      * mouse click.
43889      * @property stopPropagation
43890      * @type boolean
43891      * @static
43892      */
43893     stopPropagation: true,
43894
43895     /**
43896      * Internal flag that is set to true when drag and drop has been
43897      * intialized
43898      * @property initialized
43899      * @private
43900      * @static
43901      */
43902     initialized: false,
43903
43904     /**
43905      * All drag and drop can be disabled.
43906      * @property locked
43907      * @private
43908      * @static
43909      */
43910     locked: false,
43911
43912     /**
43913      * Called the first time an element is registered.
43914      * @method init
43915      * @private
43916      * @static
43917      */
43918     init: function() {
43919         this.initialized = true;
43920     },
43921
43922     /**
43923      * In point mode, drag and drop interaction is defined by the
43924      * location of the cursor during the drag/drop
43925      * @property POINT
43926      * @type int
43927      * @static
43928      */
43929     POINT: 0,
43930
43931     /**
43932      * In intersect mode, drag and drop interaction is defined by the
43933      * overlap of two or more drag and drop objects.
43934      * @property INTERSECT
43935      * @type int
43936      * @static
43937      */
43938     INTERSECT: 1,
43939
43940     /**
43941      * The current drag and drop mode.  Default: POINT
43942      * @property mode
43943      * @type int
43944      * @static
43945      */
43946     mode: 0,
43947
43948     /**
43949      * Runs method on all drag and drop objects
43950      * @method _execOnAll
43951      * @private
43952      * @static
43953      */
43954     _execOnAll: function(sMethod, args) {
43955         for (var i in this.ids) {
43956             for (var j in this.ids[i]) {
43957                 var oDD = this.ids[i][j];
43958                 if (! this.isTypeOfDD(oDD)) {
43959                     continue;
43960                 }
43961                 oDD[sMethod].apply(oDD, args);
43962             }
43963         }
43964     },
43965
43966     /**
43967      * Drag and drop initialization.  Sets up the global event handlers
43968      * @method _onLoad
43969      * @private
43970      * @static
43971      */
43972     _onLoad: function() {
43973
43974         this.init();
43975
43976         var Event = Ext.EventManager;
43977         Event.on(document, "mouseup",   this.handleMouseUp, this, true);
43978         Event.on(document, "mousemove", this.handleMouseMove, this, true);
43979         Event.on(window,   "unload",    this._onUnload, this, true);
43980         Event.on(window,   "resize",    this._onResize, this, true);
43981         // Event.on(window,   "mouseout",    this._test);
43982
43983     },
43984
43985     /**
43986      * Reset constraints on all drag and drop objs
43987      * @method _onResize
43988      * @private
43989      * @static
43990      */
43991     _onResize: function(e) {
43992         this._execOnAll("resetConstraints", []);
43993     },
43994
43995     /**
43996      * Lock all drag and drop functionality
43997      * @method lock
43998      * @static
43999      */
44000     lock: function() { this.locked = true; },
44001
44002     /**
44003      * Unlock all drag and drop functionality
44004      * @method unlock
44005      * @static
44006      */
44007     unlock: function() { this.locked = false; },
44008
44009     /**
44010      * Is drag and drop locked?
44011      * @method isLocked
44012      * @return {boolean} True if drag and drop is locked, false otherwise.
44013      * @static
44014      */
44015     isLocked: function() { return this.locked; },
44016
44017     /**
44018      * Location cache that is set for all drag drop objects when a drag is
44019      * initiated, cleared when the drag is finished.
44020      * @property locationCache
44021      * @private
44022      * @static
44023      */
44024     locationCache: {},
44025
44026     /**
44027      * Set useCache to false if you want to force object the lookup of each
44028      * drag and drop linked element constantly during a drag.
44029      * @property useCache
44030      * @type boolean
44031      * @static
44032      */
44033     useCache: true,
44034
44035     /**
44036      * The number of pixels that the mouse needs to move after the
44037      * mousedown before the drag is initiated.  Default=3;
44038      * @property clickPixelThresh
44039      * @type int
44040      * @static
44041      */
44042     clickPixelThresh: 3,
44043
44044     /**
44045      * The number of milliseconds after the mousedown event to initiate the
44046      * drag if we don't get a mouseup event. Default=350
44047      * @property clickTimeThresh
44048      * @type int
44049      * @static
44050      */
44051     clickTimeThresh: 350,
44052
44053     /**
44054      * Flag that indicates that either the drag pixel threshold or the
44055      * mousdown time threshold has been met
44056      * @property dragThreshMet
44057      * @type boolean
44058      * @private
44059      * @static
44060      */
44061     dragThreshMet: false,
44062
44063     /**
44064      * Timeout used for the click time threshold
44065      * @property clickTimeout
44066      * @type Object
44067      * @private
44068      * @static
44069      */
44070     clickTimeout: null,
44071
44072     /**
44073      * The X position of the mousedown event stored for later use when a
44074      * drag threshold is met.
44075      * @property startX
44076      * @type int
44077      * @private
44078      * @static
44079      */
44080     startX: 0,
44081
44082     /**
44083      * The Y position of the mousedown event stored for later use when a
44084      * drag threshold is met.
44085      * @property startY
44086      * @type int
44087      * @private
44088      * @static
44089      */
44090     startY: 0,
44091
44092     /**
44093      * Each DragDrop instance must be registered with the DragDropManager.
44094      * This is executed in DragDrop.init()
44095      * @method regDragDrop
44096      * @param {DragDrop} oDD the DragDrop object to register
44097      * @param {String} sGroup the name of the group this element belongs to
44098      * @static
44099      */
44100     regDragDrop: function(oDD, sGroup) {
44101         if (!this.initialized) { this.init(); }
44102
44103         if (!this.ids[sGroup]) {
44104             this.ids[sGroup] = {};
44105         }
44106         this.ids[sGroup][oDD.id] = oDD;
44107     },
44108
44109     /**
44110      * Removes the supplied dd instance from the supplied group. Executed
44111      * by DragDrop.removeFromGroup, so don't call this function directly.
44112      * @method removeDDFromGroup
44113      * @private
44114      * @static
44115      */
44116     removeDDFromGroup: function(oDD, sGroup) {
44117         if (!this.ids[sGroup]) {
44118             this.ids[sGroup] = {};
44119         }
44120
44121         var obj = this.ids[sGroup];
44122         if (obj && obj[oDD.id]) {
44123             delete obj[oDD.id];
44124         }
44125     },
44126
44127     /**
44128      * Unregisters a drag and drop item.  This is executed in
44129      * DragDrop.unreg, use that method instead of calling this directly.
44130      * @method _remove
44131      * @private
44132      * @static
44133      */
44134     _remove: function(oDD) {
44135         for (var g in oDD.groups) {
44136             if (g && this.ids[g] && this.ids[g][oDD.id]) {
44137                 delete this.ids[g][oDD.id];
44138             }
44139         }
44140         delete this.handleIds[oDD.id];
44141     },
44142
44143     /**
44144      * Each DragDrop handle element must be registered.  This is done
44145      * automatically when executing DragDrop.setHandleElId()
44146      * @method regHandle
44147      * @param {String} sDDId the DragDrop id this element is a handle for
44148      * @param {String} sHandleId the id of the element that is the drag
44149      * handle
44150      * @static
44151      */
44152     regHandle: function(sDDId, sHandleId) {
44153         if (!this.handleIds[sDDId]) {
44154             this.handleIds[sDDId] = {};
44155         }
44156         this.handleIds[sDDId][sHandleId] = sHandleId;
44157     },
44158
44159     /**
44160      * Utility function to determine if a given element has been
44161      * registered as a drag drop item.
44162      * @method isDragDrop
44163      * @param {String} id the element id to check
44164      * @return {boolean} true if this element is a DragDrop item,
44165      * false otherwise
44166      * @static
44167      */
44168     isDragDrop: function(id) {
44169         return ( this.getDDById(id) ) ? true : false;
44170     },
44171
44172     /**
44173      * Returns the drag and drop instances that are in all groups the
44174      * passed in instance belongs to.
44175      * @method getRelated
44176      * @param {DragDrop} p_oDD the obj to get related data for
44177      * @param {boolean} bTargetsOnly if true, only return targetable objs
44178      * @return {DragDrop[]} the related instances
44179      * @static
44180      */
44181     getRelated: function(p_oDD, bTargetsOnly) {
44182         var oDDs = [];
44183         for (var i in p_oDD.groups) {
44184             for (var j in this.ids[i]) {
44185                 var dd = this.ids[i][j];
44186                 if (! this.isTypeOfDD(dd)) {
44187                     continue;
44188                 }
44189                 if (!bTargetsOnly || dd.isTarget) {
44190                     oDDs[oDDs.length] = dd;
44191                 }
44192             }
44193         }
44194
44195         return oDDs;
44196     },
44197
44198     /**
44199      * Returns true if the specified dd target is a legal target for
44200      * the specifice drag obj
44201      * @method isLegalTarget
44202      * @param {DragDrop} oDD the drag obj
44203      * @param {DragDrop} oTargetDD the target
44204      * @return {boolean} true if the target is a legal target for the
44205      * dd obj
44206      * @static
44207      */
44208     isLegalTarget: function (oDD, oTargetDD) {
44209         var targets = this.getRelated(oDD, true);
44210         for (var i=0, len=targets.length;i<len;++i) {
44211             if (targets[i].id == oTargetDD.id) {
44212                 return true;
44213             }
44214         }
44215
44216         return false;
44217     },
44218
44219     /**
44220      * My goal is to be able to transparently determine if an object is
44221      * typeof DragDrop, and the exact subclass of DragDrop.  typeof
44222      * returns "object", oDD.constructor.toString() always returns
44223      * "DragDrop" and not the name of the subclass.  So for now it just
44224      * evaluates a well-known variable in DragDrop.
44225      * @method isTypeOfDD
44226      * @param {Object} the object to evaluate
44227      * @return {boolean} true if typeof oDD = DragDrop
44228      * @static
44229      */
44230     isTypeOfDD: function (oDD) {
44231         return (oDD && oDD.__ygDragDrop);
44232     },
44233
44234     /**
44235      * Utility function to determine if a given element has been
44236      * registered as a drag drop handle for the given Drag Drop object.
44237      * @method isHandle
44238      * @param {String} id the element id to check
44239      * @return {boolean} true if this element is a DragDrop handle, false
44240      * otherwise
44241      * @static
44242      */
44243     isHandle: function(sDDId, sHandleId) {
44244         return ( this.handleIds[sDDId] &&
44245                         this.handleIds[sDDId][sHandleId] );
44246     },
44247
44248     /**
44249      * Returns the DragDrop instance for a given id
44250      * @method getDDById
44251      * @param {String} id the id of the DragDrop object
44252      * @return {DragDrop} the drag drop object, null if it is not found
44253      * @static
44254      */
44255     getDDById: function(id) {
44256         for (var i in this.ids) {
44257             if (this.ids[i][id]) {
44258                 return this.ids[i][id];
44259             }
44260         }
44261         return null;
44262     },
44263
44264     /**
44265      * Fired after a registered DragDrop object gets the mousedown event.
44266      * Sets up the events required to track the object being dragged
44267      * @method handleMouseDown
44268      * @param {Event} e the event
44269      * @param oDD the DragDrop object being dragged
44270      * @private
44271      * @static
44272      */
44273     handleMouseDown: function(e, oDD) {
44274         if(Ext.tip.QuickTipManager){
44275             Ext.tip.QuickTipManager.ddDisable();
44276         }
44277         if(this.dragCurrent){
44278             // the original browser mouseup wasn't handled (e.g. outside FF browser window)
44279             // so clean up first to avoid breaking the next drag
44280             this.handleMouseUp(e);
44281         }
44282         
44283         this.currentTarget = e.getTarget();
44284         this.dragCurrent = oDD;
44285
44286         var el = oDD.getEl();
44287
44288         // track start position
44289         this.startX = e.getPageX();
44290         this.startY = e.getPageY();
44291
44292         this.deltaX = this.startX - el.offsetLeft;
44293         this.deltaY = this.startY - el.offsetTop;
44294
44295         this.dragThreshMet = false;
44296
44297         this.clickTimeout = setTimeout(
44298                 function() {
44299                     var DDM = Ext.dd.DragDropManager;
44300                     DDM.startDrag(DDM.startX, DDM.startY);
44301                 },
44302                 this.clickTimeThresh );
44303     },
44304
44305     /**
44306      * Fired when either the drag pixel threshol or the mousedown hold
44307      * time threshold has been met.
44308      * @method startDrag
44309      * @param x {int} the X position of the original mousedown
44310      * @param y {int} the Y position of the original mousedown
44311      * @static
44312      */
44313     startDrag: function(x, y) {
44314         clearTimeout(this.clickTimeout);
44315         if (this.dragCurrent) {
44316             this.dragCurrent.b4StartDrag(x, y);
44317             this.dragCurrent.startDrag(x, y);
44318         }
44319         this.dragThreshMet = true;
44320     },
44321
44322     /**
44323      * Internal function to handle the mouseup event.  Will be invoked
44324      * from the context of the document.
44325      * @method handleMouseUp
44326      * @param {Event} e the event
44327      * @private
44328      * @static
44329      */
44330     handleMouseUp: function(e) {
44331
44332         if(Ext.tip.QuickTipManager){
44333             Ext.tip.QuickTipManager.ddEnable();
44334         }
44335         if (! this.dragCurrent) {
44336             return;
44337         }
44338
44339         clearTimeout(this.clickTimeout);
44340
44341         if (this.dragThreshMet) {
44342             this.fireEvents(e, true);
44343         } else {
44344         }
44345
44346         this.stopDrag(e);
44347
44348         this.stopEvent(e);
44349     },
44350
44351     /**
44352      * Utility to stop event propagation and event default, if these
44353      * features are turned on.
44354      * @method stopEvent
44355      * @param {Event} e the event as returned by this.getEvent()
44356      * @static
44357      */
44358     stopEvent: function(e){
44359         if(this.stopPropagation) {
44360             e.stopPropagation();
44361         }
44362
44363         if (this.preventDefault) {
44364             e.preventDefault();
44365         }
44366     },
44367
44368     /**
44369      * Internal function to clean up event handlers after the drag
44370      * operation is complete
44371      * @method stopDrag
44372      * @param {Event} e the event
44373      * @private
44374      * @static
44375      */
44376     stopDrag: function(e) {
44377         // Fire the drag end event for the item that was dragged
44378         if (this.dragCurrent) {
44379             if (this.dragThreshMet) {
44380                 this.dragCurrent.b4EndDrag(e);
44381                 this.dragCurrent.endDrag(e);
44382             }
44383
44384             this.dragCurrent.onMouseUp(e);
44385         }
44386
44387         this.dragCurrent = null;
44388         this.dragOvers = {};
44389     },
44390
44391     /**
44392      * Internal function to handle the mousemove event.  Will be invoked
44393      * from the context of the html element.
44394      *
44395      * @TODO figure out what we can do about mouse events lost when the
44396      * user drags objects beyond the window boundary.  Currently we can
44397      * detect this in internet explorer by verifying that the mouse is
44398      * down during the mousemove event.  Firefox doesn't give us the
44399      * button state on the mousemove event.
44400      * @method handleMouseMove
44401      * @param {Event} e the event
44402      * @private
44403      * @static
44404      */
44405     handleMouseMove: function(e) {
44406         if (! this.dragCurrent) {
44407             return true;
44408         }
44409         // var button = e.which || e.button;
44410
44411         // check for IE mouseup outside of page boundary
44412         if (Ext.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
44413             this.stopEvent(e);
44414             return this.handleMouseUp(e);
44415         }
44416
44417         if (!this.dragThreshMet) {
44418             var diffX = Math.abs(this.startX - e.getPageX());
44419             var diffY = Math.abs(this.startY - e.getPageY());
44420             if (diffX > this.clickPixelThresh ||
44421                         diffY > this.clickPixelThresh) {
44422                 this.startDrag(this.startX, this.startY);
44423             }
44424         }
44425
44426         if (this.dragThreshMet) {
44427             this.dragCurrent.b4Drag(e);
44428             this.dragCurrent.onDrag(e);
44429             if(!this.dragCurrent.moveOnly){
44430                 this.fireEvents(e, false);
44431             }
44432         }
44433
44434         this.stopEvent(e);
44435
44436         return true;
44437     },
44438
44439     /**
44440      * Iterates over all of the DragDrop elements to find ones we are
44441      * hovering over or dropping on
44442      * @method fireEvents
44443      * @param {Event} e the event
44444      * @param {boolean} isDrop is this a drop op or a mouseover op?
44445      * @private
44446      * @static
44447      */
44448     fireEvents: function(e, isDrop) {
44449         var dc = this.dragCurrent;
44450
44451         // If the user did the mouse up outside of the window, we could
44452         // get here even though we have ended the drag.
44453         if (!dc || dc.isLocked()) {
44454             return;
44455         }
44456
44457         var pt = e.getPoint();
44458
44459         // cache the previous dragOver array
44460         var oldOvers = [];
44461
44462         var outEvts   = [];
44463         var overEvts  = [];
44464         var dropEvts  = [];
44465         var enterEvts = [];
44466
44467         // Check to see if the object(s) we were hovering over is no longer
44468         // being hovered over so we can fire the onDragOut event
44469         for (var i in this.dragOvers) {
44470
44471             var ddo = this.dragOvers[i];
44472
44473             if (! this.isTypeOfDD(ddo)) {
44474                 continue;
44475             }
44476
44477             if (! this.isOverTarget(pt, ddo, this.mode)) {
44478                 outEvts.push( ddo );
44479             }
44480
44481             oldOvers[i] = true;
44482             delete this.dragOvers[i];
44483         }
44484
44485         for (var sGroup in dc.groups) {
44486
44487             if ("string" != typeof sGroup) {
44488                 continue;
44489             }
44490
44491             for (i in this.ids[sGroup]) {
44492                 var oDD = this.ids[sGroup][i];
44493                 if (! this.isTypeOfDD(oDD)) {
44494                     continue;
44495                 }
44496
44497                 if (oDD.isTarget && !oDD.isLocked() && ((oDD != dc) || (dc.ignoreSelf === false))) {
44498                     if (this.isOverTarget(pt, oDD, this.mode)) {
44499                         // look for drop interactions
44500                         if (isDrop) {
44501                             dropEvts.push( oDD );
44502                         // look for drag enter and drag over interactions
44503                         } else {
44504
44505                             // initial drag over: dragEnter fires
44506                             if (!oldOvers[oDD.id]) {
44507                                 enterEvts.push( oDD );
44508                             // subsequent drag overs: dragOver fires
44509                             } else {
44510                                 overEvts.push( oDD );
44511                             }
44512
44513                             this.dragOvers[oDD.id] = oDD;
44514                         }
44515                     }
44516                 }
44517             }
44518         }
44519
44520         if (this.mode) {
44521             if (outEvts.length) {
44522                 dc.b4DragOut(e, outEvts);
44523                 dc.onDragOut(e, outEvts);
44524             }
44525
44526             if (enterEvts.length) {
44527                 dc.onDragEnter(e, enterEvts);
44528             }
44529
44530             if (overEvts.length) {
44531                 dc.b4DragOver(e, overEvts);
44532                 dc.onDragOver(e, overEvts);
44533             }
44534
44535             if (dropEvts.length) {
44536                 dc.b4DragDrop(e, dropEvts);
44537                 dc.onDragDrop(e, dropEvts);
44538             }
44539
44540         } else {
44541             // fire dragout events
44542             var len = 0;
44543             for (i=0, len=outEvts.length; i<len; ++i) {
44544                 dc.b4DragOut(e, outEvts[i].id);
44545                 dc.onDragOut(e, outEvts[i].id);
44546             }
44547
44548             // fire enter events
44549             for (i=0,len=enterEvts.length; i<len; ++i) {
44550                 // dc.b4DragEnter(e, oDD.id);
44551                 dc.onDragEnter(e, enterEvts[i].id);
44552             }
44553
44554             // fire over events
44555             for (i=0,len=overEvts.length; i<len; ++i) {
44556                 dc.b4DragOver(e, overEvts[i].id);
44557                 dc.onDragOver(e, overEvts[i].id);
44558             }
44559
44560             // fire drop events
44561             for (i=0, len=dropEvts.length; i<len; ++i) {
44562                 dc.b4DragDrop(e, dropEvts[i].id);
44563                 dc.onDragDrop(e, dropEvts[i].id);
44564             }
44565
44566         }
44567
44568         // notify about a drop that did not find a target
44569         if (isDrop && !dropEvts.length) {
44570             dc.onInvalidDrop(e);
44571         }
44572
44573     },
44574
44575     /**
44576      * Helper function for getting the best match from the list of drag
44577      * and drop objects returned by the drag and drop events when we are
44578      * in INTERSECT mode.  It returns either the first object that the
44579      * cursor is over, or the object that has the greatest overlap with
44580      * the dragged element.
44581      * @method getBestMatch
44582      * @param  {DragDrop[]} dds The array of drag and drop objects
44583      * targeted
44584      * @return {DragDrop}       The best single match
44585      * @static
44586      */
44587     getBestMatch: function(dds) {
44588         var winner = null;
44589         // Return null if the input is not what we expect
44590         //if (!dds || !dds.length || dds.length == 0) {
44591            // winner = null;
44592         // If there is only one item, it wins
44593         //} else if (dds.length == 1) {
44594
44595         var len = dds.length;
44596
44597         if (len == 1) {
44598             winner = dds[0];
44599         } else {
44600             // Loop through the targeted items
44601             for (var i=0; i<len; ++i) {
44602                 var dd = dds[i];
44603                 // If the cursor is over the object, it wins.  If the
44604                 // cursor is over multiple matches, the first one we come
44605                 // to wins.
44606                 if (dd.cursorIsOver) {
44607                     winner = dd;
44608                     break;
44609                 // Otherwise the object with the most overlap wins
44610                 } else {
44611                     if (!winner ||
44612                         winner.overlap.getArea() < dd.overlap.getArea()) {
44613                         winner = dd;
44614                     }
44615                 }
44616             }
44617         }
44618
44619         return winner;
44620     },
44621
44622     /**
44623      * Refreshes the cache of the top-left and bottom-right points of the
44624      * drag and drop objects in the specified group(s).  This is in the
44625      * format that is stored in the drag and drop instance, so typical
44626      * usage is:
44627      * <code>
44628      * Ext.dd.DragDropManager.refreshCache(ddinstance.groups);
44629      * </code>
44630      * Alternatively:
44631      * <code>
44632      * Ext.dd.DragDropManager.refreshCache({group1:true, group2:true});
44633      * </code>
44634      * @TODO this really should be an indexed array.  Alternatively this
44635      * method could accept both.
44636      * @method refreshCache
44637      * @param {Object} groups an associative array of groups to refresh
44638      * @static
44639      */
44640     refreshCache: function(groups) {
44641         for (var sGroup in groups) {
44642             if ("string" != typeof sGroup) {
44643                 continue;
44644             }
44645             for (var i in this.ids[sGroup]) {
44646                 var oDD = this.ids[sGroup][i];
44647
44648                 if (this.isTypeOfDD(oDD)) {
44649                 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
44650                     var loc = this.getLocation(oDD);
44651                     if (loc) {
44652                         this.locationCache[oDD.id] = loc;
44653                     } else {
44654                         delete this.locationCache[oDD.id];
44655                         // this will unregister the drag and drop object if
44656                         // the element is not in a usable state
44657                         // oDD.unreg();
44658                     }
44659                 }
44660             }
44661         }
44662     },
44663
44664     /**
44665      * This checks to make sure an element exists and is in the DOM.  The
44666      * main purpose is to handle cases where innerHTML is used to remove
44667      * drag and drop objects from the DOM.  IE provides an 'unspecified
44668      * error' when trying to access the offsetParent of such an element
44669      * @method verifyEl
44670      * @param {HTMLElement} el the element to check
44671      * @return {boolean} true if the element looks usable
44672      * @static
44673      */
44674     verifyEl: function(el) {
44675         if (el) {
44676             var parent;
44677             if(Ext.isIE){
44678                 try{
44679                     parent = el.offsetParent;
44680                 }catch(e){}
44681             }else{
44682                 parent = el.offsetParent;
44683             }
44684             if (parent) {
44685                 return true;
44686             }
44687         }
44688
44689         return false;
44690     },
44691
44692     /**
44693      * Returns a Region object containing the drag and drop element's position
44694      * and size, including the padding configured for it
44695      * @method getLocation
44696      * @param {DragDrop} oDD the drag and drop object to get the
44697      *                       location for
44698      * @return {Ext.util.Region} a Region object representing the total area
44699      *                             the element occupies, including any padding
44700      *                             the instance is configured for.
44701      * @static
44702      */
44703     getLocation: function(oDD) {
44704         if (! this.isTypeOfDD(oDD)) {
44705             return null;
44706         }
44707
44708         //delegate getLocation method to the
44709         //drag and drop target.
44710         if (oDD.getRegion) {
44711             return oDD.getRegion();
44712         }
44713
44714         var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
44715
44716         try {
44717             pos= Ext.core.Element.getXY(el);
44718         } catch (e) { }
44719
44720         if (!pos) {
44721             return null;
44722         }
44723
44724         x1 = pos[0];
44725         x2 = x1 + el.offsetWidth;
44726         y1 = pos[1];
44727         y2 = y1 + el.offsetHeight;
44728
44729         t = y1 - oDD.padding[0];
44730         r = x2 + oDD.padding[1];
44731         b = y2 + oDD.padding[2];
44732         l = x1 - oDD.padding[3];
44733
44734         return Ext.create('Ext.util.Region', t, r, b, l);
44735     },
44736
44737     /**
44738      * Checks the cursor location to see if it over the target
44739      * @method isOverTarget
44740      * @param {Ext.util.Point} pt The point to evaluate
44741      * @param {DragDrop} oTarget the DragDrop object we are inspecting
44742      * @return {boolean} true if the mouse is over the target
44743      * @private
44744      * @static
44745      */
44746     isOverTarget: function(pt, oTarget, intersect) {
44747         // use cache if available
44748         var loc = this.locationCache[oTarget.id];
44749         if (!loc || !this.useCache) {
44750             loc = this.getLocation(oTarget);
44751             this.locationCache[oTarget.id] = loc;
44752
44753         }
44754
44755         if (!loc) {
44756             return false;
44757         }
44758
44759         oTarget.cursorIsOver = loc.contains( pt );
44760
44761         // DragDrop is using this as a sanity check for the initial mousedown
44762         // in this case we are done.  In POINT mode, if the drag obj has no
44763         // contraints, we are also done. Otherwise we need to evaluate the
44764         // location of the target as related to the actual location of the
44765         // dragged element.
44766         var dc = this.dragCurrent;
44767         if (!dc || !dc.getTargetCoord ||
44768                 (!intersect && !dc.constrainX && !dc.constrainY)) {
44769             return oTarget.cursorIsOver;
44770         }
44771
44772         oTarget.overlap = null;
44773
44774         // Get the current location of the drag element, this is the
44775         // location of the mouse event less the delta that represents
44776         // where the original mousedown happened on the element.  We
44777         // need to consider constraints and ticks as well.
44778         var pos = dc.getTargetCoord(pt.x, pt.y);
44779
44780         var el = dc.getDragEl();
44781         var curRegion = Ext.create('Ext.util.Region', pos.y,
44782                                                pos.x + el.offsetWidth,
44783                                                pos.y + el.offsetHeight,
44784                                                pos.x );
44785
44786         var overlap = curRegion.intersect(loc);
44787
44788         if (overlap) {
44789             oTarget.overlap = overlap;
44790             return (intersect) ? true : oTarget.cursorIsOver;
44791         } else {
44792             return false;
44793         }
44794     },
44795
44796     /**
44797      * unload event handler
44798      * @method _onUnload
44799      * @private
44800      * @static
44801      */
44802     _onUnload: function(e, me) {
44803         Ext.dd.DragDropManager.unregAll();
44804     },
44805
44806     /**
44807      * Cleans up the drag and drop events and objects.
44808      * @method unregAll
44809      * @private
44810      * @static
44811      */
44812     unregAll: function() {
44813
44814         if (this.dragCurrent) {
44815             this.stopDrag();
44816             this.dragCurrent = null;
44817         }
44818
44819         this._execOnAll("unreg", []);
44820
44821         for (var i in this.elementCache) {
44822             delete this.elementCache[i];
44823         }
44824
44825         this.elementCache = {};
44826         this.ids = {};
44827     },
44828
44829     /**
44830      * A cache of DOM elements
44831      * @property elementCache
44832      * @private
44833      * @static
44834      */
44835     elementCache: {},
44836
44837     /**
44838      * Get the wrapper for the DOM element specified
44839      * @method getElWrapper
44840      * @param {String} id the id of the element to get
44841      * @return {Ext.dd.DDM.ElementWrapper} the wrapped element
44842      * @private
44843      * @deprecated This wrapper isn't that useful
44844      * @static
44845      */
44846     getElWrapper: function(id) {
44847         var oWrapper = this.elementCache[id];
44848         if (!oWrapper || !oWrapper.el) {
44849             oWrapper = this.elementCache[id] =
44850                 new this.ElementWrapper(Ext.getDom(id));
44851         }
44852         return oWrapper;
44853     },
44854
44855     /**
44856      * Returns the actual DOM element
44857      * @method getElement
44858      * @param {String} id the id of the elment to get
44859      * @return {Object} The element
44860      * @deprecated use Ext.lib.Ext.getDom instead
44861      * @static
44862      */
44863     getElement: function(id) {
44864         return Ext.getDom(id);
44865     },
44866
44867     /**
44868      * Returns the style property for the DOM element (i.e.,
44869      * document.getElById(id).style)
44870      * @method getCss
44871      * @param {String} id the id of the elment to get
44872      * @return {Object} The style property of the element
44873      * @static
44874      */
44875     getCss: function(id) {
44876         var el = Ext.getDom(id);
44877         return (el) ? el.style : null;
44878     },
44879
44880     /**
44881      * Inner class for cached elements
44882      * @class Ext.dd.DragDropManager.ElementWrapper
44883      * @for DragDropManager
44884      * @private
44885      * @deprecated
44886      */
44887     ElementWrapper: function(el) {
44888             /**
44889              * The element
44890              * @property el
44891              */
44892             this.el = el || null;
44893             /**
44894              * The element id
44895              * @property id
44896              */
44897             this.id = this.el && el.id;
44898             /**
44899              * A reference to the style property
44900              * @property css
44901              */
44902             this.css = this.el && el.style;
44903         },
44904
44905     /**
44906      * Returns the X position of an html element
44907      * @method getPosX
44908      * @param el the element for which to get the position
44909      * @return {int} the X coordinate
44910      * @for DragDropManager
44911      * @static
44912      */
44913     getPosX: function(el) {
44914         return Ext.core.Element.getX(el);
44915     },
44916
44917     /**
44918      * Returns the Y position of an html element
44919      * @method getPosY
44920      * @param el the element for which to get the position
44921      * @return {int} the Y coordinate
44922      * @static
44923      */
44924     getPosY: function(el) {
44925         return Ext.core.Element.getY(el);
44926     },
44927
44928     /**
44929      * Swap two nodes.  In IE, we use the native method, for others we
44930      * emulate the IE behavior
44931      * @method swapNode
44932      * @param n1 the first node to swap
44933      * @param n2 the other node to swap
44934      * @static
44935      */
44936     swapNode: function(n1, n2) {
44937         if (n1.swapNode) {
44938             n1.swapNode(n2);
44939         } else {
44940             var p = n2.parentNode;
44941             var s = n2.nextSibling;
44942
44943             if (s == n1) {
44944                 p.insertBefore(n1, n2);
44945             } else if (n2 == n1.nextSibling) {
44946                 p.insertBefore(n2, n1);
44947             } else {
44948                 n1.parentNode.replaceChild(n2, n1);
44949                 p.insertBefore(n1, s);
44950             }
44951         }
44952     },
44953
44954     /**
44955      * Returns the current scroll position
44956      * @method getScroll
44957      * @private
44958      * @static
44959      */
44960     getScroll: function () {
44961         var doc   = window.document,
44962             docEl = doc.documentElement,
44963             body  = doc.body,
44964             top   = 0,
44965             left  = 0;
44966             
44967         if (Ext.isGecko4) {
44968             top  = window.scrollYOffset;
44969             left = window.scrollXOffset;
44970         } else {
44971             if (docEl && (docEl.scrollTop || docEl.scrollLeft)) {
44972                 top  = docEl.scrollTop;
44973                 left = docEl.scrollLeft;
44974             } else if (body) {
44975                 top  = body.scrollTop;
44976                 left = body.scrollLeft;
44977             } 
44978         }
44979         return {
44980             top: top,
44981             left: left
44982         };
44983     },
44984
44985     /**
44986      * Returns the specified element style property
44987      * @method getStyle
44988      * @param {HTMLElement} el          the element
44989      * @param {string}      styleProp   the style property
44990      * @return {string} The value of the style property
44991      * @static
44992      */
44993     getStyle: function(el, styleProp) {
44994         return Ext.fly(el).getStyle(styleProp);
44995     },
44996
44997     /**
44998      * Gets the scrollTop
44999      * @method getScrollTop
45000      * @return {int} the document's scrollTop
45001      * @static
45002      */
45003     getScrollTop: function () {
45004         return this.getScroll().top;
45005     },
45006
45007     /**
45008      * Gets the scrollLeft
45009      * @method getScrollLeft
45010      * @return {int} the document's scrollTop
45011      * @static
45012      */
45013     getScrollLeft: function () {
45014         return this.getScroll().left;
45015     },
45016
45017     /**
45018      * Sets the x/y position of an element to the location of the
45019      * target element.
45020      * @method moveToEl
45021      * @param {HTMLElement} moveEl      The element to move
45022      * @param {HTMLElement} targetEl    The position reference element
45023      * @static
45024      */
45025     moveToEl: function (moveEl, targetEl) {
45026         var aCoord = Ext.core.Element.getXY(targetEl);
45027         Ext.core.Element.setXY(moveEl, aCoord);
45028     },
45029
45030     /**
45031      * Numeric array sort function
45032      * @method numericSort
45033      * @static
45034      */
45035     numericSort: function(a, b) {
45036         return (a - b);
45037     },
45038
45039     /**
45040      * Internal counter
45041      * @property _timeoutCount
45042      * @private
45043      * @static
45044      */
45045     _timeoutCount: 0,
45046
45047     /**
45048      * Trying to make the load order less important.  Without this we get
45049      * an error if this file is loaded before the Event Utility.
45050      * @method _addListeners
45051      * @private
45052      * @static
45053      */
45054     _addListeners: function() {
45055         if ( document ) {
45056             this._onLoad();
45057         } else {
45058             if (this._timeoutCount > 2000) {
45059             } else {
45060                 setTimeout(this._addListeners, 10);
45061                 if (document && document.body) {
45062                     this._timeoutCount += 1;
45063                 }
45064             }
45065         }
45066     },
45067
45068     /**
45069      * Recursively searches the immediate parent and all child nodes for
45070      * the handle element in order to determine wheter or not it was
45071      * clicked.
45072      * @method handleWasClicked
45073      * @param node the html element to inspect
45074      * @static
45075      */
45076     handleWasClicked: function(node, id) {
45077         if (this.isHandle(id, node.id)) {
45078             return true;
45079         } else {
45080             // check to see if this is a text node child of the one we want
45081             var p = node.parentNode;
45082
45083             while (p) {
45084                 if (this.isHandle(id, p.id)) {
45085                     return true;
45086                 } else {
45087                     p = p.parentNode;
45088                 }
45089             }
45090         }
45091
45092         return false;
45093     }
45094 }, function() {
45095     this._addListeners();
45096 });
45097
45098 /**
45099  * @class Ext.layout.container.Box
45100  * @extends Ext.layout.container.Container
45101  * <p>Base Class for HBoxLayout and VBoxLayout Classes. Generally it should not need to be used directly.</p>
45102  */
45103
45104 Ext.define('Ext.layout.container.Box', {
45105
45106     /* Begin Definitions */
45107
45108     alias: ['layout.box'],
45109     extend: 'Ext.layout.container.Container',
45110     alternateClassName: 'Ext.layout.BoxLayout',
45111     
45112     requires: [
45113         'Ext.layout.container.boxOverflow.None',
45114         'Ext.layout.container.boxOverflow.Menu',
45115         'Ext.layout.container.boxOverflow.Scroller',
45116         'Ext.util.Format',
45117         'Ext.dd.DragDropManager'
45118     ],
45119
45120     /* End Definitions */
45121
45122     /**
45123      * @cfg {Mixed} animate
45124      * <p>If truthy, child Component are <i>animated</i> into position whenever the Container
45125      * is layed out. If this option is numeric, it is used as the animation duration in milliseconds.</p>
45126      * <p>May be set as a property at any time.</p>
45127      */
45128
45129     /**
45130      * @cfg {Object} defaultMargins
45131      * <p>If the individual contained items do not have a <tt>margins</tt>
45132      * property specified or margin specified via CSS, the default margins from this property will be
45133      * applied to each item.</p>
45134      * <br><p>This property may be specified as an object containing margins
45135      * to apply in the format:</p><pre><code>
45136 {
45137     top: (top margin),
45138     right: (right margin),
45139     bottom: (bottom margin),
45140     left: (left margin)
45141 }</code></pre>
45142      * <p>This property may also be specified as a string containing
45143      * space-separated, numeric margin values. The order of the sides associated
45144      * with each value matches the way CSS processes margin values:</p>
45145      * <div class="mdetail-params"><ul>
45146      * <li>If there is only one value, it applies to all sides.</li>
45147      * <li>If there are two values, the top and bottom borders are set to the
45148      * first value and the right and left are set to the second.</li>
45149      * <li>If there are three values, the top is set to the first value, the left
45150      * and right are set to the second, and the bottom is set to the third.</li>
45151      * <li>If there are four values, they apply to the top, right, bottom, and
45152      * left, respectively.</li>
45153      * </ul></div>
45154      * <p>Defaults to:</p><pre><code>
45155      * {top:0, right:0, bottom:0, left:0}
45156      * </code></pre>
45157      */
45158     defaultMargins: {
45159         top: 0,
45160         right: 0,
45161         bottom: 0,
45162         left: 0
45163     },
45164
45165     /**
45166      * @cfg {String} padding
45167      * <p>Sets the padding to be applied to all child items managed by this layout.</p>
45168      * <p>This property must be specified as a string containing
45169      * space-separated, numeric padding values. The order of the sides associated
45170      * with each value matches the way CSS processes padding values:</p>
45171      * <div class="mdetail-params"><ul>
45172      * <li>If there is only one value, it applies to all sides.</li>
45173      * <li>If there are two values, the top and bottom borders are set to the
45174      * first value and the right and left are set to the second.</li>
45175      * <li>If there are three values, the top is set to the first value, the left
45176      * and right are set to the second, and the bottom is set to the third.</li>
45177      * <li>If there are four values, they apply to the top, right, bottom, and
45178      * left, respectively.</li>
45179      * </ul></div>
45180      * <p>Defaults to: <code>"0"</code></p>
45181      */
45182     padding: '0',
45183     // documented in subclasses
45184     pack: 'start',
45185
45186     /**
45187      * @cfg {String} pack
45188      * Controls how the child items of the container are packed together. Acceptable configuration values
45189      * for this property are:
45190      * <div class="mdetail-params"><ul>
45191      * <li><b><tt>start</tt></b> : <b>Default</b><div class="sub-desc">child items are packed together at
45192      * <b>left</b> side of container</div></li>
45193      * <li><b><tt>center</tt></b> : <div class="sub-desc">child items are packed together at
45194      * <b>mid-width</b> of container</div></li>
45195      * <li><b><tt>end</tt></b> : <div class="sub-desc">child items are packed together at <b>right</b>
45196      * side of container</div></li>
45197      * </ul></div>
45198      */
45199     /**
45200      * @cfg {Number} flex
45201      * This configuration option is to be applied to <b>child <tt>items</tt></b> of the container managed
45202      * by this layout. Each child item with a <tt>flex</tt> property will be flexed <b>horizontally</b>
45203      * according to each item's <b>relative</b> <tt>flex</tt> value compared to the sum of all items with
45204      * a <tt>flex</tt> value specified.  Any child items that have either a <tt>flex = 0</tt> or
45205      * <tt>flex = undefined</tt> will not be 'flexed' (the initial size will not be changed).
45206      */
45207
45208     type: 'box',
45209     scrollOffset: 0,
45210     itemCls: Ext.baseCSSPrefix + 'box-item',
45211     targetCls: Ext.baseCSSPrefix + 'box-layout-ct',
45212     innerCls: Ext.baseCSSPrefix + 'box-inner',
45213
45214     bindToOwnerCtContainer: true,
45215
45216     fixedLayout: false,
45217     
45218     // availableSpaceOffset is used to adjust the availableWidth, typically used
45219     // to reserve space for a scrollbar
45220     availableSpaceOffset: 0,
45221     
45222     // whether or not to reserve the availableSpaceOffset in layout calculations
45223     reserveOffset: true,
45224     
45225     /**
45226      * @cfg {Boolean} clearInnerCtOnLayout
45227      */
45228     clearInnerCtOnLayout: false,
45229
45230     flexSortFn: function (a, b) {
45231         var maxParallelPrefix = 'max' + this.parallelPrefixCap,
45232             infiniteValue = Infinity;
45233         a = a.component[maxParallelPrefix] || infiniteValue;
45234         b = b.component[maxParallelPrefix] || infiniteValue;
45235         // IE 6/7 Don't like Infinity - Infinity...
45236         if (!isFinite(a) && !isFinite(b)) {
45237             return false;
45238         }
45239         return a - b;
45240     },
45241
45242     // Sort into *descending* order.
45243     minSizeSortFn: function(a, b) {
45244         return b.available - a.available;
45245     },
45246
45247     constructor: function(config) {
45248         var me = this;
45249
45250         me.callParent(arguments);
45251
45252         // The sort function needs access to properties in this, so must be bound.
45253         me.flexSortFn = Ext.Function.bind(me.flexSortFn, me);
45254
45255         me.initOverflowHandler();
45256     },
45257
45258     /**
45259      * @private
45260      * Returns the current size and positioning of the passed child item.
45261      * @param {Component} child The child Component to calculate the box for
45262      * @return {Object} Object containing box measurements for the child. Properties are left,top,width,height.
45263      */
45264     getChildBox: function(child) {
45265         child = child.el || this.owner.getComponent(child).el;
45266         return {
45267             left: child.getLeft(true),
45268             top: child.getTop(true),
45269             width: child.getWidth(),
45270             height: child.getHeight()
45271         };
45272     },
45273
45274     /**
45275      * @private
45276      * Calculates the size and positioning of the passed child item.
45277      * @param {Component} child The child Component to calculate the box for
45278      * @return {Object} Object containing box measurements for the child. Properties are left,top,width,height.
45279      */
45280     calculateChildBox: function(child) {
45281         var me = this,
45282             boxes = me.calculateChildBoxes(me.getVisibleItems(), me.getLayoutTargetSize()).boxes,
45283             ln = boxes.length,
45284             i = 0;
45285
45286         child = me.owner.getComponent(child);
45287         for (; i < ln; i++) {
45288             if (boxes[i].component === child) {
45289                 return boxes[i];
45290             }
45291         }
45292     },
45293
45294     /**
45295      * @private
45296      * Calculates the size and positioning of each item in the box. This iterates over all of the rendered,
45297      * visible items and returns a height, width, top and left for each, as well as a reference to each. Also
45298      * returns meta data such as maxSize which are useful when resizing layout wrappers such as this.innerCt.
45299      * @param {Array} visibleItems The array of all rendered, visible items to be calculated for
45300      * @param {Object} targetSize Object containing target size and height
45301      * @return {Object} Object containing box measurements for each child, plus meta data
45302      */
45303     calculateChildBoxes: function(visibleItems, targetSize) {
45304         var me = this,
45305             math = Math,
45306             mmax = math.max,
45307             infiniteValue = Infinity,
45308             undefinedValue,
45309
45310             parallelPrefix = me.parallelPrefix,
45311             parallelPrefixCap = me.parallelPrefixCap,
45312             perpendicularPrefix = me.perpendicularPrefix,
45313             perpendicularPrefixCap = me.perpendicularPrefixCap,
45314             parallelMinString = 'min' + parallelPrefixCap,
45315             perpendicularMinString = 'min' + perpendicularPrefixCap,
45316             perpendicularMaxString = 'max' + perpendicularPrefixCap,
45317
45318             parallelSize = targetSize[parallelPrefix] - me.scrollOffset,
45319             perpendicularSize = targetSize[perpendicularPrefix],
45320             padding = me.padding,
45321             parallelOffset = padding[me.parallelBefore],
45322             paddingParallel = parallelOffset + padding[me.parallelAfter],
45323             perpendicularOffset = padding[me.perpendicularLeftTop],
45324             paddingPerpendicular =  perpendicularOffset + padding[me.perpendicularRightBottom],
45325             availPerpendicularSize = mmax(0, perpendicularSize - paddingPerpendicular),
45326
45327             isStart = me.pack == 'start',
45328             isCenter = me.pack == 'center',
45329             isEnd = me.pack == 'end',
45330
45331             constrain = Ext.Number.constrain,
45332             visibleCount = visibleItems.length,
45333             nonFlexSize = 0,
45334             totalFlex = 0,
45335             desiredSize = 0,
45336             minimumSize = 0,
45337             maxSize = 0,
45338             boxes = [],
45339             minSizes = [],
45340             calculatedWidth,
45341
45342             i, child, childParallel, childPerpendicular, childMargins, childSize, minParallel, tmpObj, shortfall, 
45343             tooNarrow, availableSpace, minSize, item, length, itemIndex, box, oldSize, newSize, reduction, diff, 
45344             flexedBoxes, remainingSpace, remainingFlex, flexedSize, parallelMargins, calcs, offset, 
45345             perpendicularMargins, stretchSize;
45346
45347         //gather the total flex of all flexed items and the width taken up by fixed width items
45348         for (i = 0; i < visibleCount; i++) {
45349             child = visibleItems[i];
45350             childPerpendicular = child[perpendicularPrefix];
45351             me.layoutItem(child);
45352             childMargins = child.margins;
45353             parallelMargins = childMargins[me.parallelBefore] + childMargins[me.parallelAfter];
45354
45355             // Create the box description object for this child item.
45356             tmpObj = {
45357                 component: child,
45358                 margins: childMargins
45359             };
45360
45361             // flex and not 'auto' width
45362             if (child.flex) {
45363                 totalFlex += child.flex;
45364                 childParallel = undefinedValue;
45365             }
45366             // Not flexed or 'auto' width or undefined width
45367             else {
45368                 if (!(child[parallelPrefix] && childPerpendicular)) {
45369                     childSize = child.getSize();
45370                 }
45371                 childParallel = child[parallelPrefix] || childSize[parallelPrefix];
45372                 childPerpendicular = childPerpendicular || childSize[perpendicularPrefix];
45373             }
45374
45375             nonFlexSize += parallelMargins + (childParallel || 0);
45376             desiredSize += parallelMargins + (child.flex ? child[parallelMinString] || 0 : childParallel);
45377             minimumSize += parallelMargins + (child[parallelMinString] || childParallel || 0);
45378
45379             // Max height for align - force layout of non-laid out subcontainers without a numeric height
45380             if (typeof childPerpendicular != 'number') {
45381                 // Clear any static sizing and revert to flow so we can get a proper measurement
45382                 // child['set' + perpendicularPrefixCap](null);
45383                 childPerpendicular = child['get' + perpendicularPrefixCap]();
45384             }
45385
45386             // Track the maximum perpendicular size for use by the stretch and stretchmax align config values.
45387             maxSize = mmax(maxSize, childPerpendicular + childMargins[me.perpendicularLeftTop] + childMargins[me.perpendicularRightBottom]);
45388
45389             tmpObj[parallelPrefix] = childParallel || undefinedValue;
45390             tmpObj[perpendicularPrefix] = childPerpendicular || undefinedValue;
45391             boxes.push(tmpObj);
45392         }
45393         shortfall = desiredSize - parallelSize;
45394         tooNarrow = minimumSize > parallelSize;
45395
45396         //the space available to the flexed items
45397         availableSpace = mmax(0, parallelSize - nonFlexSize - paddingParallel - (me.reserveOffset ? me.availableSpaceOffset : 0));
45398
45399         if (tooNarrow) {
45400             for (i = 0; i < visibleCount; i++) {
45401                 box = boxes[i];
45402                 minSize = visibleItems[i][parallelMinString] || visibleItems[i][parallelPrefix] || box[parallelPrefix];
45403                 box.dirtySize = box.dirtySize || box[parallelPrefix] != minSize;
45404                 box[parallelPrefix] = minSize;
45405             }
45406         }
45407         else {
45408             //all flexed items should be sized to their minimum size, other items should be shrunk down until
45409             //the shortfall has been accounted for
45410             if (shortfall > 0) {
45411                 /*
45412                  * When we have a shortfall but are not tooNarrow, we need to shrink the width of each non-flexed item.
45413                  * Flexed items are immediately reduced to their minWidth and anything already at minWidth is ignored.
45414                  * The remaining items are collected into the minWidths array, which is later used to distribute the shortfall.
45415                  */
45416                 for (i = 0; i < visibleCount; i++) {
45417                     item = visibleItems[i];
45418                     minSize = item[parallelMinString] || 0;
45419
45420                     //shrink each non-flex tab by an equal amount to make them all fit. Flexed items are all
45421                     //shrunk to their minSize because they're flexible and should be the first to lose size
45422                     if (item.flex) {
45423                         box = boxes[i];
45424                         box.dirtySize = box.dirtySize || box[parallelPrefix] != minSize;
45425                         box[parallelPrefix] = minSize;
45426                     }
45427                     else {
45428                         minSizes.push({
45429                             minSize: minSize,
45430                             available: boxes[i][parallelPrefix] - minSize,
45431                             index: i
45432                         });
45433                     }
45434                 }
45435
45436                 //sort by descending amount of width remaining before minWidth is reached
45437                 Ext.Array.sort(minSizes, me.minSizeSortFn);
45438
45439                 /*
45440                  * Distribute the shortfall (difference between total desired size of all items and actual size available)
45441                  * between the non-flexed items. We try to distribute the shortfall evenly, but apply it to items with the
45442                  * smallest difference between their size and minSize first, so that if reducing the size by the average
45443                  * amount would make that item less than its minSize, we carry the remainder over to the next item.
45444                  */
45445                 for (i = 0, length = minSizes.length; i < length; i++) {
45446                     itemIndex = minSizes[i].index;
45447
45448                     if (itemIndex == undefinedValue) {
45449                         continue;
45450                     }
45451                     item = visibleItems[itemIndex];
45452                     minSize = minSizes[i].minSize;
45453
45454                     box = boxes[itemIndex];
45455                     oldSize = box[parallelPrefix];
45456                     newSize = mmax(minSize, oldSize - math.ceil(shortfall / (length - i)));
45457                     reduction = oldSize - newSize;
45458
45459                     box.dirtySize = box.dirtySize || box[parallelPrefix] != newSize;
45460                     box[parallelPrefix] = newSize;
45461                     shortfall -= reduction;
45462                 }
45463             }
45464             else {
45465                 remainingSpace = availableSpace;
45466                 remainingFlex = totalFlex;
45467                 flexedBoxes = [];
45468
45469                 // Create an array containing *just the flexed boxes* for allocation of remainingSpace
45470                 for (i = 0; i < visibleCount; i++) {
45471                     child = visibleItems[i];
45472                     if (isStart && child.flex) {
45473                         flexedBoxes.push(boxes[Ext.Array.indexOf(visibleItems, child)]);
45474                     }
45475                 }
45476                 // The flexed boxes need to be sorted in ascending order of maxSize to work properly
45477                 // so that unallocated space caused by maxWidth being less than flexed width
45478                 // can be reallocated to subsequent flexed boxes.
45479                 Ext.Array.sort(flexedBoxes, me.flexSortFn);
45480
45481                 // Calculate the size of each flexed item, and attempt to set it.
45482                 for (i = 0; i < flexedBoxes.length; i++) {
45483                     calcs = flexedBoxes[i];
45484                     child = calcs.component;
45485                     childMargins = calcs.margins;
45486
45487                     flexedSize = math.ceil((child.flex / remainingFlex) * remainingSpace);
45488
45489                     // Implement maxSize and minSize check
45490                     flexedSize = Math.max(child['min' + parallelPrefixCap] || 0, math.min(child['max' + parallelPrefixCap] || infiniteValue, flexedSize));
45491
45492                     // Remaining space has already had all parallel margins subtracted from it, so just subtract consumed size
45493                     remainingSpace -= flexedSize;
45494                     remainingFlex -= child.flex;
45495
45496                     calcs.dirtySize = calcs.dirtySize || calcs[parallelPrefix] != flexedSize;
45497                     calcs[parallelPrefix] = flexedSize;
45498                 }
45499             }
45500         }
45501
45502         if (isCenter) {
45503             parallelOffset += availableSpace / 2;
45504         }
45505         else if (isEnd) {
45506             parallelOffset += availableSpace;
45507         }
45508
45509         // Fix for left and right docked Components in a dock component layout. This is for docked Headers and docked Toolbars.
45510         // Older Microsoft browsers do not size a position:absolute element's width to match its content.
45511         // So in this case, in the updateInnerCtSize method we may need to adjust the size of the owning Container's element explicitly based upon
45512         // the discovered max width. So here we put a calculatedWidth property in the metadata to facilitate this.
45513         if (me.owner.dock && (Ext.isIE6 || Ext.isIE7 || Ext.isIEQuirks) && !me.owner.width && me.direction == 'vertical') {
45514
45515             calculatedWidth = maxSize + me.owner.el.getPadding('lr') + me.owner.el.getBorderWidth('lr');
45516             if (me.owner.frameSize) {
45517                 calculatedWidth += me.owner.frameSize.left + me.owner.frameSize.right;
45518             }
45519             // If the owning element is not sized, calculate the available width to center or stretch in based upon maxSize
45520             availPerpendicularSize = Math.min(availPerpendicularSize, targetSize.width = maxSize + padding.left + padding.right);
45521         }
45522
45523         //finally, calculate the left and top position of each item
45524         for (i = 0; i < visibleCount; i++) {
45525             child = visibleItems[i];
45526             calcs = boxes[i];
45527
45528             childMargins = calcs.margins;
45529
45530             perpendicularMargins = childMargins[me.perpendicularLeftTop] + childMargins[me.perpendicularRightBottom];
45531
45532             // Advance past the "before" margin
45533             parallelOffset += childMargins[me.parallelBefore];
45534
45535             calcs[me.parallelBefore] = parallelOffset;
45536             calcs[me.perpendicularLeftTop] = perpendicularOffset + childMargins[me.perpendicularLeftTop];
45537
45538             if (me.align == 'stretch') {
45539                 stretchSize = constrain(availPerpendicularSize - perpendicularMargins, child[perpendicularMinString] || 0, child[perpendicularMaxString] || infiniteValue);
45540                 calcs.dirtySize = calcs.dirtySize || calcs[perpendicularPrefix] != stretchSize;
45541                 calcs[perpendicularPrefix] = stretchSize;
45542             }
45543             else if (me.align == 'stretchmax') {
45544                 stretchSize = constrain(maxSize - perpendicularMargins, child[perpendicularMinString] || 0, child[perpendicularMaxString] || infiniteValue);
45545                 calcs.dirtySize = calcs.dirtySize || calcs[perpendicularPrefix] != stretchSize;
45546                 calcs[perpendicularPrefix] = stretchSize;
45547             }
45548             else if (me.align == me.alignCenteringString) {
45549                 // When calculating a centered position within the content box of the innerCt, the width of the borders must be subtracted from
45550                 // the size to yield the space available to center within.
45551                 // The updateInnerCtSize method explicitly adds the border widths to the set size of the innerCt.
45552                 diff = mmax(availPerpendicularSize, maxSize) - me.innerCt.getBorderWidth(me.perpendicularLT + me.perpendicularRB) - calcs[perpendicularPrefix];
45553                 if (diff > 0) {
45554                     calcs[me.perpendicularLeftTop] = perpendicularOffset + Math.round(diff / 2);
45555                 }
45556             }
45557
45558             // Advance past the box size and the "after" margin
45559             parallelOffset += (calcs[parallelPrefix] || 0) + childMargins[me.parallelAfter];
45560         }
45561
45562         return {
45563             boxes: boxes,
45564             meta : {
45565                 calculatedWidth: calculatedWidth,
45566                 maxSize: maxSize,
45567                 nonFlexSize: nonFlexSize,
45568                 desiredSize: desiredSize,
45569                 minimumSize: minimumSize,
45570                 shortfall: shortfall,
45571                 tooNarrow: tooNarrow
45572             }
45573         };
45574     },
45575
45576     /**
45577      * @private
45578      */
45579     initOverflowHandler: function() {
45580         var handler = this.overflowHandler;
45581
45582         if (typeof handler == 'string') {
45583             handler = {
45584                 type: handler
45585             };
45586         }
45587
45588         var handlerType = 'None';
45589         if (handler && handler.type != undefined) {
45590             handlerType = handler.type;
45591         }
45592
45593         var constructor = Ext.layout.container.boxOverflow[handlerType];
45594         if (constructor[this.type]) {
45595             constructor = constructor[this.type];
45596         }
45597
45598         this.overflowHandler = Ext.create('Ext.layout.container.boxOverflow.' + handlerType, this, handler);
45599     },
45600
45601     /**
45602      * @private
45603      * Runs the child box calculations and caches them in childBoxCache. Subclasses can used these cached values
45604      * when laying out
45605      */
45606     onLayout: function() {
45607         this.callParent();
45608         // Clear the innerCt size so it doesn't influence the child items.
45609         if (this.clearInnerCtOnLayout === true && this.adjustmentPass !== true) {
45610             this.innerCt.setSize(null, null);
45611         }
45612
45613         var me = this,
45614             targetSize = me.getLayoutTargetSize(),
45615             items = me.getVisibleItems(),
45616             calcs = me.calculateChildBoxes(items, targetSize),
45617             boxes = calcs.boxes,
45618             meta = calcs.meta,
45619             handler, method, results;
45620
45621         if (me.autoSize && calcs.meta.desiredSize) {
45622             targetSize[me.parallelPrefix] = calcs.meta.desiredSize;
45623         }
45624
45625         //invoke the overflow handler, if one is configured
45626         if (meta.shortfall > 0) {
45627             handler = me.overflowHandler;
45628             method = meta.tooNarrow ? 'handleOverflow': 'clearOverflow';
45629
45630             results = handler[method](calcs, targetSize);
45631
45632             if (results) {
45633                 if (results.targetSize) {
45634                     targetSize = results.targetSize;
45635                 }
45636
45637                 if (results.recalculate) {
45638                     items = me.getVisibleItems(owner);
45639                     calcs = me.calculateChildBoxes(items, targetSize);
45640                     boxes = calcs.boxes;
45641                 }
45642             }
45643         } else {
45644             me.overflowHandler.clearOverflow();
45645         }
45646
45647         /**
45648          * @private
45649          * @property layoutTargetLastSize
45650          * @type Object
45651          * Private cache of the last measured size of the layout target. This should never be used except by
45652          * BoxLayout subclasses during their onLayout run.
45653          */
45654         me.layoutTargetLastSize = targetSize;
45655
45656         /**
45657          * @private
45658          * @property childBoxCache
45659          * @type Array
45660          * Array of the last calculated height, width, top and left positions of each visible rendered component
45661          * within the Box layout.
45662          */
45663         me.childBoxCache = calcs;
45664
45665         me.updateInnerCtSize(targetSize, calcs);
45666         me.updateChildBoxes(boxes);
45667         me.handleTargetOverflow(targetSize);
45668     },
45669
45670     /**
45671      * Resizes and repositions each child component
45672      * @param {Array} boxes The box measurements
45673      */
45674     updateChildBoxes: function(boxes) {
45675         var me = this,
45676             i = 0,
45677             length = boxes.length,
45678             animQueue = [],
45679             dd = Ext.dd.DDM.getDDById(me.innerCt.id), // Any DD active on this layout's element (The BoxReorderer plugin does this.)
45680             oldBox, newBox, changed, comp, boxAnim, animCallback;
45681
45682         for (; i < length; i++) {
45683             newBox = boxes[i];
45684             comp = newBox.component;
45685
45686             // If a Component is being drag/dropped, skip positioning it.
45687             // Accomodate the BoxReorderer plugin: Its current dragEl must not be positioned by the layout
45688             if (dd && (dd.getDragEl() === comp.el.dom)) {
45689                 continue;
45690             }
45691
45692             changed = false;
45693
45694             oldBox = me.getChildBox(comp);
45695
45696             // If we are animating, we build up an array of Anim config objects, one for each
45697             // child Component which has any changed box properties. Those with unchanged
45698             // properties are not animated.
45699             if (me.animate) {
45700                 // Animate may be a config object containing callback.
45701                 animCallback = me.animate.callback || me.animate;
45702                 boxAnim = {
45703                     layoutAnimation: true,  // Component Target handler must use set*Calculated*Size
45704                     target: comp,
45705                     from: {},
45706                     to: {},
45707                     listeners: {}
45708                 };
45709                 // Only set from and to properties when there's a change.
45710                 // Perform as few Component setter methods as possible.
45711                 // Temporarily set the property values that we are not animating
45712                 // so that doComponentLayout does not auto-size them.
45713                 if (!isNaN(newBox.width) && (newBox.width != oldBox.width)) {
45714                     changed = true;
45715                     // boxAnim.from.width = oldBox.width;
45716                     boxAnim.to.width = newBox.width;
45717                 }
45718                 if (!isNaN(newBox.height) && (newBox.height != oldBox.height)) {
45719                     changed = true;
45720                     // boxAnim.from.height = oldBox.height;
45721                     boxAnim.to.height = newBox.height;
45722                 }
45723                 if (!isNaN(newBox.left) && (newBox.left != oldBox.left)) {
45724                     changed = true;
45725                     // boxAnim.from.left = oldBox.left;
45726                     boxAnim.to.left = newBox.left;
45727                 }
45728                 if (!isNaN(newBox.top) && (newBox.top != oldBox.top)) {
45729                     changed = true;
45730                     // boxAnim.from.top = oldBox.top;
45731                     boxAnim.to.top = newBox.top;
45732                 }
45733                 if (changed) {
45734                     animQueue.push(boxAnim);
45735                 }
45736             } else {
45737                 if (newBox.dirtySize) {
45738                     if (newBox.width !== oldBox.width || newBox.height !== oldBox.height) {
45739                         me.setItemSize(comp, newBox.width, newBox.height);
45740                     }
45741                 }
45742                 // Don't set positions to NaN
45743                 if (isNaN(newBox.left) || isNaN(newBox.top)) {
45744                     continue;
45745                 }
45746                 comp.setPosition(newBox.left, newBox.top);
45747             }
45748         }
45749
45750         // Kick off any queued animations
45751         length = animQueue.length;
45752         if (length) {
45753
45754             // A function which cleans up when a Component's animation is done.
45755             // The last one to finish calls the callback.
45756             var afterAnimate = function(anim) {
45757                 // When we've animated all changed boxes into position, clear our busy flag and call the callback.
45758                 length -= 1;
45759                 if (!length) {
45760                     me.layoutBusy = false;
45761                     if (Ext.isFunction(animCallback)) {
45762                         animCallback();
45763                     }
45764                 }
45765             };
45766
45767             var beforeAnimate = function() {
45768                 me.layoutBusy = true;
45769             };
45770
45771             // Start each box animation off
45772             for (i = 0, length = animQueue.length; i < length; i++) {
45773                 boxAnim = animQueue[i];
45774
45775                 // Clean up the Component after. Clean up the *layout* after the last animation finishes
45776                 boxAnim.listeners.afteranimate = afterAnimate;
45777
45778                 // The layout is busy during animation, and may not be called, so set the flag when the first animation begins
45779                 if (!i) {
45780                     boxAnim.listeners.beforeanimate = beforeAnimate;
45781                 }
45782                 if (me.animate.duration) {
45783                     boxAnim.duration = me.animate.duration;
45784                 }
45785                 comp = boxAnim.target;
45786                 delete boxAnim.target;
45787                 // Stop any currently running animation
45788                 comp.stopAnimation();
45789                 comp.animate(boxAnim);
45790             }
45791         }
45792     },
45793
45794     /**
45795      * @private
45796      * Called by onRender just before the child components are sized and positioned. This resizes the innerCt
45797      * to make sure all child items fit within it. We call this before sizing the children because if our child
45798      * items are larger than the previous innerCt size the browser will insert scrollbars and then remove them
45799      * again immediately afterwards, giving a performance hit.
45800      * Subclasses should provide an implementation.
45801      * @param {Object} currentSize The current height and width of the innerCt
45802      * @param {Array} calculations The new box calculations of all items to be laid out
45803      */
45804     updateInnerCtSize: function(tSize, calcs) {
45805         var me = this,
45806             mmax = Math.max,
45807             align = me.align,
45808             padding = me.padding,
45809             width = tSize.width,
45810             height = tSize.height,
45811             meta = calcs.meta,
45812             innerCtWidth,
45813             innerCtHeight;
45814
45815         if (me.direction == 'horizontal') {
45816             innerCtWidth = width;
45817             innerCtHeight = meta.maxSize + padding.top + padding.bottom + me.innerCt.getBorderWidth('tb');
45818
45819             if (align == 'stretch') {
45820                 innerCtHeight = height;
45821             }
45822             else if (align == 'middle') {
45823                 innerCtHeight = mmax(height, innerCtHeight);
45824             }
45825         } else {
45826             innerCtHeight = height;
45827             innerCtWidth = meta.maxSize + padding.left + padding.right + me.innerCt.getBorderWidth('lr');
45828
45829             if (align == 'stretch') {
45830                 innerCtWidth = width;
45831             }
45832             else if (align == 'center') {
45833                 innerCtWidth = mmax(width, innerCtWidth);
45834             }
45835         }
45836         me.getRenderTarget().setSize(innerCtWidth || undefined, innerCtHeight || undefined);
45837
45838         // If a calculated width has been found (and this only happens for auto-width vertical docked Components in old Microsoft browsers)
45839         // then, if the Component has not assumed the size of its content, set it to do so.
45840         if (meta.calculatedWidth && me.owner.el.getWidth() > meta.calculatedWidth) {
45841             me.owner.el.setWidth(meta.calculatedWidth);
45842         }
45843
45844         if (me.innerCt.dom.scrollTop) {
45845             me.innerCt.dom.scrollTop = 0;
45846         }
45847     },
45848
45849     /**
45850      * @private
45851      * This should be called after onLayout of any BoxLayout subclass. If the target's overflow is not set to 'hidden',
45852      * we need to lay out a second time because the scrollbars may have modified the height and width of the layout
45853      * target. Having a Box layout inside such a target is therefore not recommended.
45854      * @param {Object} previousTargetSize The size and height of the layout target before we just laid out
45855      * @param {Ext.container.Container} container The container
45856      * @param {Ext.core.Element} target The target element
45857      * @return True if the layout overflowed, and was reflowed in a secondary onLayout call.
45858      */
45859     handleTargetOverflow: function(previousTargetSize) {
45860         var target = this.getTarget(),
45861             overflow = target.getStyle('overflow'),
45862             newTargetSize;
45863
45864         if (overflow && overflow != 'hidden' && !this.adjustmentPass) {
45865             newTargetSize = this.getLayoutTargetSize();
45866             if (newTargetSize.width != previousTargetSize.width || newTargetSize.height != previousTargetSize.height) {
45867                 this.adjustmentPass = true;
45868                 this.onLayout();
45869                 return true;
45870             }
45871         }
45872
45873         delete this.adjustmentPass;
45874     },
45875
45876     // private
45877     isValidParent : function(item, target, position) {
45878         // Note: Box layouts do not care about order within the innerCt element because it's an absolutely positioning layout
45879         // We only care whether the item is a direct child of the innerCt element.
45880         var itemEl = item.el ? item.el.dom : Ext.getDom(item);
45881         return (itemEl && this.innerCt && itemEl.parentNode === this.innerCt.dom) || false;
45882     },
45883
45884     // Overridden method from AbstractContainer.
45885     // Used in the base AbstractLayout.beforeLayout method to render all items into.
45886     getRenderTarget: function() {
45887         if (!this.innerCt) {
45888             // the innerCt prevents wrapping and shuffling while the container is resizing
45889             this.innerCt = this.getTarget().createChild({
45890                 cls: this.innerCls,
45891                 role: 'presentation'
45892             });
45893             this.padding = Ext.util.Format.parseBox(this.padding);
45894         }
45895         return this.innerCt;
45896     },
45897
45898     // private
45899     renderItem: function(item, target) {
45900         this.callParent(arguments);
45901         var me = this,
45902             itemEl = item.getEl(),
45903             style = itemEl.dom.style,
45904             margins = item.margins || item.margin;
45905
45906         // Parse the item's margin/margins specification
45907         if (margins) {
45908             if (Ext.isString(margins) || Ext.isNumber(margins)) {
45909                 margins = Ext.util.Format.parseBox(margins);
45910             } else {
45911                 Ext.applyIf(margins, {top: 0, right: 0, bottom: 0, left: 0});
45912             }
45913         } else {
45914             margins = Ext.apply({}, me.defaultMargins);
45915         }
45916
45917         // Add any before/after CSS margins to the configured margins, and zero the CSS margins
45918         margins.top    += itemEl.getMargin('t');
45919         margins.right  += itemEl.getMargin('r');
45920         margins.bottom += itemEl.getMargin('b');
45921         margins.left   += itemEl.getMargin('l');
45922         style.marginTop = style.marginRight = style.marginBottom = style.marginLeft = '0';
45923
45924         // Item must reference calculated margins.
45925         item.margins = margins;
45926     },
45927
45928     /**
45929      * @private
45930      */
45931     destroy: function() {
45932         Ext.destroy(this.overflowHandler);
45933         this.callParent(arguments);
45934     }
45935 });
45936 /**
45937  * @class Ext.layout.container.HBox
45938  * @extends Ext.layout.container.Box
45939  * <p>A layout that arranges items horizontally across a Container. This layout optionally divides available horizontal
45940  * space between child items containing a numeric <code>flex</code> configuration.</p>
45941  * This layout may also be used to set the heights of child items by configuring it with the {@link #align} option.
45942  * {@img Ext.layout.container.HBox/Ext.layout.container.HBox.png Ext.layout.container.HBox container layout}
45943  * Example usage:
45944     Ext.create('Ext.Panel', {
45945         width: 500,
45946         height: 300,
45947         title: "HBoxLayout Panel",
45948         layout: {
45949             type: 'hbox',
45950             align: 'stretch'
45951         },
45952         renderTo: document.body,
45953         items: [{
45954             xtype: 'panel',
45955             title: 'Inner Panel One',
45956             flex: 2
45957         },{
45958             xtype: 'panel',
45959             title: 'Inner Panel Two',
45960             flex: 1
45961         },{
45962             xtype: 'panel',
45963             title: 'Inner Panel Three',
45964             flex: 1
45965         }]
45966     });
45967  */
45968 Ext.define('Ext.layout.container.HBox', {
45969
45970     /* Begin Definitions */
45971
45972     alias: ['layout.hbox'],
45973     extend: 'Ext.layout.container.Box',
45974     alternateClassName: 'Ext.layout.HBoxLayout',
45975     
45976     /* End Definitions */
45977
45978     /**
45979      * @cfg {String} align
45980      * Controls how the child items of the container are aligned. Acceptable configuration values for this
45981      * property are:
45982      * <div class="mdetail-params"><ul>
45983      * <li><b><tt>top</tt></b> : <b>Default</b><div class="sub-desc">child items are aligned vertically
45984      * at the <b>top</b> of the container</div></li>
45985      * <li><b><tt>middle</tt></b> : <div class="sub-desc">child items are aligned vertically in the
45986      * <b>middle</b> of the container</div></li>
45987      * <li><b><tt>stretch</tt></b> : <div class="sub-desc">child items are stretched vertically to fill
45988      * the height of the container</div></li>
45989      * <li><b><tt>stretchmax</tt></b> : <div class="sub-desc">child items are stretched vertically to
45990      * the height of the largest item.</div></li>
45991      * </ul></div>
45992      */
45993     align: 'top', // top, middle, stretch, strechmax
45994
45995     //@private
45996     alignCenteringString: 'middle',
45997
45998     type : 'hbox',
45999
46000     direction: 'horizontal',
46001
46002     // When creating an argument list to setSize, use this order
46003     parallelSizeIndex: 0,
46004     perpendicularSizeIndex: 1,
46005
46006     parallelPrefix: 'width',
46007     parallelPrefixCap: 'Width',
46008     parallelLT: 'l',
46009     parallelRB: 'r',
46010     parallelBefore: 'left',
46011     parallelBeforeCap: 'Left',
46012     parallelAfter: 'right',
46013     parallelPosition: 'x',
46014
46015     perpendicularPrefix: 'height',
46016     perpendicularPrefixCap: 'Height',
46017     perpendicularLT: 't',
46018     perpendicularRB: 'b',
46019     perpendicularLeftTop: 'top',
46020     perpendicularRightBottom: 'bottom',
46021     perpendicularPosition: 'y'
46022 });
46023 /**
46024  * @class Ext.layout.container.VBox
46025  * @extends Ext.layout.container.Box
46026  * <p>A layout that arranges items vertically down a Container. This layout optionally divides available vertical
46027  * space between child items containing a numeric <code>flex</code> configuration.</p>
46028  * This layout may also be used to set the widths of child items by configuring it with the {@link #align} option.
46029  * {@img Ext.layout.container.VBox/Ext.layout.container.VBox.png Ext.layout.container.VBox container layout}
46030  * Example usage:
46031         Ext.create('Ext.Panel', {
46032                 width: 500,
46033                 height: 400,
46034                 title: "VBoxLayout Panel",
46035                 layout: {                        
46036                         type: 'vbox',
46037                         align: 'center'
46038                 },
46039                 renderTo: document.body,
46040                 items: [{                        
46041                         xtype: 'panel',
46042                         title: 'Inner Panel One',
46043                         width: 250,
46044                         flex: 2                      
46045                 },{
46046                         xtype: 'panel',
46047                         title: 'Inner Panel Two',
46048                         width: 250,                     
46049                         flex: 4
46050                 },{
46051                         xtype: 'panel',
46052                         title: 'Inner Panel Three',
46053                         width: '50%',                   
46054                         flex: 4
46055                 }]
46056         });
46057  */
46058 Ext.define('Ext.layout.container.VBox', {
46059
46060     /* Begin Definitions */
46061
46062     alias: ['layout.vbox'],
46063     extend: 'Ext.layout.container.Box',
46064     alternateClassName: 'Ext.layout.VBoxLayout',
46065     
46066     /* End Definitions */
46067
46068     /**
46069      * @cfg {String} align
46070      * Controls how the child items of the container are aligned. Acceptable configuration values for this
46071      * property are:
46072      * <div class="mdetail-params"><ul>
46073      * <li><b><tt>left</tt></b> : <b>Default</b><div class="sub-desc">child items are aligned horizontally
46074      * at the <b>left</b> side of the container</div></li>
46075      * <li><b><tt>center</tt></b> : <div class="sub-desc">child items are aligned horizontally at the
46076      * <b>mid-width</b> of the container</div></li>
46077      * <li><b><tt>stretch</tt></b> : <div class="sub-desc">child items are stretched horizontally to fill
46078      * the width of the container</div></li>
46079      * <li><b><tt>stretchmax</tt></b> : <div class="sub-desc">child items are stretched horizontally to
46080      * the size of the largest item.</div></li>
46081      * </ul></div>
46082      */
46083     align : 'left', // left, center, stretch, strechmax
46084
46085     //@private
46086     alignCenteringString: 'center',
46087
46088     type: 'vbox',
46089
46090     direction: 'vertical',
46091
46092     // When creating an argument list to setSize, use this order
46093     parallelSizeIndex: 1,
46094     perpendicularSizeIndex: 0,
46095
46096     parallelPrefix: 'height',
46097     parallelPrefixCap: 'Height',
46098     parallelLT: 't',
46099     parallelRB: 'b',
46100     parallelBefore: 'top',
46101     parallelBeforeCap: 'Top',
46102     parallelAfter: 'bottom',
46103     parallelPosition: 'y',
46104
46105     perpendicularPrefix: 'width',
46106     perpendicularPrefixCap: 'Width',
46107     perpendicularLT: 'l',
46108     perpendicularRB: 'r',
46109     perpendicularLeftTop: 'left',
46110     perpendicularRightBottom: 'right',
46111     perpendicularPosition: 'x'
46112 });
46113 /**
46114  * @class Ext.FocusManager
46115
46116 The FocusManager is responsible for globally:
46117
46118 1. Managing component focus
46119 2. Providing basic keyboard navigation
46120 3. (optional) Provide a visual cue for focused components, in the form of a focus ring/frame.
46121
46122 To activate the FocusManager, simply call {@link #enable `Ext.FocusManager.enable();`}. In turn, you may
46123 deactivate the FocusManager by subsequently calling {@link #disable `Ext.FocusManager.disable();`}.  The
46124 FocusManager is disabled by default.
46125
46126 To enable the optional focus frame, pass `true` or `{focusFrame: true}` to {@link #enable}.
46127
46128 Another feature of the FocusManager is to provide basic keyboard focus navigation scoped to any {@link Ext.container.Container}
46129 that would like to have navigation between its child {@link Ext.Component}'s. The {@link Ext.container.Container} can simply
46130 call {@link #subscribe Ext.FocusManager.subscribe} to take advantage of this feature, and can at any time call
46131 {@link #unsubscribe Ext.FocusManager.unsubscribe} to turn the navigation off.
46132
46133  * @singleton
46134  * @markdown
46135  * @author Jarred Nicholls <jarred@sencha.com>
46136  * @docauthor Jarred Nicholls <jarred@sencha.com>
46137  */
46138 Ext.define('Ext.FocusManager', {
46139     singleton: true,
46140     alternateClassName: 'Ext.FocusMgr',
46141
46142     mixins: {
46143         observable: 'Ext.util.Observable'
46144     },
46145
46146     requires: [
46147         'Ext.ComponentManager',
46148         'Ext.ComponentQuery',
46149         'Ext.util.HashMap',
46150         'Ext.util.KeyNav'
46151     ],
46152
46153     /**
46154      * @property {Boolean} enabled
46155      * Whether or not the FocusManager is currently enabled
46156      */
46157     enabled: false,
46158
46159     /**
46160      * @property {Ext.Component} focusedCmp
46161      * The currently focused component. Defaults to `undefined`.
46162      * @markdown
46163      */
46164
46165     focusElementCls: Ext.baseCSSPrefix + 'focus-element',
46166
46167     focusFrameCls: Ext.baseCSSPrefix + 'focus-frame',
46168
46169     /**
46170      * @property {Array} whitelist
46171      * A list of xtypes that should ignore certain navigation input keys and
46172      * allow for the default browser event/behavior. These input keys include:
46173      *
46174      * 1. Backspace
46175      * 2. Delete
46176      * 3. Left
46177      * 4. Right
46178      * 5. Up
46179      * 6. Down
46180      *
46181      * The FocusManager will not attempt to navigate when a component is an xtype (or descendents thereof)
46182      * that belongs to this whitelist. E.g., an {@link Ext.form.field.Text} should allow
46183      * the user to move the input cursor left and right, and to delete characters, etc.
46184      *
46185      * This whitelist currently defaults to `['textfield']`.
46186      * @markdown
46187      */
46188     whitelist: [
46189         'textfield'
46190     ],
46191
46192     tabIndexWhitelist: [
46193         'a',
46194         'button',
46195         'embed',
46196         'frame',
46197         'iframe',
46198         'img',
46199         'input',
46200         'object',
46201         'select',
46202         'textarea'
46203     ],
46204
46205     constructor: function() {
46206         var me = this,
46207             CQ = Ext.ComponentQuery;
46208
46209         me.addEvents(
46210             /**
46211              * @event beforecomponentfocus
46212              * Fires before a component becomes focused. Return `false` to prevent
46213              * the component from gaining focus.
46214              * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
46215              * @param {Ext.Component} cmp The component that is being focused
46216              * @param {Ext.Component} previousCmp The component that was previously focused,
46217              * or `undefined` if there was no previously focused component.
46218              * @markdown
46219              */
46220             'beforecomponentfocus',
46221
46222             /**
46223              * @event componentfocus
46224              * Fires after a component becomes focused.
46225              * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
46226              * @param {Ext.Component} cmp The component that has been focused
46227              * @param {Ext.Component} previousCmp The component that was previously focused,
46228              * or `undefined` if there was no previously focused component.
46229              * @markdown
46230              */
46231             'componentfocus',
46232
46233             /**
46234              * @event disable
46235              * Fires when the FocusManager is disabled
46236              * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
46237              */
46238             'disable',
46239
46240             /**
46241              * @event enable
46242              * Fires when the FocusManager is enabled
46243              * @param {Ext.FocusManager} fm A reference to the FocusManager singleton
46244              */
46245             'enable'
46246         );
46247
46248         // Setup KeyNav that's bound to document to catch all
46249         // unhandled/bubbled key events for navigation
46250         me.keyNav = Ext.create('Ext.util.KeyNav', Ext.getDoc(), {
46251             disabled: true,
46252             scope: me,
46253
46254             backspace: me.focusLast,
46255             enter: me.navigateIn,
46256             esc: me.navigateOut,
46257             tab: me.navigateSiblings
46258
46259             //space: me.navigateIn,
46260             //del: me.focusLast,
46261             //left: me.navigateSiblings,
46262             //right: me.navigateSiblings,
46263             //down: me.navigateSiblings,
46264             //up: me.navigateSiblings
46265         });
46266
46267         me.focusData = {};
46268         me.subscribers = Ext.create('Ext.util.HashMap');
46269         me.focusChain = {};
46270
46271         // Setup some ComponentQuery pseudos
46272         Ext.apply(CQ.pseudos, {
46273             focusable: function(cmps) {
46274                 var len = cmps.length,
46275                     results = [],
46276                     i = 0,
46277                     c,
46278
46279                     isFocusable = function(x) {
46280                         return x && x.focusable !== false && CQ.is(x, '[rendered]:not([destroying]):not([isDestroyed]):not([disabled]){isVisible(true)}{el && c.el.dom && c.el.isVisible()}');
46281                     };
46282
46283                 for (; i < len; i++) {
46284                     c = cmps[i];
46285                     if (isFocusable(c)) {
46286                         results.push(c);
46287                     }
46288                 }
46289
46290                 return results;
46291             },
46292
46293             nextFocus: function(cmps, idx, step) {
46294                 step = step || 1;
46295                 idx = parseInt(idx, 10);
46296
46297                 var len = cmps.length,
46298                     i = idx + step,
46299                     c;
46300
46301                 for (; i != idx; i += step) {
46302                     if (i >= len) {
46303                         i = 0;
46304                     } else if (i < 0) {
46305                         i = len - 1;
46306                     }
46307
46308                     c = cmps[i];
46309                     if (CQ.is(c, ':focusable')) {
46310                         return [c];
46311                     } else if (c.placeholder && CQ.is(c.placeholder, ':focusable')) {
46312                         return [c.placeholder];
46313                     }
46314                 }
46315
46316                 return [];
46317             },
46318
46319             prevFocus: function(cmps, idx) {
46320                 return this.nextFocus(cmps, idx, -1);
46321             },
46322
46323             root: function(cmps) {
46324                 var len = cmps.length,
46325                     results = [],
46326                     i = 0,
46327                     c;
46328
46329                 for (; i < len; i++) {
46330                     c = cmps[i];
46331                     if (!c.ownerCt) {
46332                         results.push(c);
46333                     }
46334                 }
46335
46336                 return results;
46337             }
46338         });
46339     },
46340
46341     /**
46342      * Adds the specified xtype to the {@link #whitelist}.
46343      * @param {String/Array} xtype Adds the xtype(s) to the {@link #whitelist}.
46344      */
46345     addXTypeToWhitelist: function(xtype) {
46346         var me = this;
46347
46348         if (Ext.isArray(xtype)) {
46349             Ext.Array.forEach(xtype, me.addXTypeToWhitelist, me);
46350             return;
46351         }
46352
46353         if (!Ext.Array.contains(me.whitelist, xtype)) {
46354             me.whitelist.push(xtype);
46355         }
46356     },
46357
46358     clearComponent: function(cmp) {
46359         clearTimeout(this.cmpFocusDelay);
46360         if (!cmp.isDestroyed) {
46361             cmp.blur();
46362         }
46363     },
46364
46365     /**
46366      * Disables the FocusManager by turning of all automatic focus management and keyboard navigation
46367      */
46368     disable: function() {
46369         var me = this;
46370
46371         if (!me.enabled) {
46372             return;
46373         }
46374
46375         delete me.options;
46376         me.enabled = false;
46377
46378         Ext.ComponentManager.all.un('add', me.onComponentCreated, me);
46379
46380         me.removeDOM();
46381
46382         // Stop handling key navigation
46383         me.keyNav.disable();
46384
46385         // disable focus for all components
46386         me.setFocusAll(false);
46387
46388         me.fireEvent('disable', me);
46389     },
46390
46391     /**
46392      * Enables the FocusManager by turning on all automatic focus management and keyboard navigation
46393      * @param {Boolean/Object} options Either `true`/`false` to turn on the focus frame, or an object of the following options:
46394         - focusFrame : Boolean
46395             `true` to show the focus frame around a component when it is focused. Defaults to `false`.
46396      * @markdown
46397      */
46398     enable: function(options) {
46399         var me = this;
46400
46401         if (options === true) {
46402             options = { focusFrame: true };
46403         }
46404         me.options = options = options || {};
46405
46406         if (me.enabled) {
46407             return;
46408         }
46409
46410         // Handle components that are newly added after we are enabled
46411         Ext.ComponentManager.all.on('add', me.onComponentCreated, me);
46412
46413         me.initDOM(options);
46414
46415         // Start handling key navigation
46416         me.keyNav.enable();
46417
46418         // enable focus for all components
46419         me.setFocusAll(true, options);
46420
46421         // Finally, let's focus our global focus el so we start fresh
46422         me.focusEl.focus();
46423         delete me.focusedCmp;
46424
46425         me.enabled = true;
46426         me.fireEvent('enable', me);
46427     },
46428
46429     focusLast: function(e) {
46430         var me = this;
46431
46432         if (me.isWhitelisted(me.focusedCmp)) {
46433             return true;
46434         }
46435
46436         // Go back to last focused item
46437         if (me.previousFocusedCmp) {
46438             me.previousFocusedCmp.focus();
46439         }
46440     },
46441
46442     getRootComponents: function() {
46443         var me = this,
46444             CQ = Ext.ComponentQuery,
46445             inline = CQ.query(':focusable:root:not([floating])'),
46446             floating = CQ.query(':focusable:root[floating]');
46447
46448         // Floating items should go to the top of our root stack, and be ordered
46449         // by their z-index (highest first)
46450         floating.sort(function(a, b) {
46451             return a.el.getZIndex() > b.el.getZIndex();
46452         });
46453
46454         return floating.concat(inline);
46455     },
46456
46457     initDOM: function(options) {
46458         var me = this,
46459             sp = '&#160',
46460             cls = me.focusFrameCls;
46461
46462         if (!Ext.isReady) {
46463             Ext.onReady(me.initDOM, me);
46464             return;
46465         }
46466
46467         // Create global focus element
46468         if (!me.focusEl) {
46469             me.focusEl = Ext.getBody().createChild({
46470                 tabIndex: '-1',
46471                 cls: me.focusElementCls,
46472                 html: sp
46473             });
46474         }
46475
46476         // Create global focus frame
46477         if (!me.focusFrame && options.focusFrame) {
46478             me.focusFrame = Ext.getBody().createChild({
46479                 cls: cls,
46480                 children: [
46481                     { cls: cls + '-top' },
46482                     { cls: cls + '-bottom' },
46483                     { cls: cls + '-left' },
46484                     { cls: cls + '-right' }
46485                 ],
46486                 style: 'top: -100px; left: -100px;'
46487             });
46488             me.focusFrame.setVisibilityMode(Ext.core.Element.DISPLAY);
46489             me.focusFrameWidth = me.focusFrame.child('.' + cls + '-top').getHeight();
46490             me.focusFrame.hide().setLeftTop(0, 0);
46491         }
46492     },
46493
46494     isWhitelisted: function(cmp) {
46495         return cmp && Ext.Array.some(this.whitelist, function(x) {
46496             return cmp.isXType(x);
46497         });
46498     },
46499
46500     navigateIn: function(e) {
46501         var me = this,
46502             focusedCmp = me.focusedCmp,
46503             rootCmps,
46504             firstChild;
46505
46506         if (!focusedCmp) {
46507             // No focus yet, so focus the first root cmp on the page
46508             rootCmps = me.getRootComponents();
46509             if (rootCmps.length) {
46510                 rootCmps[0].focus();
46511             }
46512         } else {
46513             // Drill into child ref items of the focused cmp, if applicable.
46514             // This works for any Component with a getRefItems implementation.
46515             firstChild = Ext.ComponentQuery.query('>:focusable', focusedCmp)[0];
46516             if (firstChild) {
46517                 firstChild.focus();
46518             } else {
46519                 // Let's try to fire a click event, as if it came from the mouse
46520                 if (Ext.isFunction(focusedCmp.onClick)) {
46521                     e.button = 0;
46522                     focusedCmp.onClick(e);
46523                     focusedCmp.focus();
46524                 }
46525             }
46526         }
46527     },
46528
46529     navigateOut: function(e) {
46530         var me = this,
46531             parent;
46532
46533         if (!me.focusedCmp || !(parent = me.focusedCmp.up(':focusable'))) {
46534             me.focusEl.focus();
46535             return;
46536         }
46537
46538         parent.focus();
46539     },
46540
46541     navigateSiblings: function(e, source, parent) {
46542         var me = this,
46543             src = source || me,
46544             key = e.getKey(),
46545             EO = Ext.EventObject,
46546             goBack = e.shiftKey || key == EO.LEFT || key == EO.UP,
46547             checkWhitelist = key == EO.LEFT || key == EO.RIGHT || key == EO.UP || key == EO.DOWN,
46548             nextSelector = goBack ? 'prev' : 'next',
46549             idx, next, focusedCmp;
46550
46551         focusedCmp = (src.focusedCmp && src.focusedCmp.comp) || src.focusedCmp;
46552         if (!focusedCmp && !parent) {
46553             return;
46554         }
46555
46556         if (checkWhitelist && me.isWhitelisted(focusedCmp)) {
46557             return true;
46558         }
46559
46560         parent = parent || focusedCmp.up();
46561         if (parent) {
46562             idx = focusedCmp ? Ext.Array.indexOf(parent.getRefItems(), focusedCmp) : -1;
46563             next = Ext.ComponentQuery.query('>:' + nextSelector + 'Focus(' + idx + ')', parent)[0];
46564             if (next && focusedCmp !== next) {
46565                 next.focus();
46566                 return next;
46567             }
46568         }
46569     },
46570
46571     onComponentBlur: function(cmp, e) {
46572         var me = this;
46573
46574         if (me.focusedCmp === cmp) {
46575             me.previousFocusedCmp = cmp;
46576             delete me.focusedCmp;
46577         }
46578
46579         if (me.focusFrame) {
46580             me.focusFrame.hide();
46581         }
46582     },
46583
46584     onComponentCreated: function(hash, id, cmp) {
46585         this.setFocus(cmp, true, this.options);
46586     },
46587
46588     onComponentDestroy: function(cmp) {
46589         this.setFocus(cmp, false);
46590     },
46591
46592     onComponentFocus: function(cmp, e) {
46593         var me = this,
46594             chain = me.focusChain;
46595
46596         if (!Ext.ComponentQuery.is(cmp, ':focusable')) {
46597             me.clearComponent(cmp);
46598
46599             // Check our focus chain, so we don't run into a never ending recursion
46600             // If we've attempted (unsuccessfully) to focus this component before,
46601             // then we're caught in a loop of child->parent->...->child and we
46602             // need to cut the loop off rather than feed into it.
46603             if (chain[cmp.id]) {
46604                 return;
46605             }
46606
46607             // Try to focus the parent instead
46608             var parent = cmp.up();
46609             if (parent) {
46610                 // Add component to our focus chain to detect infinite focus loop
46611                 // before we fire off an attempt to focus our parent.
46612                 // See the comments above.
46613                 chain[cmp.id] = true;
46614                 parent.focus();
46615             }
46616
46617             return;
46618         }
46619
46620         // Clear our focus chain when we have a focusable component
46621         me.focusChain = {};
46622
46623         // Defer focusing for 90ms so components can do a layout/positioning
46624         // and give us an ability to buffer focuses
46625         clearTimeout(me.cmpFocusDelay);
46626         if (arguments.length !== 2) {
46627             me.cmpFocusDelay = Ext.defer(me.onComponentFocus, 90, me, [cmp, e]);
46628             return;
46629         }
46630
46631         if (me.fireEvent('beforecomponentfocus', me, cmp, me.previousFocusedCmp) === false) {
46632             me.clearComponent(cmp);
46633             return;
46634         }
46635
46636         me.focusedCmp = cmp;
46637
46638         // If we have a focus frame, show it around the focused component
46639         if (me.shouldShowFocusFrame(cmp)) {
46640             var cls = '.' + me.focusFrameCls + '-',
46641                 ff = me.focusFrame,
46642                 fw = me.focusFrameWidth,
46643                 box = cmp.el.getPageBox(),
46644
46645             // Size the focus frame's t/b/l/r according to the box
46646             // This leaves a hole in the middle of the frame so user
46647             // interaction w/ the mouse can continue
46648                 bt = box.top,
46649                 bl = box.left,
46650                 bw = box.width,
46651                 bh = box.height,
46652                 ft = ff.child(cls + 'top'),
46653                 fb = ff.child(cls + 'bottom'),
46654                 fl = ff.child(cls + 'left'),
46655                 fr = ff.child(cls + 'right');
46656
46657             ft.setWidth(bw - 2).setLeftTop(bl + 1, bt);
46658             fb.setWidth(bw - 2).setLeftTop(bl + 1, bt + bh - fw);
46659             fl.setHeight(bh - 2).setLeftTop(bl, bt + 1);
46660             fr.setHeight(bh - 2).setLeftTop(bl + bw - fw, bt + 1);
46661
46662             ff.show();
46663         }
46664
46665         me.fireEvent('componentfocus', me, cmp, me.previousFocusedCmp);
46666     },
46667
46668     onComponentHide: function(cmp) {
46669         var me = this,
46670             CQ = Ext.ComponentQuery,
46671             cmpHadFocus = false,
46672             focusedCmp,
46673             parent;
46674
46675         if (me.focusedCmp) {
46676             focusedCmp = CQ.query('[id=' + me.focusedCmp.id + ']', cmp)[0];
46677             cmpHadFocus = me.focusedCmp.id === cmp.id || focusedCmp;
46678
46679             if (focusedCmp) {
46680                 me.clearComponent(focusedCmp);
46681             }
46682         }
46683
46684         me.clearComponent(cmp);
46685
46686         if (cmpHadFocus) {
46687             parent = CQ.query('^:focusable', cmp)[0];
46688             if (parent) {
46689                 parent.focus();
46690             }
46691         }
46692     },
46693
46694     removeDOM: function() {
46695         var me = this;
46696
46697         // If we are still enabled globally, or there are still subscribers
46698         // then we will halt here, since our DOM stuff is still being used
46699         if (me.enabled || me.subscribers.length) {
46700             return;
46701         }
46702
46703         Ext.destroy(
46704             me.focusEl,
46705             me.focusFrame
46706         );
46707         delete me.focusEl;
46708         delete me.focusFrame;
46709         delete me.focusFrameWidth;
46710     },
46711
46712     /**
46713      * Removes the specified xtype from the {@link #whitelist}.
46714      * @param {String/Array} xtype Removes the xtype(s) from the {@link #whitelist}.
46715      */
46716     removeXTypeFromWhitelist: function(xtype) {
46717         var me = this;
46718
46719         if (Ext.isArray(xtype)) {
46720             Ext.Array.forEach(xtype, me.removeXTypeFromWhitelist, me);
46721             return;
46722         }
46723
46724         Ext.Array.remove(me.whitelist, xtype);
46725     },
46726
46727     setFocus: function(cmp, focusable, options) {
46728         var me = this,
46729             el, dom, data,
46730
46731             needsTabIndex = function(n) {
46732                 return !Ext.Array.contains(me.tabIndexWhitelist, n.tagName.toLowerCase())
46733                     && n.tabIndex <= 0;
46734             };
46735
46736         options = options || {};
46737
46738         // Come back and do this after the component is rendered
46739         if (!cmp.rendered) {
46740             cmp.on('afterrender', Ext.pass(me.setFocus, arguments, me), me, { single: true });
46741             return;
46742         }
46743
46744         el = cmp.getFocusEl();
46745         dom = el.dom;
46746
46747         // Decorate the component's focus el for focus-ability
46748         if ((focusable && !me.focusData[cmp.id]) || (!focusable && me.focusData[cmp.id])) {
46749             if (focusable) {
46750                 data = {
46751                     focusFrame: options.focusFrame
46752                 };
46753
46754                 // Only set -1 tabIndex if we need it
46755                 // inputs, buttons, and anchor tags do not need it,
46756                 // and neither does any DOM that has it set already
46757                 // programmatically or in markup.
46758                 if (needsTabIndex(dom)) {
46759                     data.tabIndex = dom.tabIndex;
46760                     dom.tabIndex = -1;
46761                 }
46762
46763                 el.on({
46764                     focus: data.focusFn = Ext.bind(me.onComponentFocus, me, [cmp], 0),
46765                     blur: data.blurFn = Ext.bind(me.onComponentBlur, me, [cmp], 0),
46766                     scope: me
46767                 });
46768                 cmp.on({
46769                     hide: me.onComponentHide,
46770                     close: me.onComponentHide,
46771                     beforedestroy: me.onComponentDestroy,
46772                     scope: me
46773                 });
46774
46775                 me.focusData[cmp.id] = data;
46776             } else {
46777                 data = me.focusData[cmp.id];
46778                 if ('tabIndex' in data) {
46779                     dom.tabIndex = data.tabIndex;
46780                 }
46781                 el.un('focus', data.focusFn, me);
46782                 el.un('blur', data.blurFn, me);
46783                 cmp.un('hide', me.onComponentHide, me);
46784                 cmp.un('close', me.onComponentHide, me);
46785                 cmp.un('beforedestroy', me.onComponentDestroy, me);
46786
46787                 delete me.focusData[cmp.id];
46788             }
46789         }
46790     },
46791
46792     setFocusAll: function(focusable, options) {
46793         var me = this,
46794             cmps = Ext.ComponentManager.all.getArray(),
46795             len = cmps.length,
46796             cmp,
46797             i = 0;
46798
46799         for (; i < len; i++) {
46800             me.setFocus(cmps[i], focusable, options);
46801         }
46802     },
46803
46804     setupSubscriberKeys: function(container, keys) {
46805         var me = this,
46806             el = container.getFocusEl(),
46807             scope = keys.scope,
46808             handlers = {
46809                 backspace: me.focusLast,
46810                 enter: me.navigateIn,
46811                 esc: me.navigateOut,
46812                 scope: me
46813             },
46814
46815             navSiblings = function(e) {
46816                 if (me.focusedCmp === container) {
46817                     // Root the sibling navigation to this container, so that we
46818                     // can automatically dive into the container, rather than forcing
46819                     // the user to hit the enter key to dive in.
46820                     return me.navigateSiblings(e, me, container);
46821                 } else {
46822                     return me.navigateSiblings(e);
46823                 }
46824             };
46825
46826         Ext.iterate(keys, function(key, cb) {
46827             handlers[key] = function(e) {
46828                 var ret = navSiblings(e);
46829
46830                 if (Ext.isFunction(cb) && cb.call(scope || container, e, ret) === true) {
46831                     return true;
46832                 }
46833
46834                 return ret;
46835             };
46836         }, me);
46837
46838         return Ext.create('Ext.util.KeyNav', el, handlers);
46839     },
46840
46841     shouldShowFocusFrame: function(cmp) {
46842         var me = this,
46843             opts = me.options || {};
46844
46845         if (!me.focusFrame || !cmp) {
46846             return false;
46847         }
46848
46849         // Global trumps
46850         if (opts.focusFrame) {
46851             return true;
46852         }
46853
46854         if (me.focusData[cmp.id].focusFrame) {
46855             return true;
46856         }
46857
46858         return false;
46859     },
46860
46861     /**
46862      * Subscribes an {@link Ext.container.Container} to provide basic keyboard focus navigation between its child {@link Ext.Component}'s.
46863      * @param {Ext.container.Container} container A reference to the {@link Ext.container.Container} on which to enable keyboard functionality and focus management.
46864      * @param {Boolean/Object} options An object of the following options:
46865         - keys : Array/Object
46866             An array containing the string names of navigation keys to be supported. The allowed values are:
46867
46868             - 'left'
46869             - 'right'
46870             - 'up'
46871             - 'down'
46872
46873             Or, an object containing those key names as keys with `true` or a callback function as their value. A scope may also be passed. E.g.:
46874
46875                 {
46876                     left: this.onLeftKey,
46877                     right: this.onRightKey,
46878                     scope: this
46879                 }
46880
46881         - focusFrame : Boolean (optional)
46882             `true` to show the focus frame around a component when it is focused. Defaults to `false`.
46883      * @markdown
46884      */
46885     subscribe: function(container, options) {
46886         var me = this,
46887             EA = Ext.Array,
46888             data = {},
46889             subs = me.subscribers,
46890
46891             // Recursively add focus ability as long as a descendent container isn't
46892             // itself subscribed to the FocusManager, or else we'd have unwanted side
46893             // effects for subscribing a descendent container twice.
46894             safeSetFocus = function(cmp) {
46895                 if (cmp.isContainer && !subs.containsKey(cmp.id)) {
46896                     EA.forEach(cmp.query('>'), safeSetFocus);
46897                     me.setFocus(cmp, true, options);
46898                     cmp.on('add', data.onAdd, me);
46899                 } else if (!cmp.isContainer) {
46900                     me.setFocus(cmp, true, options);
46901                 }
46902             };
46903
46904         // We only accept containers
46905         if (!container || !container.isContainer) {
46906             return;
46907         }
46908
46909         if (!container.rendered) {
46910             container.on('afterrender', Ext.pass(me.subscribe, arguments, me), me, { single: true });
46911             return;
46912         }
46913
46914         // Init the DOM, incase this is the first time it will be used
46915         me.initDOM(options);
46916
46917         // Create key navigation for subscriber based on keys option
46918         data.keyNav = me.setupSubscriberKeys(container, options.keys);
46919
46920         // We need to keep track of components being added to our subscriber
46921         // and any containers nested deeply within it (omg), so let's do that.
46922         // Components that are removed are globally handled.
46923         // Also keep track of destruction of our container for auto-unsubscribe.
46924         data.onAdd = function(ct, cmp, idx) {
46925             safeSetFocus(cmp);
46926         };
46927         container.on('beforedestroy', me.unsubscribe, me);
46928
46929         // Now we setup focusing abilities for the container and all its components
46930         safeSetFocus(container);
46931
46932         // Add to our subscribers list
46933         subs.add(container.id, data);
46934     },
46935
46936     /**
46937      * Unsubscribes an {@link Ext.container.Container} from keyboard focus management.
46938      * @param {Ext.container.Container} container A reference to the {@link Ext.container.Container} to unsubscribe from the FocusManager.
46939      * @markdown
46940      */
46941     unsubscribe: function(container) {
46942         var me = this,
46943             EA = Ext.Array,
46944             subs = me.subscribers,
46945             data,
46946
46947             // Recursively remove focus ability as long as a descendent container isn't
46948             // itself subscribed to the FocusManager, or else we'd have unwanted side
46949             // effects for unsubscribing an ancestor container.
46950             safeSetFocus = function(cmp) {
46951                 if (cmp.isContainer && !subs.containsKey(cmp.id)) {
46952                     EA.forEach(cmp.query('>'), safeSetFocus);
46953                     me.setFocus(cmp, false);
46954                     cmp.un('add', data.onAdd, me);
46955                 } else if (!cmp.isContainer) {
46956                     me.setFocus(cmp, false);
46957                 }
46958             };
46959
46960         if (!container || !subs.containsKey(container.id)) {
46961             return;
46962         }
46963
46964         data = subs.get(container.id);
46965         data.keyNav.destroy();
46966         container.un('beforedestroy', me.unsubscribe, me);
46967         subs.removeAtKey(container.id);
46968         safeSetFocus(container);
46969         me.removeDOM();
46970     }
46971 });
46972 /**
46973  * @class Ext.toolbar.Toolbar
46974  * @extends Ext.container.Container
46975
46976 Basic Toolbar class. Although the {@link Ext.container.Container#defaultType defaultType} for Toolbar is {@link Ext.button.Button button}, Toolbar 
46977 elements (child items for the Toolbar container) may be virtually any type of Component. Toolbar elements can be created explicitly via their 
46978 constructors, or implicitly via their xtypes, and can be {@link #add}ed dynamically.
46979
46980 __Some items have shortcut strings for creation:__
46981
46982 | Shortcut | xtype         | Class                         | Description                                        |
46983 |:---------|:--------------|:------------------------------|:---------------------------------------------------|
46984 | `->`     | `tbspacer`    | {@link Ext.toolbar.Fill}      | begin using the right-justified button container   |
46985 | `-`      | `tbseparator` | {@link Ext.toolbar.Separator} | add a vertical separator bar between toolbar items |
46986 | ` `      | `tbspacer`    | {@link Ext.toolbar.Spacer}    | add horiztonal space between elements              |
46987
46988 {@img Ext.toolbar.Toolbar/Ext.toolbar.Toolbar1.png Toolbar component}
46989 Example usage:
46990
46991     Ext.create('Ext.toolbar.Toolbar", {
46992         renderTo: document.body,
46993         width   : 500,
46994         items: [
46995             {
46996                 // xtype: 'button', // default for Toolbars
46997                 text: 'Button'
46998             },
46999             {
47000                 xtype: 'splitbutton',
47001                 text : 'Split Button'
47002             },
47003             // begin using the right-justified button container
47004             '->', // same as {xtype: 'tbfill'}, // Ext.toolbar.Fill
47005             {
47006                 xtype    : 'textfield',
47007                 name     : 'field1',
47008                 emptyText: 'enter search term'
47009             },
47010             // add a vertical separator bar between toolbar items
47011             '-', // same as {xtype: 'tbseparator'} to create Ext.toolbar.Separator
47012             'text 1', // same as {xtype: 'tbtext', text: 'text1'} to create Ext.toolbar.TextItem
47013             {xtype: 'tbspacer'},// same as ' ' to create Ext.toolbar.Spacer
47014             'text 2',
47015             {xtype: 'tbspacer', width: 50}, // add a 50px space
47016             'text 3'
47017         ]
47018     });
47019
47020 Toolbars have {@link #enable} and {@link #disable} methods which when called, will enable/disable all items within your toolbar.
47021
47022 {@img Ext.toolbar.Toolbar/Ext.toolbar.Toolbar2.png Toolbar component}
47023 Example usage:
47024
47025     Ext.create('Ext.toolbar.Toolbar', {
47026         renderTo: document.body,
47027         width   : 400,
47028         items: [
47029             {
47030                 text: 'Button'
47031             },
47032             {
47033                 xtype: 'splitbutton',
47034                 text : 'Split Button'
47035             },
47036             '->',
47037             {
47038                 xtype    : 'textfield',
47039                 name     : 'field1',
47040                 emptyText: 'enter search term'
47041             }
47042         ]
47043     });
47044
47045 {@img Ext.toolbar.Toolbar/Ext.toolbar.Toolbar3.png Toolbar component}
47046 Example usage:
47047     
47048     var enableBtn = Ext.create('Ext.button.Button', {
47049         text    : 'Enable All Items',
47050         disabled: true,
47051         scope   : this,
47052         handler : function() {
47053             //disable the enable button and enable the disable button
47054             enableBtn.disable();
47055             disableBtn.enable();
47056             
47057             //enable the toolbar
47058             toolbar.enable();
47059         }
47060     });
47061     
47062     var disableBtn = Ext.create('Ext.button.Button', {
47063         text    : 'Disable All Items',
47064         scope   : this,
47065         handler : function() {
47066             //enable the enable button and disable button
47067             disableBtn.disable();
47068             enableBtn.enable();
47069             
47070             //disable the toolbar
47071             toolbar.disable();
47072         }
47073     });
47074     
47075     var toolbar = Ext.create('Ext.toolbar.Toolbar', {
47076         renderTo: document.body,
47077         width   : 400,
47078         margin  : '5 0 0 0',
47079         items   : [enableBtn, disableBtn]
47080     });
47081
47082 Adding items to and removing items from a toolbar is as simple as calling the {@link #add} and {@link #remove} methods. There is also a {@link #removeAll} method 
47083 which remove all items within the toolbar.
47084
47085 {@img Ext.toolbar.Toolbar/Ext.toolbar.Toolbar4.png Toolbar component}
47086 Example usage:
47087
47088     var toolbar = Ext.create('Ext.toolbar.Toolbar', {
47089         renderTo: document.body,
47090         width   : 700,
47091         items: [
47092             {
47093                 text: 'Example Button'
47094             }
47095         ]
47096     });
47097     
47098     var addedItems = [];
47099     
47100     Ext.create('Ext.toolbar.Toolbar', {
47101         renderTo: document.body,
47102         width   : 700,
47103         margin  : '5 0 0 0',
47104         items   : [
47105             {
47106                 text   : 'Add a button',
47107                 scope  : this,
47108                 handler: function() {
47109                     var text = prompt('Please enter the text for your button:');
47110                     addedItems.push(toolbar.add({
47111                         text: text
47112                     }));
47113                 }
47114             },
47115             {
47116                 text   : 'Add a text item',
47117                 scope  : this,
47118                 handler: function() {
47119                     var text = prompt('Please enter the text for your item:');
47120                     addedItems.push(toolbar.add(text));
47121                 }
47122             },
47123             {
47124                 text   : 'Add a toolbar seperator',
47125                 scope  : this,
47126                 handler: function() {
47127                     addedItems.push(toolbar.add('-'));
47128                 }
47129             },
47130             {
47131                 text   : 'Add a toolbar spacer',
47132                 scope  : this,
47133                 handler: function() {
47134                     addedItems.push(toolbar.add('->'));
47135                 }
47136             },
47137             '->',
47138             {
47139                 text   : 'Remove last inserted item',
47140                 scope  : this,
47141                 handler: function() {
47142                     if (addedItems.length) {
47143                         toolbar.remove(addedItems.pop());
47144                     } else if (toolbar.items.length) {
47145                         toolbar.remove(toolbar.items.last());
47146                     } else {
47147                         alert('No items in the toolbar');
47148                     }
47149                 }
47150             },
47151             {
47152                 text   : 'Remove all items',
47153                 scope  : this,
47154                 handler: function() {
47155                     toolbar.removeAll();
47156                 }
47157             }
47158         ]
47159     });
47160
47161  * @constructor
47162  * Creates a new Toolbar
47163  * @param {Object/Array} config A config object or an array of buttons to <code>{@link #add}</code>
47164  * @xtype toolbar
47165  * @docauthor Robert Dougan <rob@sencha.com>
47166  * @markdown
47167  */
47168 Ext.define('Ext.toolbar.Toolbar', {
47169     extend: 'Ext.container.Container',
47170     requires: [
47171         'Ext.toolbar.Fill',
47172         'Ext.layout.container.HBox',
47173         'Ext.layout.container.VBox',
47174         'Ext.FocusManager'
47175     ],
47176     uses: [
47177         'Ext.toolbar.Separator'
47178     ],
47179     alias: 'widget.toolbar',
47180     alternateClassName: 'Ext.Toolbar',
47181     
47182     isToolbar: true,
47183     baseCls  : Ext.baseCSSPrefix + 'toolbar',
47184     ariaRole : 'toolbar',
47185     
47186     defaultType: 'button',
47187     
47188     /**
47189      * @cfg {Boolean} vertical
47190      * Set to `true` to make the toolbar vertical. The layout will become a `vbox`.
47191      * (defaults to `false`)
47192      */
47193     vertical: false,
47194
47195     /**
47196      * @cfg {String/Object} layout
47197      * This class assigns a default layout (<code>layout:'<b>hbox</b>'</code>).
47198      * Developers <i>may</i> override this configuration option if another layout
47199      * is required (the constructor must be passed a configuration object in this
47200      * case instead of an array).
47201      * See {@link Ext.container.Container#layout} for additional information.
47202      */
47203
47204     /**
47205      * @cfg {Boolean} enableOverflow
47206      * Defaults to false. Configure <code>true</code> to make the toolbar provide a button
47207      * which activates a dropdown Menu to show items which overflow the Toolbar's width.
47208      */
47209     enableOverflow: false,
47210     
47211     // private
47212     trackMenus: true,
47213     
47214     itemCls: Ext.baseCSSPrefix + 'toolbar-item',
47215     
47216     initComponent: function() {
47217         var me = this,
47218             keys;
47219
47220         // check for simplified (old-style) overflow config:
47221         if (!me.layout && me.enableOverflow) {
47222             me.layout = { overflowHandler: 'Menu' };
47223         }
47224         
47225         if (me.dock === 'right' || me.dock === 'left') {
47226             me.vertical = true;
47227         }
47228
47229         me.layout = Ext.applyIf(Ext.isString(me.layout) ? {
47230             type: me.layout
47231         } : me.layout || {}, {
47232             type: me.vertical ? 'vbox' : 'hbox',
47233             align: me.vertical ? 'stretchmax' : 'middle'
47234         });
47235         
47236         if (me.vertical) {
47237             me.addClsWithUI('vertical');
47238         }
47239         
47240         // @TODO: remove this hack and implement a more general solution
47241         if (me.ui === 'footer') {
47242             me.ignoreBorderManagement = true;
47243         }
47244         
47245         me.callParent();
47246
47247         /**
47248          * @event overflowchange
47249          * Fires after the overflow state has changed.
47250          * @param {Object} c The Container
47251          * @param {Boolean} lastOverflow overflow state
47252          */
47253         me.addEvents('overflowchange');
47254         
47255         // Subscribe to Ext.FocusManager for key navigation
47256         keys = me.vertical ? ['up', 'down'] : ['left', 'right'];
47257         Ext.FocusManager.subscribe(me, {
47258             keys: keys
47259         });
47260     },
47261
47262     /**
47263      * <p>Adds element(s) to the toolbar -- this function takes a variable number of
47264      * arguments of mixed type and adds them to the toolbar.</p>
47265      * <br><p><b>Note</b>: See the notes within {@link Ext.container.Container#add}.</p>
47266      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
47267      * <ul>
47268      * <li>{@link Ext.button.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
47269      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
47270      * <li>Field: Any form field (equivalent to {@link #addField})</li>
47271      * <li>Item: Any subclass of {@link Ext.toolbar.Item} (equivalent to {@link #addItem})</li>
47272      * <li>String: Any generic string (gets wrapped in a {@link Ext.toolbar.TextItem}, equivalent to {@link #addText}).
47273      * Note that there are a few special strings that are treated differently as explained next.</li>
47274      * <li>'-': Creates a separator element (equivalent to {@link #addSeparator})</li>
47275      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
47276      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
47277      * </ul>
47278      * @param {Mixed} arg2
47279      * @param {Mixed} etc.
47280      * @method add
47281      */
47282
47283     // private
47284     lookupComponent: function(c) {
47285         if (Ext.isString(c)) {
47286             var shortcut = Ext.toolbar.Toolbar.shortcuts[c];
47287             if (shortcut) {
47288                 c = {
47289                     xtype: shortcut
47290                 };
47291             } else {
47292                 c = {
47293                     xtype: 'tbtext',
47294                     text: c
47295                 };
47296             }
47297             this.applyDefaults(c);
47298         }
47299         return this.callParent(arguments);
47300     },
47301
47302     // private
47303     applyDefaults: function(c) {
47304         if (!Ext.isString(c)) {
47305             c = this.callParent(arguments);
47306             var d = this.internalDefaults;
47307             if (c.events) {
47308                 Ext.applyIf(c.initialConfig, d);
47309                 Ext.apply(c, d);
47310             } else {
47311                 Ext.applyIf(c, d);
47312             }
47313         }
47314         return c;
47315     },
47316
47317     // private
47318     trackMenu: function(item, remove) {
47319         if (this.trackMenus && item.menu) {
47320             var method = remove ? 'mun' : 'mon',
47321                 me = this;
47322
47323             me[method](item, 'menutriggerover', me.onButtonTriggerOver, me);
47324             me[method](item, 'menushow', me.onButtonMenuShow, me);
47325             me[method](item, 'menuhide', me.onButtonMenuHide, me);
47326         }
47327     },
47328
47329     // private
47330     constructButton: function(item) {
47331         return item.events ? item : this.createComponent(item, item.split ? 'splitbutton' : this.defaultType);
47332     },
47333
47334     // private
47335     onBeforeAdd: function(component) {
47336         if (component.is('field') || (component.is('button') && this.ui != 'footer')) {
47337             component.ui = component.ui + '-toolbar';
47338         }
47339         
47340         // Any separators needs to know if is vertical or not
47341         if (component instanceof Ext.toolbar.Separator) {
47342             component.setUI((this.vertical) ? 'vertical' : 'horizontal');
47343         }
47344         
47345         this.callParent(arguments);
47346     },
47347
47348     // private
47349     onAdd: function(component) {
47350         this.callParent(arguments);
47351
47352         this.trackMenu(component);
47353         if (this.disabled) {
47354             component.disable();
47355         }
47356     },
47357
47358     // private
47359     onRemove: function(c) {
47360         this.callParent(arguments);
47361         this.trackMenu(c, true);
47362     },
47363
47364     // private
47365     onButtonTriggerOver: function(btn){
47366         if (this.activeMenuBtn && this.activeMenuBtn != btn) {
47367             this.activeMenuBtn.hideMenu();
47368             btn.showMenu();
47369             this.activeMenuBtn = btn;
47370         }
47371     },
47372
47373     // private
47374     onButtonMenuShow: function(btn) {
47375         this.activeMenuBtn = btn;
47376     },
47377
47378     // private
47379     onButtonMenuHide: function(btn) {
47380         delete this.activeMenuBtn;
47381     }
47382 }, function() {
47383     this.shortcuts = {
47384         '-' : 'tbseparator',
47385         ' ' : 'tbspacer',
47386         '->': 'tbfill'
47387     };
47388 });
47389 /**
47390  * @class Ext.panel.AbstractPanel
47391  * @extends Ext.container.Container
47392  * <p>A base class which provides methods common to Panel classes across the Sencha product range.</p>
47393  * <p>Please refer to sub class's documentation</p>
47394  * @constructor
47395  * @param {Object} config The config object
47396  */
47397 Ext.define('Ext.panel.AbstractPanel', {
47398
47399     /* Begin Definitions */
47400
47401     extend: 'Ext.container.Container',
47402
47403     requires: ['Ext.util.MixedCollection', 'Ext.core.Element', 'Ext.toolbar.Toolbar'],
47404
47405     /* End Definitions */
47406
47407     /**
47408      * @cfg {String} baseCls
47409      * The base CSS class to apply to this panel's element (defaults to <code>'x-panel'</code>).
47410      */
47411     baseCls : Ext.baseCSSPrefix + 'panel',
47412
47413     /**
47414      * @cfg {Number/String} bodyPadding
47415      * A shortcut for setting a padding style on the body element. The value can either be
47416      * a number to be applied to all sides, or a normal css string describing padding.
47417      * Defaults to <code>undefined</code>.
47418      */
47419
47420     /**
47421      * @cfg {Boolean} bodyBorder
47422      * A shortcut to add or remove the border on the body of a panel. This only applies to a panel which has the {@link #frame} configuration set to `true`.
47423      * Defaults to <code>undefined</code>.
47424      */
47425     
47426     /**
47427      * @cfg {String/Object/Function} bodyStyle
47428      * Custom CSS styles to be applied to the panel's body element, which can be supplied as a valid CSS style string,
47429      * an object containing style property name/value pairs or a function that returns such a string or object.
47430      * For example, these two formats are interpreted to be equivalent:<pre><code>
47431 bodyStyle: 'background:#ffc; padding:10px;'
47432
47433 bodyStyle: {
47434     background: '#ffc',
47435     padding: '10px'
47436 }
47437      * </code></pre>
47438      */
47439     
47440     /**
47441      * @cfg {String/Array} bodyCls
47442      * A CSS class, space-delimited string of classes, or array of classes to be applied to the panel's body element.
47443      * The following examples are all valid:<pre><code>
47444 bodyCls: 'foo'
47445 bodyCls: 'foo bar'
47446 bodyCls: ['foo', 'bar']
47447      * </code></pre>
47448      */
47449
47450     isPanel: true,
47451
47452     componentLayout: 'dock',
47453
47454     renderTpl: ['<div class="{baseCls}-body<tpl if="bodyCls"> {bodyCls}</tpl> {baseCls}-body-{ui}<tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-body-{parent.ui}-{.}</tpl></tpl>"<tpl if="bodyStyle"> style="{bodyStyle}"</tpl>></div>'],
47455
47456     // TODO: Move code examples into product-specific files. The code snippet below is Touch only.
47457     /**
47458      * @cfg {Object/Array} dockedItems
47459      * A component or series of components to be added as docked items to this panel.
47460      * The docked items can be docked to either the top, right, left or bottom of a panel.
47461      * This is typically used for things like toolbars or tab bars:
47462      * <pre><code>
47463 var panel = new Ext.panel.Panel({
47464     fullscreen: true,
47465     dockedItems: [{
47466         xtype: 'toolbar',
47467         dock: 'top',
47468         items: [{
47469             text: 'Docked to the top'
47470         }]
47471     }]
47472 });</code></pre>
47473      */
47474      
47475     border: true,
47476
47477     initComponent : function() {
47478         var me = this;
47479         
47480         me.addEvents(
47481             /**
47482              * @event bodyresize
47483              * Fires after the Panel has been resized.
47484              * @param {Ext.panel.Panel} p the Panel which has been resized.
47485              * @param {Number} width The Panel body's new width.
47486              * @param {Number} height The Panel body's new height.
47487              */
47488             'bodyresize'
47489             // // inherited
47490             // 'activate',
47491             // // inherited
47492             // 'deactivate'
47493         );
47494
47495         Ext.applyIf(me.renderSelectors, {
47496             body: '.' + me.baseCls + '-body'
47497         });
47498         
47499         //!frame 
47500         //!border
47501         
47502         if (me.frame && me.border && me.bodyBorder === undefined) {
47503             me.bodyBorder = false;
47504         }
47505         if (me.frame && me.border && (me.bodyBorder === false || me.bodyBorder === 0)) {
47506             me.manageBodyBorders = true;
47507         }
47508         
47509         me.callParent();
47510     },
47511
47512     // @private
47513     initItems : function() {
47514         var me = this,
47515             items = me.dockedItems;
47516             
47517         me.callParent();
47518         me.dockedItems = Ext.create('Ext.util.MixedCollection', false, me.getComponentId);
47519         if (items) {
47520             me.addDocked(items);
47521         }
47522     },
47523
47524     /**
47525      * Finds a docked component by id, itemId or position. Also see {@link #getDockedItems}
47526      * @param {String/Number} comp The id, itemId or position of the docked component (see {@link #getComponent} for details)
47527      * @return {Ext.Component} The docked component (if found)
47528      */
47529     getDockedComponent: function(comp) {
47530         if (Ext.isObject(comp)) {
47531             comp = comp.getItemId();
47532         }
47533         return this.dockedItems.get(comp);
47534     },
47535
47536     /**
47537      * Attempts a default component lookup (see {@link Ext.container.Container#getComponent}). If the component is not found in the normal
47538      * items, the dockedItems are searched and the matched component (if any) returned (see {@loink #getDockedComponent}). Note that docked
47539      * items will only be matched by component id or itemId -- if you pass a numeric index only non-docked child components will be searched.
47540      * @param {String/Number} comp The component id, itemId or position to find
47541      * @return {Ext.Component} The component (if found)
47542      */
47543     getComponent: function(comp) {
47544         var component = this.callParent(arguments);
47545         if (component === undefined && !Ext.isNumber(comp)) {
47546             // If the arg is a numeric index skip docked items
47547             component = this.getDockedComponent(comp);
47548         }
47549         return component;
47550     },
47551
47552     /**
47553      * Parses the {@link bodyStyle} config if available to create a style string that will be applied to the body element.
47554      * This also includes {@link bodyPadding} and {@link bodyBorder} if available.
47555      * @return {String} A CSS style string with body styles, padding and border.
47556      * @private
47557      */
47558     initBodyStyles: function() {
47559         var me = this,
47560             bodyStyle = me.bodyStyle,
47561             styles = [],
47562             Element = Ext.core.Element,
47563             prop;
47564
47565         if (Ext.isFunction(bodyStyle)) {
47566             bodyStyle = bodyStyle();
47567         }
47568         if (Ext.isString(bodyStyle)) {
47569             styles = bodyStyle.split(';');
47570         } else {
47571             for (prop in bodyStyle) {
47572                 if (bodyStyle.hasOwnProperty(prop)) {
47573                     styles.push(prop + ':' + bodyStyle[prop]);
47574                 }
47575             }
47576         }
47577
47578         if (me.bodyPadding !== undefined) {
47579             styles.push('padding: ' + Element.unitizeBox((me.bodyPadding === true) ? 5 : me.bodyPadding));
47580         }
47581         if (me.frame && me.bodyBorder) {
47582             if (!Ext.isNumber(me.bodyBorder)) {
47583                 me.bodyBorder = 1;
47584             }
47585             styles.push('border-width: ' + Element.unitizeBox(me.bodyBorder));
47586         }
47587         delete me.bodyStyle;
47588         return styles.length ? styles.join(';') : undefined;
47589     },
47590     
47591     /**
47592      * Parse the {@link bodyCls} config if available to create a comma-delimited string of 
47593      * CSS classes to be applied to the body element.
47594      * @return {String} The CSS class(es)
47595      * @private
47596      */
47597     initBodyCls: function() {
47598         var me = this,
47599             cls = '',
47600             bodyCls = me.bodyCls;
47601         
47602         if (bodyCls) {
47603             Ext.each(bodyCls, function(v) {
47604                 cls += " " + v;
47605             });
47606             delete me.bodyCls;
47607         }
47608         return cls.length > 0 ? cls : undefined;
47609     },
47610     
47611     /**
47612      * Initialized the renderData to be used when rendering the renderTpl.
47613      * @return {Object} Object with keys and values that are going to be applied to the renderTpl
47614      * @private
47615      */
47616     initRenderData: function() {
47617         return Ext.applyIf(this.callParent(), {
47618             bodyStyle: this.initBodyStyles(),
47619             bodyCls: this.initBodyCls()
47620         });
47621     },
47622
47623     /**
47624      * Adds docked item(s) to the panel.
47625      * @param {Object/Array} component The Component or array of components to add. The components
47626      * must include a 'dock' parameter on each component to indicate where it should be docked ('top', 'right',
47627      * 'bottom', 'left').
47628      * @param {Number} pos (optional) The index at which the Component will be added
47629      */
47630     addDocked : function(items, pos) {
47631         var me = this,
47632             i = 0,
47633             item, length;
47634
47635         items = me.prepareItems(items);
47636         length = items.length;
47637
47638         for (; i < length; i++) {
47639             item = items[i];
47640             item.dock = item.dock || 'top';
47641
47642             // Allow older browsers to target docked items to style without borders
47643             if (me.border === false) {
47644                 // item.cls = item.cls || '' + ' ' + me.baseCls + '-noborder-docked-' + item.dock;
47645             }
47646
47647             if (pos !== undefined) {
47648                 me.dockedItems.insert(pos + i, item);
47649             }
47650             else {
47651                 me.dockedItems.add(item);
47652             }
47653             item.onAdded(me, i);
47654             me.onDockedAdd(item);
47655         }
47656         if (me.rendered) {
47657             me.doComponentLayout();
47658         }
47659         return items;
47660     },
47661
47662     // Placeholder empty functions
47663     onDockedAdd : Ext.emptyFn,
47664     onDockedRemove : Ext.emptyFn,
47665
47666     /**
47667      * Inserts docked item(s) to the panel at the indicated position.
47668      * @param {Number} pos The index at which the Component will be inserted
47669      * @param {Object/Array} component. The Component or array of components to add. The components
47670      * must include a 'dock' paramater on each component to indicate where it should be docked ('top', 'right',
47671      * 'bottom', 'left').
47672      */
47673     insertDocked : function(pos, items) {
47674         this.addDocked(items, pos);
47675     },
47676
47677     /**
47678      * Removes the docked item from the panel.
47679      * @param {Ext.Component} item. The Component to remove.
47680      * @param {Boolean} autoDestroy (optional) Destroy the component after removal.
47681      */
47682     removeDocked : function(item, autoDestroy) {
47683         var me = this,
47684             layout,
47685             hasLayout;
47686             
47687         if (!me.dockedItems.contains(item)) {
47688             return item;
47689         }
47690
47691         layout = me.componentLayout;
47692         hasLayout = layout && me.rendered;
47693
47694         if (hasLayout) {
47695             layout.onRemove(item);
47696         }
47697
47698         me.dockedItems.remove(item);
47699         item.onRemoved();
47700         me.onDockedRemove(item);
47701
47702         if (autoDestroy === true || (autoDestroy !== false && me.autoDestroy)) {
47703             item.destroy();
47704         }
47705
47706         if (hasLayout && !autoDestroy) {
47707             layout.afterRemove(item);
47708         }
47709         
47710         if (!this.destroying) {
47711             me.doComponentLayout();
47712         }
47713
47714         return item;
47715     },
47716
47717     /**
47718      * Retrieve an array of all currently docked Components.
47719      * @param {String} cqSelector A {@link Ext.ComponentQuery ComponentQuery} selector string to filter the returned items.
47720      * @return {Array} An array of components.
47721      */
47722     getDockedItems : function(cqSelector) {
47723         var me = this,
47724             // Start with a weight of 1, so users can provide <= 0 to come before top items
47725             // Odd numbers, so users can provide a weight to come in between if desired
47726             defaultWeight = { top: 1, left: 3, right: 5, bottom: 7 },
47727             dockedItems;
47728
47729         if (me.dockedItems && me.dockedItems.items.length) {
47730             // Allow filtering of returned docked items by CQ selector.
47731             if (cqSelector) {
47732                 dockedItems = Ext.ComponentQuery.query(cqSelector, me.dockedItems.items);
47733             } else {
47734                 dockedItems = me.dockedItems.items.slice();
47735             }
47736
47737             Ext.Array.sort(dockedItems, function(a, b) {
47738                 // Docked items are ordered by their visual representation by default (t,l,r,b)
47739                 // TODO: Enforce position ordering, and have weights be sub-ordering within positions?
47740                 var aw = a.weight || defaultWeight[a.dock],
47741                     bw = b.weight || defaultWeight[b.dock];
47742                 if (Ext.isNumber(aw) && Ext.isNumber(bw)) {
47743                     return aw - bw;
47744                 }
47745                 return 0;
47746             });
47747             
47748             return dockedItems;
47749         }
47750         return [];
47751     },
47752     
47753     // inherit docs
47754     addUIClsToElement: function(cls, force) {
47755         var me = this;
47756         
47757         me.callParent(arguments);
47758         
47759         if (!force && me.rendered) {
47760             me.body.addCls(Ext.baseCSSPrefix + cls);
47761             me.body.addCls(me.baseCls + '-body-' + cls);
47762             me.body.addCls(me.baseCls + '-body-' + me.ui + '-' + cls);
47763         }
47764     },
47765     
47766     // inherit docs
47767     removeUIClsFromElement: function(cls, force) {
47768         var me = this;
47769         
47770         me.callParent(arguments);
47771         
47772         if (!force && me.rendered) {
47773             me.body.removeCls(Ext.baseCSSPrefix + cls);
47774             me.body.removeCls(me.baseCls + '-body-' + cls);
47775             me.body.removeCls(me.baseCls + '-body-' + me.ui + '-' + cls);
47776         }
47777     },
47778     
47779     // inherit docs
47780     addUIToElement: function(force) {
47781         var me = this;
47782         
47783         me.callParent(arguments);
47784         
47785         if (!force && me.rendered) {
47786             me.body.addCls(me.baseCls + '-body-' + me.ui);
47787         }
47788     },
47789     
47790     // inherit docs
47791     removeUIFromElement: function() {
47792         var me = this;
47793         
47794         me.callParent(arguments);
47795         
47796         if (me.rendered) {
47797             me.body.removeCls(me.baseCls + '-body-' + me.ui);
47798         }
47799     },
47800
47801     // @private
47802     getTargetEl : function() {
47803         return this.body;
47804     },
47805
47806     getRefItems: function(deep) {
47807         var items = this.callParent(arguments),
47808             // deep fetches all docked items, and their descendants using '*' selector and then '* *'
47809             dockedItems = this.getDockedItems(deep ? '*,* *' : undefined),
47810             ln = dockedItems.length,
47811             i = 0,
47812             item;
47813         
47814         // Find the index where we go from top/left docked items to right/bottom docked items
47815         for (; i < ln; i++) {
47816             item = dockedItems[i];
47817             if (item.dock === 'right' || item.dock === 'bottom') {
47818                 break;
47819             }
47820         }
47821         
47822         // Return docked items in the top/left position before our container items, and
47823         // return right/bottom positioned items after our container items.
47824         // See AbstractDock.renderItems() for more information.
47825         return dockedItems.splice(0, i).concat(items).concat(dockedItems);
47826     },
47827
47828     beforeDestroy: function(){
47829         var docked = this.dockedItems,
47830             c;
47831
47832         if (docked) {
47833             while ((c = docked.first())) {
47834                 this.removeDocked(c, true);
47835             }
47836         }
47837         this.callParent();
47838     },
47839     
47840     setBorder: function(border) {
47841         var me = this;
47842         me.border = (border !== undefined) ? border : true;
47843         if (me.rendered) {
47844             me.doComponentLayout();
47845         }
47846     }
47847 });
47848 /**
47849  * @class Ext.panel.Header
47850  * @extends Ext.container.Container
47851  * Simple header class which is used for on {@link Ext.panel.Panel} and {@link Ext.window.Window}
47852  * @xtype header
47853  */
47854 Ext.define('Ext.panel.Header', {
47855     extend: 'Ext.container.Container',
47856     uses: ['Ext.panel.Tool', 'Ext.draw.Component', 'Ext.util.CSS'],
47857     alias: 'widget.header',
47858
47859     isHeader       : true,
47860     defaultType    : 'tool',
47861     indicateDrag   : false,
47862     weight         : -1,
47863
47864     renderTpl: ['<div class="{baseCls}-body<tpl if="bodyCls"> {bodyCls}</tpl><tpl if="uiCls"><tpl for="uiCls"> {parent.baseCls}-body-{parent.ui}-{.}</tpl></tpl>"<tpl if="bodyStyle"> style="{bodyStyle}"</tpl>></div>'],
47865
47866     initComponent: function() {
47867         var me = this,
47868             rule,
47869             style,
47870             titleTextEl,
47871             ui;
47872
47873         me.indicateDragCls = me.baseCls + '-draggable';
47874         me.title = me.title || '&#160;';
47875         me.tools = me.tools || [];
47876         me.items = me.items || [];
47877         me.orientation = me.orientation || 'horizontal';
47878         me.dock = (me.dock) ? me.dock : (me.orientation == 'horizontal') ? 'top' : 'left';
47879
47880         //add the dock as a ui
47881         //this is so we support top/right/left/bottom headers
47882         me.addClsWithUI(me.orientation);
47883         me.addClsWithUI(me.dock);
47884
47885         Ext.applyIf(me.renderSelectors, {
47886             body: '.' + me.baseCls + '-body'
47887         });
47888
47889         // Add Icon
47890         if (!Ext.isEmpty(me.iconCls)) {
47891             me.initIconCmp();
47892             me.items.push(me.iconCmp);
47893         }
47894
47895         // Add Title
47896         if (me.orientation == 'vertical') {
47897             // Hack for IE6/7's inability to display an inline-block
47898             if (Ext.isIE6 || Ext.isIE7) {
47899                 me.width = this.width || 24;
47900             } else if (Ext.isIEQuirks) {
47901                 me.width = this.width || 25;
47902             }
47903
47904             me.layout = {
47905                 type : 'vbox',
47906                 align: 'center',
47907                 clearInnerCtOnLayout: true,
47908                 bindToOwnerCtContainer: false
47909             };
47910             me.textConfig = {
47911                 cls: me.baseCls + '-text',
47912                 type: 'text',
47913                 text: me.title,
47914                 rotate: {
47915                     degrees: 90
47916                 }
47917             };
47918             ui = me.ui;
47919             if (Ext.isArray(ui)) {
47920                 ui = ui[0];
47921             }
47922             rule = Ext.util.CSS.getRule('.' + me.baseCls + '-text-' + ui);
47923             if (rule) {
47924                 style = rule.style;
47925             }
47926             if (style) {
47927                 Ext.apply(me.textConfig, {
47928                     'font-family': style.fontFamily,
47929                     'font-weight': style.fontWeight,
47930                     'font-size': style.fontSize,
47931                     fill: style.color
47932                 });
47933             }
47934             me.titleCmp = Ext.create('Ext.draw.Component', {
47935                 ariaRole  : 'heading',
47936                 focusable: false,
47937                 viewBox: false,
47938                 autoSize: true,
47939                 margins: '5 0 0 0',
47940                 items: [ me.textConfig ],
47941                 renderSelectors: {
47942                     textEl: '.' + me.baseCls + '-text'
47943                 }
47944             });
47945         } else {
47946             me.layout = {
47947                 type : 'hbox',
47948                 align: 'middle',
47949                 clearInnerCtOnLayout: true,
47950                 bindToOwnerCtContainer: false
47951             };
47952             me.titleCmp = Ext.create('Ext.Component', {
47953                 xtype     : 'component',
47954                 ariaRole  : 'heading',
47955                 focusable: false,
47956                 renderTpl : ['<span class="{cls}-text {cls}-text-{ui}">{title}</span>'],
47957                 renderData: {
47958                     title: me.title,
47959                     cls  : me.baseCls,
47960                     ui   : me.ui
47961                 },
47962                 renderSelectors: {
47963                     textEl: '.' + me.baseCls + '-text'
47964                 }
47965             });
47966         }
47967         me.items.push(me.titleCmp);
47968
47969         // Spacer ->
47970         me.items.push({
47971             xtype: 'component',
47972             html : '&nbsp;',
47973             flex : 1,
47974             focusable: false
47975         });
47976
47977         // Add Tools
47978         me.items = me.items.concat(me.tools);
47979         this.callParent();
47980     },
47981
47982     initIconCmp: function() {
47983         this.iconCmp = Ext.create('Ext.Component', {
47984             focusable: false,
47985             renderTpl : ['<img alt="" src="{blank}" class="{cls}-icon {iconCls}"/>'],
47986             renderData: {
47987                 blank  : Ext.BLANK_IMAGE_URL,
47988                 cls    : this.baseCls,
47989                 iconCls: this.iconCls,
47990                 orientation: this.orientation
47991             },
47992             renderSelectors: {
47993                 iconEl: '.' + this.baseCls + '-icon'
47994             },
47995             iconCls: this.iconCls
47996         });
47997     },
47998
47999     afterRender: function() {
48000         var me = this;
48001
48002         me.el.unselectable();
48003         if (me.indicateDrag) {
48004             me.el.addCls(me.indicateDragCls);
48005         }
48006         me.mon(me.el, {
48007             click: me.onClick,
48008             scope: me
48009         });
48010         me.callParent();
48011     },
48012
48013     afterLayout: function() {
48014         var me = this;
48015         me.callParent(arguments);
48016
48017         // IE7 needs a forced repaint to make the top framing div expand to full width
48018         if (Ext.isIE7) {
48019             me.el.repaint();
48020         }
48021     },
48022
48023     // inherit docs
48024     addUIClsToElement: function(cls, force) {
48025         var me = this;
48026
48027         me.callParent(arguments);
48028
48029         if (!force && me.rendered) {
48030             me.body.addCls(me.baseCls + '-body-' + cls);
48031             me.body.addCls(me.baseCls + '-body-' + me.ui + '-' + cls);
48032         }
48033     },
48034
48035     // inherit docs
48036     removeUIClsFromElement: function(cls, force) {
48037         var me = this;
48038
48039         me.callParent(arguments);
48040
48041         if (!force && me.rendered) {
48042             me.body.removeCls(me.baseCls + '-body-' + cls);
48043             me.body.removeCls(me.baseCls + '-body-' + me.ui + '-' + cls);
48044         }
48045     },
48046
48047     // inherit docs
48048     addUIToElement: function(force) {
48049         var me = this;
48050
48051         me.callParent(arguments);
48052
48053         if (!force && me.rendered) {
48054             me.body.addCls(me.baseCls + '-body-' + me.ui);
48055         }
48056
48057         if (!force && me.titleCmp && me.titleCmp.rendered && me.titleCmp.textEl) {
48058             me.titleCmp.textEl.addCls(me.baseCls + '-text-' + me.ui);
48059         }
48060     },
48061
48062     // inherit docs
48063     removeUIFromElement: function() {
48064         var me = this;
48065
48066         me.callParent(arguments);
48067
48068         if (me.rendered) {
48069             me.body.removeCls(me.baseCls + '-body-' + me.ui);
48070         }
48071
48072         if (me.titleCmp && me.titleCmp.rendered && me.titleCmp.textEl) {
48073             me.titleCmp.textEl.removeCls(me.baseCls + '-text-' + me.ui);
48074         }
48075     },
48076
48077     onClick: function(e) {
48078         if (!e.getTarget(Ext.baseCSSPrefix + 'tool')) {
48079             this.fireEvent('click', e);
48080         }
48081     },
48082
48083     getTargetEl: function() {
48084         return this.body || this.frameBody || this.el;
48085     },
48086
48087     /**
48088      * Sets the title of the header.
48089      * @param {String} title The title to be set
48090      */
48091     setTitle: function(title) {
48092         var me = this;
48093         if (me.rendered) {
48094             if (me.titleCmp.rendered) {
48095                 if (me.titleCmp.surface) {
48096                     me.title = title || '';
48097                     var sprite = me.titleCmp.surface.items.items[0],
48098                         surface = me.titleCmp.surface;
48099
48100                     surface.remove(sprite);
48101                     me.textConfig.type = 'text';
48102                     me.textConfig.text = title;
48103                     sprite = surface.add(me.textConfig);
48104                     sprite.setAttributes({
48105                         rotate: {
48106                             degrees: 90
48107                         }
48108                     }, true);
48109                     me.titleCmp.autoSizeSurface();
48110                 } else {
48111                     me.title = title || '&#160;';
48112                     me.titleCmp.textEl.update(me.title);
48113                 }
48114             } else {
48115                 me.titleCmp.on({
48116                     render: function() {
48117                         me.setTitle(title);
48118                     },
48119                     single: true
48120                 });
48121             }
48122         } else {
48123             me.on({
48124                 render: function() {
48125                     me.layout.layout();
48126                     me.setTitle(title);
48127                 },
48128                 single: true
48129             });
48130         }
48131     },
48132
48133     /**
48134      * Sets the CSS class that provides the icon image for this panel.  This method will replace any existing
48135      * icon class if one has already been set and fire the {@link #iconchange} event after completion.
48136      * @param {String} cls The new CSS class name
48137      */
48138     setIconCls: function(cls) {
48139         this.iconCls = cls;
48140         if (!this.iconCmp) {
48141             this.initIconCmp();
48142             this.insert(0, this.iconCmp);
48143         }
48144         else {
48145             if (!cls || !cls.length) {
48146                 this.iconCmp.destroy();
48147             }
48148             else {
48149                 var iconCmp = this.iconCmp,
48150                     el      = iconCmp.iconEl;
48151
48152                 el.removeCls(iconCmp.iconCls);
48153                 el.addCls(cls);
48154                 iconCmp.iconCls = cls;
48155             }
48156         }
48157     },
48158
48159     /**
48160      * Add a tool to the header
48161      * @param {Object} tool
48162      */
48163     addTool: function(tool) {
48164         this.tools.push(this.add(tool));
48165     },
48166
48167     /**
48168      * @private
48169      * Set up the tools.&lt;tool type> link in the owning Panel.
48170      * Bind the tool to its owning Panel.
48171      * @param component
48172      * @param index
48173      */
48174     onAdd: function(component, index) {
48175         this.callParent([arguments]);
48176         if (component instanceof Ext.panel.Tool) {
48177             component.bindTo(this.ownerCt);
48178             this.tools[component.type] = component;
48179         }
48180     }
48181 });
48182
48183 /**
48184  * @class Ext.fx.target.Element
48185  * @extends Ext.fx.target.Target
48186  * 
48187  * This class represents a animation target for an {@link Ext.core.Element}. In general this class will not be
48188  * created directly, the {@link Ext.core.Element} will be passed to the animation and
48189  * and the appropriate target will be created.
48190  */
48191 Ext.define('Ext.fx.target.Element', {
48192
48193     /* Begin Definitions */
48194     
48195     extend: 'Ext.fx.target.Target',
48196     
48197     /* End Definitions */
48198
48199     type: 'element',
48200
48201     getElVal: function(el, attr, val) {
48202         if (val == undefined) {
48203             if (attr === 'x') {
48204                 val = el.getX();
48205             }
48206             else if (attr === 'y') {
48207                 val = el.getY();
48208             }
48209             else if (attr === 'scrollTop') {
48210                 val = el.getScroll().top;
48211             }
48212             else if (attr === 'scrollLeft') {
48213                 val = el.getScroll().left;
48214             }
48215             else if (attr === 'height') {
48216                 val = el.getHeight();
48217             }
48218             else if (attr === 'width') {
48219                 val = el.getWidth();
48220             }
48221             else {
48222                 val = el.getStyle(attr);
48223             }
48224         }
48225         return val;
48226     },
48227
48228     getAttr: function(attr, val) {
48229         var el = this.target;
48230         return [[ el, this.getElVal(el, attr, val)]];
48231     },
48232
48233     setAttr: function(targetData) {
48234         var target = this.target,
48235             ln = targetData.length,
48236             attrs, attr, o, i, j, ln2, element, value;
48237         for (i = 0; i < ln; i++) {
48238             attrs = targetData[i].attrs;
48239             for (attr in attrs) {
48240                 if (attrs.hasOwnProperty(attr)) {
48241                     ln2 = attrs[attr].length;
48242                     for (j = 0; j < ln2; j++) {
48243                         o = attrs[attr][j];
48244                         element = o[0];
48245                         value = o[1];
48246                         if (attr === 'x') {
48247                             element.setX(value);
48248                         }
48249                         else if (attr === 'y') {
48250                             element.setY(value);
48251                         }
48252                         else if (attr === 'scrollTop') {
48253                             element.scrollTo('top', value);
48254                         }
48255                         else if (attr === 'scrollLeft') {
48256                             element.scrollTo('left',value);
48257                         }
48258                         else {
48259                             element.setStyle(attr, value);
48260                         }
48261                     }
48262                 }
48263             }
48264         }
48265     }
48266 });
48267
48268 /**
48269  * @class Ext.fx.target.CompositeElement
48270  * @extends Ext.fx.target.Element
48271  * 
48272  * This class represents a animation target for a {@link Ext.CompositeElement}. It allows
48273  * each {@link Ext.core.Element} in the group to be animated as a whole. In general this class will not be
48274  * created directly, the {@link Ext.CompositeElement} will be passed to the animation and
48275  * and the appropriate target will be created.
48276  */
48277 Ext.define('Ext.fx.target.CompositeElement', {
48278
48279     /* Begin Definitions */
48280
48281     extend: 'Ext.fx.target.Element',
48282
48283     /* End Definitions */
48284
48285     isComposite: true,
48286     
48287     constructor: function(target) {
48288         target.id = target.id || Ext.id(null, 'ext-composite-');
48289         this.callParent([target]);
48290     },
48291
48292     getAttr: function(attr, val) {
48293         var out = [],
48294             target = this.target;
48295         target.each(function(el) {
48296             out.push([el, this.getElVal(el, attr, val)]);
48297         }, this);
48298         return out;
48299     }
48300 });
48301
48302 /**
48303  * @class Ext.fx.Manager
48304  * Animation Manager which keeps track of all current animations and manages them on a frame by frame basis.
48305  * @private
48306  * @singleton
48307  */
48308
48309 Ext.define('Ext.fx.Manager', {
48310
48311     /* Begin Definitions */
48312
48313     singleton: true,
48314
48315     requires: ['Ext.util.MixedCollection',
48316                'Ext.fx.target.Element',
48317                'Ext.fx.target.CompositeElement',
48318                'Ext.fx.target.Sprite',
48319                'Ext.fx.target.CompositeSprite',
48320                'Ext.fx.target.Component'],
48321
48322     mixins: {
48323         queue: 'Ext.fx.Queue'
48324     },
48325
48326     /* End Definitions */
48327
48328     constructor: function() {
48329         this.items = Ext.create('Ext.util.MixedCollection');
48330         this.mixins.queue.constructor.call(this);
48331
48332         // this.requestAnimFrame = (function() {
48333         //     var raf = window.requestAnimationFrame ||
48334         //               window.webkitRequestAnimationFrame ||
48335         //               window.mozRequestAnimationFrame ||
48336         //               window.oRequestAnimationFrame ||
48337         //               window.msRequestAnimationFrame;
48338         //     if (raf) {
48339         //         return function(callback, element) {
48340         //             raf(callback);
48341         //         };
48342         //     }
48343         //     else {
48344         //         return function(callback, element) {
48345         //             window.setTimeout(callback, Ext.fx.Manager.interval);
48346         //         };
48347         //     }
48348         // })();
48349     },
48350
48351     /**
48352      * @cfg {Number} interval Default interval in miliseconds to calculate each frame.  Defaults to 16ms (~60fps)
48353      */
48354     interval: 16,
48355
48356     /**
48357      * @cfg {Boolean} forceJS Turn off to not use CSS3 transitions when they are available
48358      */
48359     forceJS: true,
48360
48361     // @private Target factory
48362     createTarget: function(target) {
48363         var me = this,
48364             useCSS3 = !me.forceJS && Ext.supports.Transitions,
48365             targetObj;
48366
48367         me.useCSS3 = useCSS3;
48368
48369         // dom id
48370         if (Ext.isString(target)) {
48371             target = Ext.get(target);
48372         }
48373         // dom element
48374         if (target && target.tagName) {
48375             target = Ext.get(target);
48376             targetObj = Ext.create('Ext.fx.target.' + 'Element' + (useCSS3 ? 'CSS' : ''), target);
48377             me.targets.add(targetObj);
48378             return targetObj;
48379         }
48380         if (Ext.isObject(target)) {
48381             // Element
48382             if (target.dom) {
48383                 targetObj = Ext.create('Ext.fx.target.' + 'Element' + (useCSS3 ? 'CSS' : ''), target);
48384             }
48385             // Element Composite
48386             else if (target.isComposite) {
48387                 targetObj = Ext.create('Ext.fx.target.' + 'CompositeElement' + (useCSS3 ? 'CSS' : ''), target);
48388             }
48389             // Draw Sprite
48390             else if (target.isSprite) {
48391                 targetObj = Ext.create('Ext.fx.target.Sprite', target);
48392             }
48393             // Draw Sprite Composite
48394             else if (target.isCompositeSprite) {
48395                 targetObj = Ext.create('Ext.fx.target.CompositeSprite', target);
48396             }
48397             // Component
48398             else if (target.isComponent) {
48399                 targetObj = Ext.create('Ext.fx.target.Component', target);
48400             }
48401             else if (target.isAnimTarget) {
48402                 return target;
48403             }
48404             else {
48405                 return null;
48406             }
48407             me.targets.add(targetObj);
48408             return targetObj;
48409         }
48410         else {
48411             return null;
48412         }
48413     },
48414
48415     /**
48416      * Add an Anim to the manager. This is done automatically when an Anim instance is created.
48417      * @param {Ext.fx.Anim} anim
48418      */
48419     addAnim: function(anim) {
48420         var items = this.items,
48421             task = this.task;
48422         // var me = this,
48423         //     items = me.items,
48424         //     cb = function() {
48425         //         if (items.length) {
48426         //             me.task = true;
48427         //             me.runner();
48428         //             me.requestAnimFrame(cb);
48429         //         }
48430         //         else {
48431         //             me.task = false;
48432         //         }
48433         //     };
48434
48435         items.add(anim);
48436
48437         // Start the timer if not already running
48438         if (!task && items.length) {
48439             task = this.task = {
48440                 run: this.runner,
48441                 interval: this.interval,
48442                 scope: this
48443             };
48444             Ext.TaskManager.start(task);
48445         }
48446
48447         // //Start the timer if not already running
48448         // if (!me.task && items.length) {
48449         //     me.requestAnimFrame(cb);
48450         // }
48451     },
48452
48453     /**
48454      * Remove an Anim from the manager. This is done automatically when an Anim ends.
48455      * @param {Ext.fx.Anim} anim
48456      */
48457     removeAnim: function(anim) {
48458         // this.items.remove(anim);
48459         var items = this.items,
48460             task = this.task;
48461         items.remove(anim);
48462         // Stop the timer if there are no more managed Anims
48463         if (task && !items.length) {
48464             Ext.TaskManager.stop(task);
48465             delete this.task;
48466         }
48467     },
48468
48469     /**
48470      * @private
48471      * Filter function to determine which animations need to be started
48472      */
48473     startingFilter: function(o) {
48474         return o.paused === false && o.running === false && o.iterations > 0;
48475     },
48476
48477     /**
48478      * @private
48479      * Filter function to determine which animations are still running
48480      */
48481     runningFilter: function(o) {
48482         return o.paused === false && o.running === true && o.isAnimator !== true;
48483     },
48484
48485     /**
48486      * @private
48487      * Runner function being called each frame
48488      */
48489     runner: function() {
48490         var me = this,
48491             items = me.items;
48492
48493         me.targetData = {};
48494         me.targetArr = {};
48495
48496         // Single timestamp for all animations this interval
48497         me.timestamp = new Date();
48498
48499         // Start any items not current running
48500         items.filterBy(me.startingFilter).each(me.startAnim, me);
48501
48502         // Build the new attributes to be applied for all targets in this frame
48503         items.filterBy(me.runningFilter).each(me.runAnim, me);
48504
48505         // Apply all the pending changes to their targets
48506         me.applyPendingAttrs();
48507     },
48508
48509     /**
48510      * @private
48511      * Start the individual animation (initialization)
48512      */
48513     startAnim: function(anim) {
48514         anim.start(this.timestamp);
48515     },
48516
48517     /**
48518      * @private
48519      * Run the individual animation for this frame
48520      */
48521     runAnim: function(anim) {
48522         if (!anim) {
48523             return;
48524         }
48525         var me = this,
48526             targetId = anim.target.getId(),
48527             useCSS3 = me.useCSS3 && anim.target.type == 'element',
48528             elapsedTime = me.timestamp - anim.startTime,
48529             target, o;
48530
48531         this.collectTargetData(anim, elapsedTime, useCSS3);
48532
48533         // For CSS3 animation, we need to immediately set the first frame's attributes without any transition
48534         // to get a good initial state, then add the transition properties and set the final attributes.
48535         if (useCSS3) {
48536             // Flush the collected attributes, without transition
48537             anim.target.setAttr(me.targetData[targetId], true);
48538
48539             // Add the end frame data
48540             me.targetData[targetId] = [];
48541             me.collectTargetData(anim, anim.duration, useCSS3);
48542
48543             // Pause the animation so runAnim doesn't keep getting called
48544             anim.paused = true;
48545
48546             target = anim.target.target;
48547             // We only want to attach an event on the last element in a composite
48548             if (anim.target.isComposite) {
48549                 target = anim.target.target.last();
48550             }
48551
48552             // Listen for the transitionend event
48553             o = {};
48554             o[Ext.supports.CSS3TransitionEnd] = anim.lastFrame;
48555             o.scope = anim;
48556             o.single = true;
48557             target.on(o);
48558         }
48559         // For JS animation, trigger the lastFrame handler if this is the final frame
48560         else if (elapsedTime >= anim.duration) {
48561             me.applyPendingAttrs(true);
48562             delete me.targetData[targetId];
48563             delete me.targetArr[targetId];
48564             anim.lastFrame();
48565         }
48566     },
48567
48568     /**
48569      * Collect target attributes for the given Anim object at the given timestamp
48570      * @param {Ext.fx.Anim} anim The Anim instance
48571      * @param {Number} timestamp Time after the anim's start time
48572      */
48573     collectTargetData: function(anim, elapsedTime, useCSS3) {
48574         var targetId = anim.target.getId(),
48575             targetData = this.targetData[targetId],
48576             data;
48577         
48578         if (!targetData) {
48579             targetData = this.targetData[targetId] = [];
48580             this.targetArr[targetId] = anim.target;
48581         }
48582
48583         data = {
48584             duration: anim.duration,
48585             easing: (useCSS3 && anim.reverse) ? anim.easingFn.reverse().toCSS3() : anim.easing,
48586             attrs: {}
48587         };
48588         Ext.apply(data.attrs, anim.runAnim(elapsedTime));
48589         targetData.push(data);
48590     },
48591
48592     /**
48593      * @private
48594      * Apply all pending attribute changes to their targets
48595      */
48596     applyPendingAttrs: function(isLastFrame) {
48597         var targetData = this.targetData,
48598             targetArr = this.targetArr,
48599             targetId;
48600         for (targetId in targetData) {
48601             if (targetData.hasOwnProperty(targetId)) {
48602                 targetArr[targetId].setAttr(targetData[targetId], false, isLastFrame);
48603             }
48604         }
48605     }
48606 });
48607
48608 /**
48609  * @class Ext.fx.Animator
48610  * Animation instance
48611
48612 This class is used to run keyframe based animations, which follows the CSS3 based animation structure. 
48613 Keyframe animations differ from typical from/to animations in that they offer the ability to specify values 
48614 at various points throughout the animation.
48615
48616 __Using Keyframes__
48617 The {@link #keyframes} option is the most important part of specifying an animation when using this 
48618 class. A key frame is a point in a particular animation. We represent this as a percentage of the
48619 total animation duration. At each key frame, we can specify the target values at that time. Note that
48620 you *must* specify the values at 0% and 100%, the start and ending values. There is also a {@link keyframe}
48621 event that fires after each key frame is reached.
48622
48623 __Example Usage__
48624 In the example below, we modify the values of the element at each fifth throughout the animation.
48625
48626     Ext.create('Ext.fx.Animator', {
48627         target: Ext.getBody().createChild({
48628             style: {
48629                 width: '100px',
48630                 height: '100px',
48631                 'background-color': 'red'
48632             }
48633         }),
48634         duration: 10000, // 10 seconds
48635         keyframes: {
48636             0: {
48637                 opacity: 1,
48638                 backgroundColor: 'FF0000'
48639             },
48640             20: {
48641                 x: 30,
48642                 opacity: 0.5    
48643             },
48644             40: {
48645                 x: 130,
48646                 backgroundColor: '0000FF'    
48647             },
48648             60: {
48649                 y: 80,
48650                 opacity: 0.3    
48651             },
48652             80: {
48653                 width: 200,
48654                 y: 200    
48655             },
48656             100: {
48657                 opacity: 1,
48658                 backgroundColor: '00FF00'
48659             }
48660         }
48661     });
48662
48663  * @markdown
48664  */
48665 Ext.define('Ext.fx.Animator', {
48666
48667     /* Begin Definitions */
48668
48669     mixins: {
48670         observable: 'Ext.util.Observable'
48671     },
48672
48673     requires: ['Ext.fx.Manager'],
48674
48675     /* End Definitions */
48676
48677     isAnimator: true,
48678
48679     /**
48680      * @cfg {Number} duration
48681      * Time in milliseconds for the animation to last. Defaults to 250.
48682      */
48683     duration: 250,
48684
48685     /**
48686      * @cfg {Number} delay
48687      * Time to delay before starting the animation. Defaults to 0.
48688      */
48689     delay: 0,
48690
48691     /* private used to track a delayed starting time */
48692     delayStart: 0,
48693
48694     /**
48695      * @cfg {Boolean} dynamic
48696      * Currently only for Component Animation: Only set a component's outer element size bypassing layouts.  Set to true to do full layouts for every frame of the animation.  Defaults to false.
48697      */
48698     dynamic: false,
48699
48700     /**
48701      * @cfg {String} easing
48702
48703 This describes how the intermediate values used during a transition will be calculated. It allows for a transition to change
48704 speed over its duration. 
48705
48706 - backIn
48707 - backOut
48708 - bounceIn
48709 - bounceOut
48710 - ease
48711 - easeIn
48712 - easeOut
48713 - easeInOut
48714 - elasticIn
48715 - elasticOut
48716 - cubic-bezier(x1, y1, x2, y2)
48717
48718 Note that cubic-bezier will create a custom easing curve following the CSS3 transition-timing-function specification `{@link http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag}`. The four values specify points P1 and P2 of the curve
48719 as (x1, y1, x2, y2). All values must be in the range [0, 1] or the definition is invalid.
48720
48721      * @markdown
48722      */
48723     easing: 'ease',
48724
48725     /**
48726      * Flag to determine if the animation has started
48727      * @property running
48728      * @type boolean
48729      */
48730     running: false,
48731
48732     /**
48733      * Flag to determine if the animation is paused. Only set this to true if you need to
48734      * keep the Anim instance around to be unpaused later; otherwise call {@link #end}.
48735      * @property paused
48736      * @type boolean
48737      */
48738     paused: false,
48739
48740     /**
48741      * @private
48742      */
48743     damper: 1,
48744
48745     /**
48746      * @cfg {Number} iterations
48747      * Number of times to execute the animation. Defaults to 1.
48748      */
48749     iterations: 1,
48750
48751     /**
48752      * Current iteration the animation is running.
48753      * @property currentIteration
48754      * @type int
48755      */
48756     currentIteration: 0,
48757
48758     /**
48759      * Current keyframe step of the animation.
48760      * @property keyframeStep
48761      * @type Number
48762      */
48763     keyframeStep: 0,
48764
48765     /**
48766      * @private
48767      */
48768     animKeyFramesRE: /^(from|to|\d+%?)$/,
48769
48770     /**
48771      * @cfg {Ext.fx.target} target
48772      * The Ext.fx.target to apply the animation to.  If not specified during initialization, this can be passed to the applyAnimator
48773      * method to apply the same animation to many targets.
48774      */
48775
48776      /**
48777       * @cfg {Object} keyframes
48778       * Animation keyframes follow the CSS3 Animation configuration pattern. 'from' is always considered '0%' and 'to'
48779       * is considered '100%'.<b>Every keyframe declaration must have a keyframe rule for 0% and 100%, possibly defined using
48780       * "from" or "to"</b>.  A keyframe declaration without these keyframe selectors is invalid and will not be available for
48781       * animation.  The keyframe declaration for a keyframe rule consists of properties and values. Properties that are unable to
48782       * be animated are ignored in these rules, with the exception of 'easing' which can be changed at each keyframe. For example:
48783  <pre><code>
48784 keyframes : {
48785     '0%': {
48786         left: 100
48787     },
48788     '40%': {
48789         left: 150
48790     },
48791     '60%': {
48792         left: 75
48793     },
48794     '100%': {
48795         left: 100
48796     }
48797 }
48798  </code></pre>
48799       */
48800     constructor: function(config) {
48801         var me = this;
48802         config = Ext.apply(me, config || {});
48803         me.config = config;
48804         me.id = Ext.id(null, 'ext-animator-');
48805         me.addEvents(
48806             /**
48807              * @event beforeanimate
48808              * Fires before the animation starts. A handler can return false to cancel the animation.
48809              * @param {Ext.fx.Animator} this
48810              */
48811             'beforeanimate',
48812             /**
48813               * @event keyframe
48814               * Fires at each keyframe.
48815               * @param {Ext.fx.Animator} this
48816               * @param {Number} keyframe step number
48817               */
48818             'keyframe',
48819             /**
48820              * @event afteranimate
48821              * Fires when the animation is complete.
48822              * @param {Ext.fx.Animator} this
48823              * @param {Date} startTime
48824              */
48825             'afteranimate'
48826         );
48827         me.mixins.observable.constructor.call(me, config);
48828         me.timeline = [];
48829         me.createTimeline(me.keyframes);
48830         if (me.target) {
48831             me.applyAnimator(me.target);
48832             Ext.fx.Manager.addAnim(me);
48833         }
48834     },
48835
48836     /**
48837      * @private
48838      */
48839     sorter: function (a, b) {
48840         return a.pct - b.pct;
48841     },
48842
48843     /**
48844      * @private
48845      * Takes the given keyframe configuration object and converts it into an ordered array with the passed attributes per keyframe
48846      * or applying the 'to' configuration to all keyframes.  Also calculates the proper animation duration per keyframe.
48847      */
48848     createTimeline: function(keyframes) {
48849         var me = this,
48850             attrs = [],
48851             to = me.to || {},
48852             duration = me.duration,
48853             prevMs, ms, i, ln, pct, anim, nextAnim, attr;
48854
48855         for (pct in keyframes) {
48856             if (keyframes.hasOwnProperty(pct) && me.animKeyFramesRE.test(pct)) {
48857                 attr = {attrs: Ext.apply(keyframes[pct], to)};
48858                 // CSS3 spec allow for from/to to be specified.
48859                 if (pct == "from") {
48860                     pct = 0;
48861                 }
48862                 else if (pct == "to") {
48863                     pct = 100;
48864                 }
48865                 // convert % values into integers
48866                 attr.pct = parseInt(pct, 10);
48867                 attrs.push(attr);
48868             }
48869         }
48870         // Sort by pct property
48871         Ext.Array.sort(attrs, me.sorter);
48872         // Only an end
48873         //if (attrs[0].pct) {
48874         //    attrs.unshift({pct: 0, attrs: element.attrs});
48875         //}
48876
48877         ln = attrs.length;
48878         for (i = 0; i < ln; i++) {
48879             prevMs = (attrs[i - 1]) ? duration * (attrs[i - 1].pct / 100) : 0;
48880             ms = duration * (attrs[i].pct / 100);
48881             me.timeline.push({
48882                 duration: ms - prevMs,
48883                 attrs: attrs[i].attrs
48884             });
48885         }
48886     },
48887
48888     /**
48889      * Applies animation to the Ext.fx.target
48890      * @private
48891      * @param target
48892      * @type string/object
48893      */
48894     applyAnimator: function(target) {
48895         var me = this,
48896             anims = [],
48897             timeline = me.timeline,
48898             reverse = me.reverse,
48899             ln = timeline.length,
48900             anim, easing, damper, initial, attrs, lastAttrs, i;
48901
48902         if (me.fireEvent('beforeanimate', me) !== false) {
48903             for (i = 0; i < ln; i++) {
48904                 anim = timeline[i];
48905                 attrs = anim.attrs;
48906                 easing = attrs.easing || me.easing;
48907                 damper = attrs.damper || me.damper;
48908                 delete attrs.easing;
48909                 delete attrs.damper;
48910                 anim = Ext.create('Ext.fx.Anim', {
48911                     target: target,
48912                     easing: easing,
48913                     damper: damper,
48914                     duration: anim.duration,
48915                     paused: true,
48916                     to: attrs
48917                 });
48918                 anims.push(anim);
48919             }
48920             me.animations = anims;
48921             me.target = anim.target;
48922             for (i = 0; i < ln - 1; i++) {
48923                 anim = anims[i];
48924                 anim.nextAnim = anims[i + 1];
48925                 anim.on('afteranimate', function() {
48926                     this.nextAnim.paused = false;
48927                 });
48928                 anim.on('afteranimate', function() {
48929                     this.fireEvent('keyframe', this, ++this.keyframeStep);
48930                 }, me);
48931             }
48932             anims[ln - 1].on('afteranimate', function() {
48933                 this.lastFrame();
48934             }, me);
48935         }
48936     },
48937
48938     /*
48939      * @private
48940      * Fires beforeanimate and sets the running flag.
48941      */
48942     start: function(startTime) {
48943         var me = this,
48944             delay = me.delay,
48945             delayStart = me.delayStart,
48946             delayDelta;
48947         if (delay) {
48948             if (!delayStart) {
48949                 me.delayStart = startTime;
48950                 return;
48951             }
48952             else {
48953                 delayDelta = startTime - delayStart;
48954                 if (delayDelta < delay) {
48955                     return;
48956                 }
48957                 else {
48958                     // Compensate for frame delay;
48959                     startTime = new Date(delayStart.getTime() + delay);
48960                 }
48961             }
48962         }
48963         if (me.fireEvent('beforeanimate', me) !== false) {
48964             me.startTime = startTime;
48965             me.running = true;
48966             me.animations[me.keyframeStep].paused = false;
48967         }
48968     },
48969
48970     /*
48971      * @private
48972      * Perform lastFrame cleanup and handle iterations
48973      * @returns a hash of the new attributes.
48974      */
48975     lastFrame: function() {
48976         var me = this,
48977             iter = me.iterations,
48978             iterCount = me.currentIteration;
48979
48980         iterCount++;
48981         if (iterCount < iter) {
48982             me.startTime = new Date();
48983             me.currentIteration = iterCount;
48984             me.keyframeStep = 0;
48985             me.applyAnimator(me.target);
48986             me.animations[me.keyframeStep].paused = false;
48987         }
48988         else {
48989             me.currentIteration = 0;
48990             me.end();
48991         }
48992     },
48993
48994     /*
48995      * Fire afteranimate event and end the animation. Usually called automatically when the
48996      * animation reaches its final frame, but can also be called manually to pre-emptively
48997      * stop and destroy the running animation.
48998      */
48999     end: function() {
49000         var me = this;
49001         me.fireEvent('afteranimate', me, me.startTime, new Date() - me.startTime);
49002     }
49003 });
49004 /**
49005  * @class Ext.fx.Easing
49006  * 
49007 This class contains a series of function definitions used to modify values during an animation.
49008 They describe how the intermediate values used during a transition will be calculated. It allows for a transition to change
49009 speed over its duration. The following options are available: 
49010
49011 - linear The default easing type
49012 - backIn
49013 - backOut
49014 - bounceIn
49015 - bounceOut
49016 - ease
49017 - easeIn
49018 - easeOut
49019 - easeInOut
49020 - elasticIn
49021 - elasticOut
49022 - cubic-bezier(x1, y1, x2, y2)
49023
49024 Note that cubic-bezier will create a custom easing curve following the CSS3 transition-timing-function specification `{@link http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag}`. The four values specify points P1 and P2 of the curve
49025 as (x1, y1, x2, y2). All values must be in the range [0, 1] or the definition is invalid.
49026  * @markdown
49027  * @singleton
49028  */
49029 Ext.ns('Ext.fx');
49030
49031 Ext.require('Ext.fx.CubicBezier', function() {
49032     var math = Math,
49033         pi = math.PI,
49034         pow = math.pow,
49035         sin = math.sin,
49036         sqrt = math.sqrt,
49037         abs = math.abs,
49038         backInSeed = 1.70158;
49039     Ext.fx.Easing = {
49040         // ease: Ext.fx.CubicBezier.cubicBezier(0.25, 0.1, 0.25, 1),
49041         // linear: Ext.fx.CubicBezier.cubicBezier(0, 0, 1, 1),
49042         // 'ease-in': Ext.fx.CubicBezier.cubicBezier(0.42, 0, 1, 1),
49043         // 'ease-out': Ext.fx.CubicBezier.cubicBezier(0, 0.58, 1, 1),
49044         // 'ease-in-out': Ext.fx.CubicBezier.cubicBezier(0.42, 0, 0.58, 1),
49045         // 'easeIn': Ext.fx.CubicBezier.cubicBezier(0.42, 0, 1, 1),
49046         // 'easeOut': Ext.fx.CubicBezier.cubicBezier(0, 0.58, 1, 1),
49047         // 'easeInOut': Ext.fx.CubicBezier.cubicBezier(0.42, 0, 0.58, 1)
49048     };
49049
49050     Ext.apply(Ext.fx.Easing, {
49051         linear: function(n) {
49052             return n;
49053         },
49054         ease: function(n) {
49055             var q = 0.07813 - n / 2,
49056                 alpha = -0.25,
49057                 Q = sqrt(0.0066 + q * q),
49058                 x = Q - q,
49059                 X = pow(abs(x), 1/3) * (x < 0 ? -1 : 1),
49060                 y = -Q - q,
49061                 Y = pow(abs(y), 1/3) * (y < 0 ? -1 : 1),
49062                 t = X + Y + 0.25;
49063             return pow(1 - t, 2) * 3 * t * 0.1 + (1 - t) * 3 * t * t + t * t * t;
49064         },
49065         easeIn: function (n) {
49066             return pow(n, 1.7);
49067         },
49068         easeOut: function (n) {
49069             return pow(n, 0.48);
49070         },
49071         easeInOut: function(n) {
49072             var q = 0.48 - n / 1.04,
49073                 Q = sqrt(0.1734 + q * q),
49074                 x = Q - q,
49075                 X = pow(abs(x), 1/3) * (x < 0 ? -1 : 1),
49076                 y = -Q - q,
49077                 Y = pow(abs(y), 1/3) * (y < 0 ? -1 : 1),
49078                 t = X + Y + 0.5;
49079             return (1 - t) * 3 * t * t + t * t * t;
49080         },
49081         backIn: function (n) {
49082             return n * n * ((backInSeed + 1) * n - backInSeed);
49083         },
49084         backOut: function (n) {
49085             n = n - 1;
49086             return n * n * ((backInSeed + 1) * n + backInSeed) + 1;
49087         },
49088         elasticIn: function (n) {
49089             if (n === 0 || n === 1) {
49090                 return n;
49091             }
49092             var p = 0.3,
49093                 s = p / 4;
49094             return pow(2, -10 * n) * sin((n - s) * (2 * pi) / p) + 1;
49095         },
49096         elasticOut: function (n) {
49097             return 1 - Ext.fx.Easing.elasticIn(1 - n);
49098         },
49099         bounceIn: function (n) {
49100             return 1 - Ext.fx.Easing.bounceOut(1 - n);
49101         },
49102         bounceOut: function (n) {
49103             var s = 7.5625,
49104                 p = 2.75,
49105                 l;
49106             if (n < (1 / p)) {
49107                 l = s * n * n;
49108             } else {
49109                 if (n < (2 / p)) {
49110                     n -= (1.5 / p);
49111                     l = s * n * n + 0.75;
49112                 } else {
49113                     if (n < (2.5 / p)) {
49114                         n -= (2.25 / p);
49115                         l = s * n * n + 0.9375;
49116                     } else {
49117                         n -= (2.625 / p);
49118                         l = s * n * n + 0.984375;
49119                     }
49120                 }
49121             }
49122             return l;
49123         }
49124     });
49125     Ext.apply(Ext.fx.Easing, {
49126         'back-in': Ext.fx.Easing.backIn,
49127         'back-out': Ext.fx.Easing.backOut,
49128         'ease-in': Ext.fx.Easing.easeIn,
49129         'ease-out': Ext.fx.Easing.easeOut,
49130         'elastic-in': Ext.fx.Easing.elasticIn,
49131         'elastic-out': Ext.fx.Easing.elasticIn,
49132         'bounce-in': Ext.fx.Easing.bounceIn,
49133         'bounce-out': Ext.fx.Easing.bounceOut,
49134         'ease-in-out': Ext.fx.Easing.easeInOut
49135     });
49136 });
49137 /*
49138  * @class Ext.draw.Draw
49139  * Base Drawing class.  Provides base drawing functions.
49140  */
49141
49142 Ext.define('Ext.draw.Draw', {
49143     /* Begin Definitions */
49144
49145     singleton: true,
49146
49147     requires: ['Ext.draw.Color'],
49148
49149     /* End Definitions */
49150
49151     pathToStringRE: /,?([achlmqrstvxz]),?/gi,
49152     pathCommandRE: /([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?\s*,?\s*)+)/ig,
49153     pathValuesRE: /(-?\d*\.?\d*(?:e[-+]?\d+)?)\s*,?\s*/ig,
49154     stopsRE: /^(\d+%?)$/,
49155     radian: Math.PI / 180,
49156
49157     availableAnimAttrs: {
49158         along: "along",
49159         blur: null,
49160         "clip-rect": "csv",
49161         cx: null,
49162         cy: null,
49163         fill: "color",
49164         "fill-opacity": null,
49165         "font-size": null,
49166         height: null,
49167         opacity: null,
49168         path: "path",
49169         r: null,
49170         rotation: "csv",
49171         rx: null,
49172         ry: null,
49173         scale: "csv",
49174         stroke: "color",
49175         "stroke-opacity": null,
49176         "stroke-width": null,
49177         translation: "csv",
49178         width: null,
49179         x: null,
49180         y: null
49181     },
49182
49183     is: function(o, type) {
49184         type = String(type).toLowerCase();
49185         return (type == "object" && o === Object(o)) ||
49186             (type == "undefined" && typeof o == type) ||
49187             (type == "null" && o === null) ||
49188             (type == "array" && Array.isArray && Array.isArray(o)) ||
49189             (Object.prototype.toString.call(o).toLowerCase().slice(8, -1)) == type;
49190     },
49191
49192     ellipsePath: function(sprite) {
49193         var attr = sprite.attr;
49194         return Ext.String.format("M{0},{1}A{2},{3},0,1,1,{0},{4}A{2},{3},0,1,1,{0},{1}z", attr.x, attr.y - attr.ry, attr.rx, attr.ry, attr.y + attr.ry);
49195     },
49196
49197     rectPath: function(sprite) {
49198         var attr = sprite.attr;
49199         if (attr.radius) {
49200             return Ext.String.format("M{0},{1}l{2},0a{3},{3},0,0,1,{3},{3}l0,{5}a{3},{3},0,0,1,{4},{3}l{6},0a{3},{3},0,0,1,{4},{4}l0,{7}a{3},{3},0,0,1,{3},{4}z", attr.x + attr.radius, attr.y, attr.width - attr.radius * 2, attr.radius, -attr.radius, attr.height - attr.radius * 2, attr.radius * 2 - attr.width, attr.radius * 2 - attr.height);
49201         }
49202         else {
49203             return Ext.String.format("M{0},{1}l{2},0,0,{3},{4},0z", attr.x, attr.y, attr.width, attr.height, -attr.width);
49204         }
49205     },
49206
49207     path2string: function () {
49208         return this.join(",").replace(Ext.draw.Draw.pathToStringRE, "$1");
49209     },
49210
49211     parsePathString: function (pathString) {
49212         if (!pathString) {
49213             return null;
49214         }
49215         var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0},
49216             data = [],
49217             me = this;
49218         if (me.is(pathString, "array") && me.is(pathString[0], "array")) { // rough assumption
49219             data = me.pathClone(pathString);
49220         }
49221         if (!data.length) {
49222             String(pathString).replace(me.pathCommandRE, function (a, b, c) {
49223                 var params = [],
49224                     name = b.toLowerCase();
49225                 c.replace(me.pathValuesRE, function (a, b) {
49226                     b && params.push(+b);
49227                 });
49228                 if (name == "m" && params.length > 2) {
49229                     data.push([b].concat(params.splice(0, 2)));
49230                     name = "l";
49231                     b = (b == "m") ? "l" : "L";
49232                 }
49233                 while (params.length >= paramCounts[name]) {
49234                     data.push([b].concat(params.splice(0, paramCounts[name])));
49235                     if (!paramCounts[name]) {
49236                         break;
49237                     }
49238                 }
49239             });
49240         }
49241         data.toString = me.path2string;
49242         return data;
49243     },
49244
49245     mapPath: function (path, matrix) {
49246         if (!matrix) {
49247             return path;
49248         }
49249         var x, y, i, ii, j, jj, pathi;
49250         path = this.path2curve(path);
49251         for (i = 0, ii = path.length; i < ii; i++) {
49252             pathi = path[i];
49253             for (j = 1, jj = pathi.length; j < jj-1; j += 2) {
49254                 x = matrix.x(pathi[j], pathi[j + 1]);
49255                 y = matrix.y(pathi[j], pathi[j + 1]);
49256                 pathi[j] = x;
49257                 pathi[j + 1] = y;
49258             }
49259         }
49260         return path;
49261     },
49262
49263     pathClone: function(pathArray) {
49264         var res = [],
49265             j,
49266             jj,
49267             i,
49268             ii;
49269         if (!this.is(pathArray, "array") || !this.is(pathArray && pathArray[0], "array")) { // rough assumption
49270             pathArray = this.parsePathString(pathArray);
49271         }
49272         for (i = 0, ii = pathArray.length; i < ii; i++) {
49273             res[i] = [];
49274             for (j = 0, jj = pathArray[i].length; j < jj; j++) {
49275                 res[i][j] = pathArray[i][j];
49276             }
49277         }
49278         res.toString = this.path2string;
49279         return res;
49280     },
49281
49282     pathToAbsolute: function (pathArray) {
49283         if (!this.is(pathArray, "array") || !this.is(pathArray && pathArray[0], "array")) { // rough assumption
49284             pathArray = this.parsePathString(pathArray);
49285         }
49286         var res = [],
49287             x = 0,
49288             y = 0,
49289             mx = 0,
49290             my = 0,
49291             start = 0,
49292             i,
49293             ii,
49294             r,
49295             pa,
49296             j,
49297             jj,
49298             k,
49299             kk;
49300         if (pathArray[0][0] == "M") {
49301             x = +pathArray[0][1];
49302             y = +pathArray[0][2];
49303             mx = x;
49304             my = y;
49305             start++;
49306             res[0] = ["M", x, y];
49307         }
49308         for (i = start, ii = pathArray.length; i < ii; i++) {
49309             r = res[i] = [];
49310             pa = pathArray[i];
49311             if (pa[0] != pa[0].toUpperCase()) {
49312                 r[0] = pa[0].toUpperCase();
49313                 switch (r[0]) {
49314                     case "A":
49315                         r[1] = pa[1];
49316                         r[2] = pa[2];
49317                         r[3] = pa[3];
49318                         r[4] = pa[4];
49319                         r[5] = pa[5];
49320                         r[6] = +(pa[6] + x);
49321                         r[7] = +(pa[7] + y);
49322                         break;
49323                     case "V":
49324                         r[1] = +pa[1] + y;
49325                         break;
49326                     case "H":
49327                         r[1] = +pa[1] + x;
49328                         break;
49329                     case "M":
49330                         mx = +pa[1] + x;
49331                         my = +pa[2] + y;
49332                     default:
49333                         for (j = 1, jj = pa.length; j < jj; j++) {
49334                             r[j] = +pa[j] + ((j % 2) ? x : y);
49335                         }
49336                 }
49337             } else {
49338                 for (k = 0, kk = pa.length; k < kk; k++) {
49339                     res[i][k] = pa[k];
49340                 }
49341             }
49342             switch (r[0]) {
49343                 case "Z":
49344                     x = mx;
49345                     y = my;
49346                     break;
49347                 case "H":
49348                     x = r[1];
49349                     break;
49350                 case "V":
49351                     y = r[1];
49352                     break;
49353                 case "M":
49354                     mx = res[i][res[i].length - 2];
49355                     my = res[i][res[i].length - 1];
49356                 default:
49357                     x = res[i][res[i].length - 2];
49358                     y = res[i][res[i].length - 1];
49359             }
49360         }
49361         res.toString = this.path2string;
49362         return res;
49363     },
49364
49365     pathToRelative: function (pathArray) {
49366         if (!this.is(pathArray, "array") || !this.is(pathArray && pathArray[0], "array")) {
49367             pathArray = this.parsePathString(pathArray);
49368         }
49369         var res = [],
49370             x = 0,
49371             y = 0,
49372             mx = 0,
49373             my = 0,
49374             start = 0;
49375         if (pathArray[0][0] == "M") {
49376             x = pathArray[0][1];
49377             y = pathArray[0][2];
49378             mx = x;
49379             my = y;
49380             start++;
49381             res.push(["M", x, y]);
49382         }
49383         for (var i = start, ii = pathArray.length; i < ii; i++) {
49384             var r = res[i] = [],
49385                 pa = pathArray[i];
49386             if (pa[0] != pa[0].toLowerCase()) {
49387                 r[0] = pa[0].toLowerCase();
49388                 switch (r[0]) {
49389                     case "a":
49390                         r[1] = pa[1];
49391                         r[2] = pa[2];
49392                         r[3] = pa[3];
49393                         r[4] = pa[4];
49394                         r[5] = pa[5];
49395                         r[6] = +(pa[6] - x).toFixed(3);
49396                         r[7] = +(pa[7] - y).toFixed(3);
49397                         break;
49398                     case "v":
49399                         r[1] = +(pa[1] - y).toFixed(3);
49400                         break;
49401                     case "m":
49402                         mx = pa[1];
49403                         my = pa[2];
49404                     default:
49405                         for (var j = 1, jj = pa.length; j < jj; j++) {
49406                             r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3);
49407                         }
49408                 }
49409             } else {
49410                 r = res[i] = [];
49411                 if (pa[0] == "m") {
49412                     mx = pa[1] + x;
49413                     my = pa[2] + y;
49414                 }
49415                 for (var k = 0, kk = pa.length; k < kk; k++) {
49416                     res[i][k] = pa[k];
49417                 }
49418             }
49419             var len = res[i].length;
49420             switch (res[i][0]) {
49421                 case "z":
49422                     x = mx;
49423                     y = my;
49424                     break;
49425                 case "h":
49426                     x += +res[i][len - 1];
49427                     break;
49428                 case "v":
49429                     y += +res[i][len - 1];
49430                     break;
49431                 default:
49432                     x += +res[i][len - 2];
49433                     y += +res[i][len - 1];
49434             }
49435         }
49436         res.toString = this.path2string;
49437         return res;
49438     },
49439
49440     //Returns a path converted to a set of curveto commands
49441     path2curve: function (path) {
49442         var me = this,
49443             points = me.pathToAbsolute(path),
49444             ln = points.length,
49445             attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
49446             i, seg, segLn, point;
49447             
49448         for (i = 0; i < ln; i++) {
49449             points[i] = me.command2curve(points[i], attrs);
49450             if (points[i].length > 7) {
49451                     points[i].shift();
49452                     point = points[i];
49453                     while (point.length) {
49454                         points.splice(i++, 0, ["C"].concat(point.splice(0, 6)));
49455                     }
49456                     points.splice(i, 1);
49457                     ln = points.length;
49458                 }
49459             seg = points[i];
49460             segLn = seg.length;
49461             attrs.x = seg[segLn - 2];
49462             attrs.y = seg[segLn - 1];
49463             attrs.bx = parseFloat(seg[segLn - 4]) || attrs.x;
49464             attrs.by = parseFloat(seg[segLn - 3]) || attrs.y;
49465         }
49466         return points;
49467     },
49468     
49469     interpolatePaths: function (path, path2) {
49470         var me = this,
49471             p = me.pathToAbsolute(path),
49472             p2 = me.pathToAbsolute(path2),
49473             attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
49474             attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null},
49475             fixArc = function (pp, i) {
49476                 if (pp[i].length > 7) {
49477                     pp[i].shift();
49478                     var pi = pp[i];
49479                     while (pi.length) {
49480                         pp.splice(i++, 0, ["C"].concat(pi.splice(0, 6)));
49481                     }
49482                     pp.splice(i, 1);
49483                     ii = Math.max(p.length, p2.length || 0);
49484                 }
49485             },
49486             fixM = function (path1, path2, a1, a2, i) {
49487                 if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
49488                     path2.splice(i, 0, ["M", a2.x, a2.y]);
49489                     a1.bx = 0;
49490                     a1.by = 0;
49491                     a1.x = path1[i][1];
49492                     a1.y = path1[i][2];
49493                     ii = Math.max(p.length, p2.length || 0);
49494                 }
49495             };
49496         for (var i = 0, ii = Math.max(p.length, p2.length || 0); i < ii; i++) {
49497             p[i] = me.command2curve(p[i], attrs);
49498             fixArc(p, i);
49499             (p2[i] = me.command2curve(p2[i], attrs2));
49500             fixArc(p2, i);
49501             fixM(p, p2, attrs, attrs2, i);
49502             fixM(p2, p, attrs2, attrs, i);
49503             var seg = p[i],
49504                 seg2 = p2[i],
49505                 seglen = seg.length,
49506                 seg2len = seg2.length;
49507             attrs.x = seg[seglen - 2];
49508             attrs.y = seg[seglen - 1];
49509             attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x;
49510             attrs.by = parseFloat(seg[seglen - 3]) || attrs.y;
49511             attrs2.bx = (parseFloat(seg2[seg2len - 4]) || attrs2.x);
49512             attrs2.by = (parseFloat(seg2[seg2len - 3]) || attrs2.y);
49513             attrs2.x = seg2[seg2len - 2];
49514             attrs2.y = seg2[seg2len - 1];
49515         }
49516         return [p, p2];
49517     },
49518     
49519     //Returns any path command as a curveto command based on the attrs passed
49520     command2curve: function (pathCommand, d) {
49521         var me = this;
49522         if (!pathCommand) {
49523             return ["C", d.x, d.y, d.x, d.y, d.x, d.y];
49524         }
49525         if (pathCommand[0] != "T" && pathCommand[0] != "Q") {
49526             d.qx = d.qy = null;
49527         }
49528         switch (pathCommand[0]) {
49529             case "M":
49530                 d.X = pathCommand[1];
49531                 d.Y = pathCommand[2];
49532                 break;
49533             case "A":
49534                 pathCommand = ["C"].concat(me.arc2curve.apply(me, [d.x, d.y].concat(pathCommand.slice(1))));
49535                 break;
49536             case "S":
49537                 pathCommand = ["C", d.x + (d.x - (d.bx || d.x)), d.y + (d.y - (d.by || d.y))].concat(pathCommand.slice(1));
49538                 break;
49539             case "T":
49540                 d.qx = d.x + (d.x - (d.qx || d.x));
49541                 d.qy = d.y + (d.y - (d.qy || d.y));
49542                 pathCommand = ["C"].concat(me.quadratic2curve(d.x, d.y, d.qx, d.qy, pathCommand[1], pathCommand[2]));
49543                 break;
49544             case "Q":
49545                 d.qx = pathCommand[1];
49546                 d.qy = pathCommand[2];
49547                 pathCommand = ["C"].concat(me.quadratic2curve(d.x, d.y, pathCommand[1], pathCommand[2], pathCommand[3], pathCommand[4]));
49548                 break;
49549             case "L":
49550                 pathCommand = ["C"].concat(d.x, d.y, pathCommand[1], pathCommand[2], pathCommand[1], pathCommand[2]);
49551                 break;
49552             case "H":
49553                 pathCommand = ["C"].concat(d.x, d.y, pathCommand[1], d.y, pathCommand[1], d.y);
49554                 break;
49555             case "V":
49556                 pathCommand = ["C"].concat(d.x, d.y, d.x, pathCommand[1], d.x, pathCommand[1]);
49557                 break;
49558             case "Z":
49559                 pathCommand = ["C"].concat(d.x, d.y, d.X, d.Y, d.X, d.Y);
49560                 break;
49561         }
49562         return pathCommand;
49563     },
49564
49565     quadratic2curve: function (x1, y1, ax, ay, x2, y2) {
49566         var _13 = 1 / 3,
49567             _23 = 2 / 3;
49568         return [
49569                 _13 * x1 + _23 * ax,
49570                 _13 * y1 + _23 * ay,
49571                 _13 * x2 + _23 * ax,
49572                 _13 * y2 + _23 * ay,
49573                 x2,
49574                 y2
49575             ];
49576     },
49577     
49578     rotate: function (x, y, rad) {
49579         var cos = Math.cos(rad),
49580             sin = Math.sin(rad),
49581             X = x * cos - y * sin,
49582             Y = x * sin + y * cos;
49583         return {x: X, y: Y};
49584     },
49585
49586     arc2curve: function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
49587         // for more information of where this Math came from visit:
49588         // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
49589         var me = this,
49590             PI = Math.PI,
49591             radian = me.radian,
49592             _120 = PI * 120 / 180,
49593             rad = radian * (+angle || 0),
49594             res = [],
49595             math = Math,
49596             mcos = math.cos,
49597             msin = math.sin,
49598             msqrt = math.sqrt,
49599             mabs = math.abs,
49600             masin = math.asin,
49601             xy, cos, sin, x, y, h, rx2, ry2, k, cx, cy, f1, f2, df, c1, s1, c2, s2,
49602             t, hx, hy, m1, m2, m3, m4, newres, i, ln, f2old, x2old, y2old;
49603         if (!recursive) {
49604             xy = me.rotate(x1, y1, -rad);
49605             x1 = xy.x;
49606             y1 = xy.y;
49607             xy = me.rotate(x2, y2, -rad);
49608             x2 = xy.x;
49609             y2 = xy.y;
49610             cos = mcos(radian * angle);
49611             sin = msin(radian * angle);
49612             x = (x1 - x2) / 2;
49613             y = (y1 - y2) / 2;
49614             h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
49615             if (h > 1) {
49616                 h = msqrt(h);
49617                 rx = h * rx;
49618                 ry = h * ry;
49619             }
49620             rx2 = rx * rx;
49621             ry2 = ry * ry;
49622             k = (large_arc_flag == sweep_flag ? -1 : 1) *
49623                     msqrt(mabs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)));
49624             cx = k * rx * y / ry + (x1 + x2) / 2;
49625             cy = k * -ry * x / rx + (y1 + y2) / 2;
49626             f1 = masin(((y1 - cy) / ry).toFixed(7));
49627             f2 = masin(((y2 - cy) / ry).toFixed(7));
49628
49629             f1 = x1 < cx ? PI - f1 : f1;
49630             f2 = x2 < cx ? PI - f2 : f2;
49631             if (f1 < 0) {
49632                 f1 = PI * 2 + f1;
49633             }
49634             if (f2 < 0) {
49635                 f2 = PI * 2 + f2;
49636             }
49637             if (sweep_flag && f1 > f2) {
49638                 f1 = f1 - PI * 2;
49639             }
49640             if (!sweep_flag && f2 > f1) {
49641                 f2 = f2 - PI * 2;
49642             }
49643         }
49644         else {
49645             f1 = recursive[0];
49646             f2 = recursive[1];
49647             cx = recursive[2];
49648             cy = recursive[3];
49649         }
49650         df = f2 - f1;
49651         if (mabs(df) > _120) {
49652             f2old = f2;
49653             x2old = x2;
49654             y2old = y2;
49655             f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
49656             x2 = cx + rx * mcos(f2);
49657             y2 = cy + ry * msin(f2);
49658             res = me.arc2curve(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
49659         }
49660         df = f2 - f1;
49661         c1 = mcos(f1);
49662         s1 = msin(f1);
49663         c2 = mcos(f2);
49664         s2 = msin(f2);
49665         t = math.tan(df / 4);
49666         hx = 4 / 3 * rx * t;
49667         hy = 4 / 3 * ry * t;
49668         m1 = [x1, y1];
49669         m2 = [x1 + hx * s1, y1 - hy * c1];
49670         m3 = [x2 + hx * s2, y2 - hy * c2];
49671         m4 = [x2, y2];
49672         m2[0] = 2 * m1[0] - m2[0];
49673         m2[1] = 2 * m1[1] - m2[1];
49674         if (recursive) {
49675             return [m2, m3, m4].concat(res);
49676         }
49677         else {
49678             res = [m2, m3, m4].concat(res).join().split(",");
49679             newres = [];
49680             ln = res.length;
49681             for (i = 0;  i < ln; i++) {
49682                 newres[i] = i % 2 ? me.rotate(res[i - 1], res[i], rad).y : me.rotate(res[i], res[i + 1], rad).x;
49683             }
49684             return newres;
49685         }
49686     },
49687     
49688     rotatePoint: function (x, y, alpha, cx, cy) {
49689         if (!alpha) {
49690             return {
49691                 x: x,
49692                 y: y
49693             };
49694         }
49695         cx = cx || 0;
49696         cy = cy || 0;
49697         x = x - cx;
49698         y = y - cy;
49699         alpha = alpha * this.radian;
49700         var cos = Math.cos(alpha),
49701             sin = Math.sin(alpha);
49702         return {
49703             x: x * cos - y * sin + cx,
49704             y: x * sin + y * cos + cy
49705         };
49706     },
49707
49708     rotateAndTranslatePath: function (sprite) {
49709         var alpha = sprite.rotation.degrees,
49710             cx = sprite.rotation.x,
49711             cy = sprite.rotation.y,
49712             dx = sprite.translation.x,
49713             dy = sprite.translation.y,
49714             path,
49715             i,
49716             p,
49717             xy,
49718             j,
49719             res = [];
49720         if (!alpha && !dx && !dy) {
49721             return this.pathToAbsolute(sprite.attr.path);
49722         }
49723         dx = dx || 0;
49724         dy = dy || 0;
49725         path = this.pathToAbsolute(sprite.attr.path);
49726         for (i = path.length; i--;) {
49727             p = res[i] = path[i].slice();
49728             if (p[0] == "A") {
49729                 xy = this.rotatePoint(p[6], p[7], alpha, cx, cy);
49730                 p[6] = xy.x + dx;
49731                 p[7] = xy.y + dy;
49732             } else {
49733                 j = 1;
49734                 while (p[j + 1] != null) {
49735                     xy = this.rotatePoint(p[j], p[j + 1], alpha, cx, cy);
49736                     p[j] = xy.x + dx;
49737                     p[j + 1] = xy.y + dy;
49738                     j += 2;
49739                 }
49740             }
49741         }
49742         return res;
49743     },
49744     
49745     pathDimensions: function (path) {
49746         if (!path || !(path + "")) {
49747             return {x: 0, y: 0, width: 0, height: 0};
49748         }
49749         path = this.path2curve(path);
49750         var x = 0, 
49751             y = 0,
49752             X = [],
49753             Y = [],
49754             p,
49755             i,
49756             ii,
49757             xmin,
49758             ymin,
49759             dim;
49760         for (i = 0, ii = path.length; i < ii; i++) {
49761             p = path[i];
49762             if (p[0] == "M") {
49763                 x = p[1];
49764                 y = p[2];
49765                 X.push(x);
49766                 Y.push(y);
49767             }
49768             else {
49769                 dim = this.curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
49770                 X = X.concat(dim.min.x, dim.max.x);
49771                 Y = Y.concat(dim.min.y, dim.max.y);
49772                 x = p[5];
49773                 y = p[6];
49774             }
49775         }
49776         xmin = Math.min.apply(0, X);
49777         ymin = Math.min.apply(0, Y);
49778         return {
49779             x: xmin,
49780             y: ymin,
49781             path: path,
49782             width: Math.max.apply(0, X) - xmin,
49783             height: Math.max.apply(0, Y) - ymin
49784         };
49785     },
49786     
49787     intersect: function(subjectPolygon, clipPolygon) {
49788         var cp1, cp2, s, e, point;
49789         var inside = function(p) {
49790             return (cp2[0]-cp1[0]) * (p[1]-cp1[1]) > (cp2[1]-cp1[1]) * (p[0]-cp1[0]);
49791         };
49792         var intersection = function() {
49793             var p = [];
49794             var dcx = cp1[0]-cp2[0],
49795                 dcy = cp1[1]-cp2[1],
49796                 dpx = s[0]-e[0],
49797                 dpy = s[1]-e[1],
49798                 n1 = cp1[0]*cp2[1] - cp1[1]*cp2[0],
49799                 n2 = s[0]*e[1] - s[1]*e[0],
49800                 n3 = 1 / (dcx*dpy - dcy*dpx);
49801
49802             p[0] = (n1*dpx - n2*dcx) * n3;
49803             p[1] = (n1*dpy - n2*dcy) * n3;
49804             return p;
49805         };
49806         var outputList = subjectPolygon;
49807         cp1 = clipPolygon[clipPolygon.length -1];
49808         for (var i = 0, l = clipPolygon.length; i < l; ++i) {
49809             cp2 = clipPolygon[i];
49810             var inputList = outputList;
49811             outputList = [];
49812             s = inputList[inputList.length -1];
49813             for (var j = 0, ln = inputList.length; j < ln; j++) {
49814                 e = inputList[j];
49815                 if (inside(e)) {
49816                     if (!inside(s)) {
49817                         outputList.push(intersection());
49818                     }
49819                     outputList.push(e);
49820                 } else if (inside(s)) {
49821                     outputList.push(intersection());
49822                 }
49823                 s = e;
49824             }
49825             cp1 = cp2;
49826         }
49827         return outputList;
49828     },
49829     
49830     curveDim: function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
49831         var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x),
49832             b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
49833             c = p1x - c1x,
49834             t1 = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 / a,
49835             t2 = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 / a,
49836             y = [p1y, p2y],
49837             x = [p1x, p2x],
49838             dot;
49839         if (Math.abs(t1) > 1e12) {
49840             t1 = 0.5;
49841         }
49842         if (Math.abs(t2) > 1e12) {
49843             t2 = 0.5;
49844         }
49845         if (t1 > 0 && t1 < 1) {
49846             dot = this.findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
49847             x.push(dot.x);
49848             y.push(dot.y);
49849         }
49850         if (t2 > 0 && t2 < 1) {
49851             dot = this.findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
49852             x.push(dot.x);
49853             y.push(dot.y);
49854         }
49855         a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y);
49856         b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
49857         c = p1y - c1y;
49858         t1 = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 / a;
49859         t2 = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 / a;
49860         if (Math.abs(t1) > 1e12) {
49861             t1 = 0.5;
49862         }
49863         if (Math.abs(t2) > 1e12) {
49864             t2 = 0.5;
49865         }
49866         if (t1 > 0 && t1 < 1) {
49867             dot = this.findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
49868             x.push(dot.x);
49869             y.push(dot.y);
49870         }
49871         if (t2 > 0 && t2 < 1) {
49872             dot = this.findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
49873             x.push(dot.x);
49874             y.push(dot.y);
49875         }
49876         return {
49877             min: {x: Math.min.apply(0, x), y: Math.min.apply(0, y)},
49878             max: {x: Math.max.apply(0, x), y: Math.max.apply(0, y)}
49879         };
49880     },
49881
49882     getAnchors: function (p1x, p1y, p2x, p2y, p3x, p3y, value) {
49883         value = value || 4;
49884         var l = Math.min(Math.sqrt(Math.pow(p1x - p2x, 2) + Math.pow(p1y - p2y, 2)) / value, Math.sqrt(Math.pow(p3x - p2x, 2) + Math.pow(p3y - p2y, 2)) / value),
49885             a = Math.atan((p2x - p1x) / Math.abs(p2y - p1y)),
49886             b = Math.atan((p3x - p2x) / Math.abs(p2y - p3y)),
49887             pi = Math.PI;
49888         a = p1y < p2y ? pi - a : a;
49889         b = p3y < p2y ? pi - b : b;
49890         var alpha = pi / 2 - ((a + b) % (pi * 2)) / 2;
49891         alpha > pi / 2 && (alpha -= pi);
49892         var dx1 = l * Math.sin(alpha + a),
49893             dy1 = l * Math.cos(alpha + a),
49894             dx2 = l * Math.sin(alpha + b),
49895             dy2 = l * Math.cos(alpha + b),
49896             out = {
49897                 x1: p2x - dx1,
49898                 y1: p2y + dy1,
49899                 x2: p2x + dx2,
49900                 y2: p2y + dy2
49901             };
49902         return out;
49903     },
49904
49905     /* Smoothing function for a path.  Converts a path into cubic beziers.  Value defines the divider of the distance between points.
49906      * Defaults to a value of 4.
49907      */
49908     smooth: function (originalPath, value) {
49909         var path = this.path2curve(originalPath),
49910             newp = [path[0]],
49911             x = path[0][1],
49912             y = path[0][2],
49913             j,
49914             points,
49915             i = 1,
49916             ii = path.length,
49917             beg = 1,
49918             mx = x,
49919             my = y,
49920             cx = 0,
49921             cy = 0;
49922         for (; i < ii; i++) {
49923             var pathi = path[i],
49924                 pathil = pathi.length,
49925                 pathim = path[i - 1],
49926                 pathiml = pathim.length,
49927                 pathip = path[i + 1],
49928                 pathipl = pathip && pathip.length;
49929             if (pathi[0] == "M") {
49930                 mx = pathi[1];
49931                 my = pathi[2];
49932                 j = i + 1;
49933                 while (path[j][0] != "C") {
49934                     j++;
49935                 }
49936                 cx = path[j][5];
49937                 cy = path[j][6];
49938                 newp.push(["M", mx, my]);
49939                 beg = newp.length;
49940                 x = mx;
49941                 y = my;
49942                 continue;
49943             }
49944             if (pathi[pathil - 2] == mx && pathi[pathil - 1] == my && (!pathip || pathip[0] == "M")) {
49945                 var begl = newp[beg].length;
49946                 points = this.getAnchors(pathim[pathiml - 2], pathim[pathiml - 1], mx, my, newp[beg][begl - 2], newp[beg][begl - 1], value);
49947                 newp[beg][1] = points.x2;
49948                 newp[beg][2] = points.y2;
49949             }
49950             else if (!pathip || pathip[0] == "M") {
49951                 points = {
49952                     x1: pathi[pathil - 2],
49953                     y1: pathi[pathil - 1]
49954                 };
49955             } else {
49956                 points = this.getAnchors(pathim[pathiml - 2], pathim[pathiml - 1], pathi[pathil - 2], pathi[pathil - 1], pathip[pathipl - 2], pathip[pathipl - 1], value);
49957             }
49958             newp.push(["C", x, y, points.x1, points.y1, pathi[pathil - 2], pathi[pathil - 1]]);
49959             x = points.x2;
49960             y = points.y2;
49961         }
49962         return newp;
49963     },
49964
49965     findDotAtSegment: function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
49966         var t1 = 1 - t;
49967         return {
49968             x: Math.pow(t1, 3) * p1x + Math.pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + Math.pow(t, 3) * p2x,
49969             y: Math.pow(t1, 3) * p1y + Math.pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + Math.pow(t, 3) * p2y
49970         };
49971     },
49972
49973     snapEnds: function (from, to, stepsMax) {
49974         var step = (to - from) / stepsMax,
49975             level = Math.floor(Math.log(step) / Math.LN10) + 1,
49976             m = Math.pow(10, level),
49977             cur,
49978             modulo = Math.round((step % m) * Math.pow(10, 2 - level)),
49979             interval = [[0, 15], [20, 4], [30, 2], [40, 4], [50, 9], [60, 4], [70, 2], [80, 4], [100, 15]],
49980             stepCount = 0,
49981             value,
49982             weight,
49983             i,
49984             topValue,
49985             topWeight = 1e9,
49986             ln = interval.length;
49987         cur = from = Math.floor(from / m) * m;
49988         for (i = 0; i < ln; i++) {
49989             value = interval[i][0];
49990             weight = (value - modulo) < 0 ? 1e6 : (value - modulo) / interval[i][1];
49991             if (weight < topWeight) {
49992                 topValue = value;
49993                 topWeight = weight;
49994             }
49995         }
49996         step = Math.floor(step * Math.pow(10, -level)) * Math.pow(10, level) + topValue * Math.pow(10, level - 2);
49997         while (cur < to) {
49998             cur += step;
49999             stepCount++;
50000         }
50001         to = +cur.toFixed(10);
50002         return {
50003             from: from,
50004             to: to,
50005             power: level,
50006             step: step,
50007             steps: stepCount
50008         };
50009     },
50010
50011     sorter: function (a, b) {
50012         return a.offset - b.offset;
50013     },
50014
50015     rad: function(degrees) {
50016         return degrees % 360 * Math.PI / 180;
50017     },
50018
50019     degrees: function(radian) {
50020         return radian * 180 / Math.PI % 360;
50021     },
50022
50023     withinBox: function(x, y, bbox) {
50024         bbox = bbox || {};
50025         return (x >= bbox.x && x <= (bbox.x + bbox.width) && y >= bbox.y && y <= (bbox.y + bbox.height));
50026     },
50027
50028     parseGradient: function(gradient) {
50029         var me = this,
50030             type = gradient.type || 'linear',
50031             angle = gradient.angle || 0,
50032             radian = me.radian,
50033             stops = gradient.stops,
50034             stopsArr = [],
50035             stop,
50036             vector,
50037             max,
50038             stopObj;
50039
50040         if (type == 'linear') {
50041             vector = [0, 0, Math.cos(angle * radian), Math.sin(angle * radian)];
50042             max = 1 / (Math.max(Math.abs(vector[2]), Math.abs(vector[3])) || 1);
50043             vector[2] *= max;
50044             vector[3] *= max;
50045             if (vector[2] < 0) {
50046                 vector[0] = -vector[2];
50047                 vector[2] = 0;
50048             }
50049             if (vector[3] < 0) {
50050                 vector[1] = -vector[3];
50051                 vector[3] = 0;
50052             }
50053         }
50054
50055         for (stop in stops) {
50056             if (stops.hasOwnProperty(stop) && me.stopsRE.test(stop)) {
50057                 stopObj = {
50058                     offset: parseInt(stop, 10),
50059                     color: Ext.draw.Color.toHex(stops[stop].color) || '#ffffff',
50060                     opacity: stops[stop].opacity || 1
50061                 };
50062                 stopsArr.push(stopObj);
50063             }
50064         }
50065         // Sort by pct property
50066         Ext.Array.sort(stopsArr, me.sorter);
50067         if (type == 'linear') {
50068             return {
50069                 id: gradient.id,
50070                 type: type,
50071                 vector: vector,
50072                 stops: stopsArr
50073             };
50074         }
50075         else {
50076             return {
50077                 id: gradient.id,
50078                 type: type,
50079                 centerX: gradient.centerX,
50080                 centerY: gradient.centerY,
50081                 focalX: gradient.focalX,
50082                 focalY: gradient.focalY,
50083                 radius: gradient.radius,
50084                 vector: vector,
50085                 stops: stopsArr
50086             };
50087         }
50088     }
50089 });
50090
50091 /**
50092  * @class Ext.fx.PropertyHandler
50093  * @ignore
50094  */
50095 Ext.define('Ext.fx.PropertyHandler', {
50096
50097     /* Begin Definitions */
50098
50099     requires: ['Ext.draw.Draw'],
50100
50101     statics: {
50102         defaultHandler: {
50103             pixelDefaults: ['width', 'height', 'top', 'left'],
50104             unitRE: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/,
50105
50106             computeDelta: function(from, end, damper, initial, attr) {
50107                 damper = (typeof damper == 'number') ? damper : 1;
50108                 var match = this.unitRE.exec(from),
50109                     start, units;
50110                 if (match) {
50111                     from = match[1];
50112                     units = match[2];
50113                     if (!units && Ext.Array.contains(this.pixelDefaults, attr)) {
50114                         units = 'px';
50115                     }
50116                 }
50117                 from = +from || 0;
50118
50119                 match = this.unitRE.exec(end);
50120                 if (match) {
50121                     end = match[1];
50122                     units = match[2] || units;
50123                 }
50124                 end = +end || 0;
50125                 start = (initial != null) ? initial : from;
50126                 return {
50127                     from: from,
50128                     delta: (end - start) * damper,
50129                     units: units
50130                 };
50131             },
50132
50133             get: function(from, end, damper, initialFrom, attr) {
50134                 var ln = from.length,
50135                     out = [],
50136                     i, initial, res, j, len;
50137                 for (i = 0; i < ln; i++) {
50138                     if (initialFrom) {
50139                         initial = initialFrom[i][1].from;
50140                     }
50141                     if (Ext.isArray(from[i][1]) && Ext.isArray(end)) {
50142                         res = [];
50143                         j = 0;
50144                         len = from[i][1].length;
50145                         for (; j < len; j++) {
50146                             res.push(this.computeDelta(from[i][1][j], end[j], damper, initial, attr));
50147                         }
50148                         out.push([from[i][0], res]);
50149                     }
50150                     else {
50151                         out.push([from[i][0], this.computeDelta(from[i][1], end, damper, initial, attr)]);
50152                     }
50153                 }
50154                 return out;
50155             },
50156
50157             set: function(values, easing) {
50158                 var ln = values.length,
50159                     out = [],
50160                     i, val, res, len, j;
50161                 for (i = 0; i < ln; i++) {
50162                     val  = values[i][1];
50163                     if (Ext.isArray(val)) {
50164                         res = [];
50165                         j = 0;
50166                         len = val.length;
50167                         for (; j < len; j++) {
50168                             res.push(val[j].from + (val[j].delta * easing) + (val[j].units || 0));
50169                         }
50170                         out.push([values[i][0], res]);
50171                     } else {
50172                         out.push([values[i][0], val.from + (val.delta * easing) + (val.units || 0)]);
50173                     }
50174                 }
50175                 return out;
50176             }
50177         },
50178         color: {
50179             rgbRE: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,
50180             hexRE: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,
50181             hex3RE: /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i,
50182
50183             parseColor : function(color, damper) {
50184                 damper = (typeof damper == 'number') ? damper : 1;
50185                 var base,
50186                     out = false,
50187                     match;
50188
50189                 Ext.each([this.hexRE, this.rgbRE, this.hex3RE], function(re, idx) {
50190                     base = (idx % 2 == 0) ? 16 : 10;
50191                     match = re.exec(color);
50192                     if (match && match.length == 4) {
50193                         if (idx == 2) {
50194                             match[1] += match[1];
50195                             match[2] += match[2];
50196                             match[3] += match[3];
50197                         }
50198                         out = {
50199                             red: parseInt(match[1], base),
50200                             green: parseInt(match[2], base),
50201                             blue: parseInt(match[3], base)
50202                         };
50203                         return false;
50204                     }
50205                 });
50206                 return out || color;
50207             },
50208
50209             computeDelta: function(from, end, damper, initial) {
50210                 from = this.parseColor(from);
50211                 end = this.parseColor(end, damper);
50212                 var start = initial ? initial : from,
50213                     tfrom = typeof start,
50214                     tend = typeof end;
50215                 //Extra check for when the color string is not recognized.
50216                 if (tfrom == 'string' ||  tfrom == 'undefined' 
50217                   || tend == 'string' || tend == 'undefined') {
50218                     return end || start;
50219                 }
50220                 return {
50221                     from:  from,
50222                     delta: {
50223                         red: Math.round((end.red - start.red) * damper),
50224                         green: Math.round((end.green - start.green) * damper),
50225                         blue: Math.round((end.blue - start.blue) * damper)
50226                     }
50227                 };
50228             },
50229
50230             get: function(start, end, damper, initialFrom) {
50231                 var ln = start.length,
50232                     out = [],
50233                     i, initial;
50234                 for (i = 0; i < ln; i++) {
50235                     if (initialFrom) {
50236                         initial = initialFrom[i][1].from;
50237                     }
50238                     out.push([start[i][0], this.computeDelta(start[i][1], end, damper, initial)]);
50239                 }
50240                 return out;
50241             },
50242
50243             set: function(values, easing) {
50244                 var ln = values.length,
50245                     out = [],
50246                     i, val, parsedString, from, delta;
50247                 for (i = 0; i < ln; i++) {
50248                     val = values[i][1];
50249                     if (val) {
50250                         from = val.from;
50251                         delta = val.delta;
50252                         //multiple checks to reformat the color if it can't recognized by computeDelta.
50253                         val = (typeof val == 'object' && 'red' in val)? 
50254                                 'rgb(' + val.red + ', ' + val.green + ', ' + val.blue + ')' : val;
50255                         val = (typeof val == 'object' && val.length)? val[0] : val;
50256                         if (typeof val == 'undefined') {
50257                             return [];
50258                         }
50259                         parsedString = typeof val == 'string'? val :
50260                             'rgb(' + [
50261                                   (from.red + Math.round(delta.red * easing)) % 256,
50262                                   (from.green + Math.round(delta.green * easing)) % 256,
50263                                   (from.blue + Math.round(delta.blue * easing)) % 256
50264                               ].join(',') + ')';
50265                         out.push([
50266                             values[i][0],
50267                             parsedString
50268                         ]);
50269                     }
50270                 }
50271                 return out;
50272             }
50273         },
50274         object: {
50275             interpolate: function(prop, damper) {
50276                 damper = (typeof damper == 'number') ? damper : 1;
50277                 var out = {},
50278                     p;
50279                 for(p in prop) {
50280                     out[p] = parseInt(prop[p], 10) * damper;
50281                 }
50282                 return out;
50283             },
50284
50285             computeDelta: function(from, end, damper, initial) {
50286                 from = this.interpolate(from);
50287                 end = this.interpolate(end, damper);
50288                 var start = initial ? initial : from,
50289                     delta = {},
50290                     p;
50291
50292                 for(p in end) {
50293                     delta[p] = end[p] - start[p];
50294                 }
50295                 return {
50296                     from:  from,
50297                     delta: delta
50298                 };
50299             },
50300
50301             get: function(start, end, damper, initialFrom) {
50302                 var ln = start.length,
50303                     out = [],
50304                     i, initial;
50305                 for (i = 0; i < ln; i++) {
50306                     if (initialFrom) {
50307                         initial = initialFrom[i][1].from;
50308                     }
50309                     out.push([start[i][0], this.computeDelta(start[i][1], end, damper, initial)]);
50310                 }
50311                 return out;
50312             },
50313
50314             set: function(values, easing) {
50315                 var ln = values.length,
50316                     out = [],
50317                     outObject = {},
50318                     i, from, delta, val, p;
50319                 for (i = 0; i < ln; i++) {
50320                     val  = values[i][1];
50321                     from = val.from;
50322                     delta = val.delta;
50323                     for (p in from) {
50324                         outObject[p] = Math.round(from[p] + delta[p] * easing);
50325                     }
50326                     out.push([
50327                         values[i][0],
50328                         outObject
50329                     ]);
50330                 }
50331                 return out;
50332             }
50333         },
50334
50335         path: {
50336             computeDelta: function(from, end, damper, initial) {
50337                 damper = (typeof damper == 'number') ? damper : 1;
50338                 var start;
50339                 from = +from || 0;
50340                 end = +end || 0;
50341                 start = (initial != null) ? initial : from;
50342                 return {
50343                     from: from,
50344                     delta: (end - start) * damper
50345                 };
50346             },
50347
50348             forcePath: function(path) {
50349                 if (!Ext.isArray(path) && !Ext.isArray(path[0])) {
50350                     path = Ext.draw.Draw.parsePathString(path);
50351                 }
50352                 return path;
50353             },
50354
50355             get: function(start, end, damper, initialFrom) {
50356                 var endPath = this.forcePath(end),
50357                     out = [],
50358                     startLn = start.length,
50359                     startPathLn, pointsLn, i, deltaPath, initial, j, k, path, startPath;
50360                 for (i = 0; i < startLn; i++) {
50361                     startPath = this.forcePath(start[i][1]);
50362
50363                     deltaPath = Ext.draw.Draw.interpolatePaths(startPath, endPath);
50364                     startPath = deltaPath[0];
50365                     endPath = deltaPath[1];
50366
50367                     startPathLn = startPath.length;
50368                     path = [];
50369                     for (j = 0; j < startPathLn; j++) {
50370                         deltaPath = [startPath[j][0]];
50371                         pointsLn = startPath[j].length;
50372                         for (k = 1; k < pointsLn; k++) {
50373                             initial = initialFrom && initialFrom[0][1][j][k].from;
50374                             deltaPath.push(this.computeDelta(startPath[j][k], endPath[j][k], damper, initial));
50375                         }
50376                         path.push(deltaPath);
50377                     }
50378                     out.push([start[i][0], path]);
50379                 }
50380                 return out;
50381             },
50382
50383             set: function(values, easing) {
50384                 var ln = values.length,
50385                     out = [],
50386                     i, j, k, newPath, calcPath, deltaPath, deltaPathLn, pointsLn;
50387                 for (i = 0; i < ln; i++) {
50388                     deltaPath = values[i][1];
50389                     newPath = [];
50390                     deltaPathLn = deltaPath.length;
50391                     for (j = 0; j < deltaPathLn; j++) {
50392                         calcPath = [deltaPath[j][0]];
50393                         pointsLn = deltaPath[j].length;
50394                         for (k = 1; k < pointsLn; k++) {
50395                             calcPath.push(deltaPath[j][k].from + deltaPath[j][k].delta * easing);
50396                         }
50397                         newPath.push(calcPath.join(','));
50398                     }
50399                     out.push([values[i][0], newPath.join(',')]);
50400                 }
50401                 return out;
50402             }
50403         }
50404         /* End Definitions */
50405     }
50406 }, function() {
50407     Ext.each([
50408         'outlineColor',
50409         'backgroundColor',
50410         'borderColor',
50411         'borderTopColor',
50412         'borderRightColor', 
50413         'borderBottomColor', 
50414         'borderLeftColor',
50415         'fill',
50416         'stroke'
50417     ], function(prop) {
50418         this[prop] = this.color;
50419     }, this);
50420 });
50421 /**
50422  * @class Ext.fx.Anim
50423  * 
50424  * This class manages animation for a specific {@link #target}. The animation allows
50425  * animation of various properties on the target, such as size, position, color and others.
50426  * 
50427  * ## Starting Conditions
50428  * The starting conditions for the animation are provided by the {@link #from} configuration.
50429  * Any/all of the properties in the {@link #from} configuration can be specified. If a particular
50430  * property is not defined, the starting value for that property will be read directly from the target.
50431  * 
50432  * ## End Conditions
50433  * The ending conditions for the animation are provided by the {@link #to} configuration. These mark
50434  * the final values once the animations has finished. The values in the {@link #from} can mirror
50435  * those in the {@link #to} configuration to provide a starting point.
50436  * 
50437  * ## Other Options
50438  *  - {@link #duration}: Specifies the time period of the animation.
50439  *  - {@link #easing}: Specifies the easing of the animation.
50440  *  - {@link #iterations}: Allows the animation to repeat a number of times.
50441  *  - {@link #alternate}: Used in conjunction with {@link #iterations}, reverses the direction every second iteration.
50442  * 
50443  * ## Example Code
50444  * 
50445  *     var myComponent = Ext.create('Ext.Component', {
50446  *         renderTo: document.body,
50447  *         width: 200,
50448  *         height: 200,
50449  *         style: 'border: 1px solid red;'
50450  *     });
50451  *     
50452  *     new Ext.fx.Anim({
50453  *         target: myComponent,
50454  *         duration: 1000,
50455  *         from: {
50456  *             width: 400 //starting width 400
50457  *         },
50458  *         to: {
50459  *             width: 300, //end width 300
50460  *             height: 300 // end width 300
50461  *         }
50462  *     });
50463  */
50464 Ext.define('Ext.fx.Anim', {
50465
50466     /* Begin Definitions */
50467
50468     mixins: {
50469         observable: 'Ext.util.Observable'
50470     },
50471
50472     requires: ['Ext.fx.Manager', 'Ext.fx.Animator', 'Ext.fx.Easing', 'Ext.fx.CubicBezier', 'Ext.fx.PropertyHandler'],
50473
50474     /* End Definitions */
50475
50476     isAnimation: true,
50477     /**
50478      * @cfg {Number} duration
50479      * Time in milliseconds for a single animation to last. Defaults to 250. If the {@link #iterations} property is
50480      * specified, then each animate will take the same duration for each iteration.
50481      */
50482     duration: 250,
50483
50484     /**
50485      * @cfg {Number} delay
50486      * Time to delay before starting the animation. Defaults to 0.
50487      */
50488     delay: 0,
50489
50490     /* private used to track a delayed starting time */
50491     delayStart: 0,
50492
50493     /**
50494      * @cfg {Boolean} dynamic
50495      * Currently only for Component Animation: Only set a component's outer element size bypassing layouts.  Set to true to do full layouts for every frame of the animation.  Defaults to false.
50496      */
50497     dynamic: false,
50498
50499     /**
50500      * @cfg {String} easing
50501 This describes how the intermediate values used during a transition will be calculated. It allows for a transition to change
50502 speed over its duration. 
50503
50504          -backIn
50505          -backOut
50506          -bounceIn
50507          -bounceOut
50508          -ease
50509          -easeIn
50510          -easeOut
50511          -easeInOut
50512          -elasticIn
50513          -elasticOut
50514          -cubic-bezier(x1, y1, x2, y2)
50515
50516 Note that cubic-bezier will create a custom easing curve following the CSS3 transition-timing-function specification `{@link http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag}`. The four values specify points P1 and P2 of the curve
50517 as (x1, y1, x2, y2). All values must be in the range [0, 1] or the definition is invalid.
50518      * @markdown
50519      */
50520     easing: 'ease',
50521
50522      /**
50523       * @cfg {Object} keyframes
50524       * Animation keyframes follow the CSS3 Animation configuration pattern. 'from' is always considered '0%' and 'to'
50525       * is considered '100%'.<b>Every keyframe declaration must have a keyframe rule for 0% and 100%, possibly defined using
50526       * "from" or "to"</b>.  A keyframe declaration without these keyframe selectors is invalid and will not be available for
50527       * animation.  The keyframe declaration for a keyframe rule consists of properties and values. Properties that are unable to
50528       * be animated are ignored in these rules, with the exception of 'easing' which can be changed at each keyframe. For example:
50529  <pre><code>
50530 keyframes : {
50531     '0%': {
50532         left: 100
50533     },
50534     '40%': {
50535         left: 150
50536     },
50537     '60%': {
50538         left: 75
50539     },
50540     '100%': {
50541         left: 100
50542     }
50543 }
50544  </code></pre>
50545       */
50546
50547     /**
50548      * @private
50549      */
50550     damper: 1,
50551
50552     /**
50553      * @private
50554      */
50555     bezierRE: /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
50556
50557     /**
50558      * Run the animation from the end to the beginning
50559      * Defaults to false.
50560      * @cfg {Boolean} reverse
50561      */
50562     reverse: false,
50563
50564     /**
50565      * Flag to determine if the animation has started
50566      * @property running
50567      * @type boolean
50568      */
50569     running: false,
50570
50571     /**
50572      * Flag to determine if the animation is paused. Only set this to true if you need to
50573      * keep the Anim instance around to be unpaused later; otherwise call {@link #end}.
50574      * @property paused
50575      * @type boolean
50576      */
50577     paused: false,
50578
50579     /**
50580      * Number of times to execute the animation. Defaults to 1.
50581      * @cfg {int} iterations
50582      */
50583     iterations: 1,
50584
50585     /**
50586      * Used in conjunction with iterations to reverse the animation each time an iteration completes.
50587      * @cfg {Boolean} alternate
50588      * Defaults to false.
50589      */
50590     alternate: false,
50591
50592     /**
50593      * Current iteration the animation is running.
50594      * @property currentIteration
50595      * @type int
50596      */
50597     currentIteration: 0,
50598
50599     /**
50600      * Starting time of the animation.
50601      * @property startTime
50602      * @type Date
50603      */
50604     startTime: 0,
50605
50606     /**
50607      * Contains a cache of the interpolators to be used.
50608      * @private
50609      * @property propHandlers
50610      * @type Object
50611      */
50612
50613     /**
50614      * @cfg {String/Object} target
50615      * The {@link Ext.fx.target.Target} to apply the animation to.  This should only be specified when creating an Ext.fx.Anim directly.
50616      * The target does not need to be a {@link Ext.fx.target.Target} instance, it can be the underlying object. For example, you can
50617      * pass a Component, Element or Sprite as the target and the Anim will create the appropriate {@link Ext.fx.target.Target} object
50618      * automatically.
50619      */
50620
50621     /**
50622      * @cfg {Object} from
50623      * An object containing property/value pairs for the beginning of the animation.  If not specified, the current state of the
50624      * Ext.fx.target will be used. For example:
50625 <pre><code>
50626 from : {
50627     opacity: 0,       // Transparent
50628     color: '#ffffff', // White
50629     left: 0
50630 }
50631 </code></pre>
50632      */
50633
50634     /**
50635      * @cfg {Object} to
50636      * An object containing property/value pairs for the end of the animation. For example:
50637  <pre><code>
50638  to : {
50639      opacity: 1,       // Opaque
50640      color: '#00ff00', // Green
50641      left: 500
50642  }
50643  </code></pre>
50644      */
50645
50646     // @private
50647     constructor: function(config) {
50648         var me = this;
50649         config = config || {};
50650         // If keyframes are passed, they really want an Animator instead.
50651         if (config.keyframes) {
50652             return Ext.create('Ext.fx.Animator', config);
50653         }
50654         config = Ext.apply(me, config);
50655         if (me.from === undefined) {
50656             me.from = {};
50657         }
50658         me.propHandlers = {};
50659         me.config = config;
50660         me.target = Ext.fx.Manager.createTarget(me.target);
50661         me.easingFn = Ext.fx.Easing[me.easing];
50662         me.target.dynamic = me.dynamic;
50663
50664         // If not a pre-defined curve, try a cubic-bezier
50665         if (!me.easingFn) {
50666             me.easingFn = String(me.easing).match(me.bezierRE);
50667             if (me.easingFn && me.easingFn.length == 5) {
50668                 var curve = me.easingFn;
50669                 me.easingFn = Ext.fx.cubicBezier(+curve[1], +curve[2], +curve[3], +curve[4]);
50670             }
50671         }
50672         me.id = Ext.id(null, 'ext-anim-');
50673         Ext.fx.Manager.addAnim(me);
50674         me.addEvents(
50675             /**
50676              * @event beforeanimate
50677              * Fires before the animation starts. A handler can return false to cancel the animation.
50678              * @param {Ext.fx.Anim} this
50679              */
50680             'beforeanimate',
50681              /**
50682               * @event afteranimate
50683               * Fires when the animation is complete.
50684               * @param {Ext.fx.Anim} this
50685               * @param {Date} startTime
50686               */
50687             'afteranimate',
50688              /**
50689               * @event lastframe
50690               * Fires when the animation's last frame has been set.
50691               * @param {Ext.fx.Anim} this
50692               * @param {Date} startTime
50693               */
50694             'lastframe'
50695         );
50696         me.mixins.observable.constructor.call(me, config);
50697         if (config.callback) {
50698             me.on('afteranimate', config.callback, config.scope);
50699         }
50700         return me;
50701     },
50702
50703     /**
50704      * @private
50705      * Helper to the target
50706      */
50707     setAttr: function(attr, value) {
50708         return Ext.fx.Manager.items.get(this.id).setAttr(this.target, attr, value);
50709     },
50710
50711     /*
50712      * @private
50713      * Set up the initial currentAttrs hash.
50714      */
50715     initAttrs: function() {
50716         var me = this,
50717             from = me.from,
50718             to = me.to,
50719             initialFrom = me.initialFrom || {},
50720             out = {},
50721             start, end, propHandler, attr;
50722
50723         for (attr in to) {
50724             if (to.hasOwnProperty(attr)) {
50725                 start = me.target.getAttr(attr, from[attr]);
50726                 end = to[attr];
50727                 // Use default (numeric) property handler
50728                 if (!Ext.fx.PropertyHandler[attr]) {
50729                     if (Ext.isObject(end)) {
50730                         propHandler = me.propHandlers[attr] = Ext.fx.PropertyHandler.object;
50731                     } else {
50732                         propHandler = me.propHandlers[attr] = Ext.fx.PropertyHandler.defaultHandler;
50733                     }
50734                 }
50735                 // Use custom handler
50736                 else {
50737                     propHandler = me.propHandlers[attr] = Ext.fx.PropertyHandler[attr];
50738                 }
50739                 out[attr] = propHandler.get(start, end, me.damper, initialFrom[attr], attr);
50740             }
50741         }
50742         me.currentAttrs = out;
50743     },
50744
50745     /*
50746      * @private
50747      * Fires beforeanimate and sets the running flag.
50748      */
50749     start: function(startTime) {
50750         var me = this,
50751             delay = me.delay,
50752             delayStart = me.delayStart,
50753             delayDelta;
50754         if (delay) {
50755             if (!delayStart) {
50756                 me.delayStart = startTime;
50757                 return;
50758             }
50759             else {
50760                 delayDelta = startTime - delayStart;
50761                 if (delayDelta < delay) {
50762                     return;
50763                 }
50764                 else {
50765                     // Compensate for frame delay;
50766                     startTime = new Date(delayStart.getTime() + delay);
50767                 }
50768             }
50769         }
50770         if (me.fireEvent('beforeanimate', me) !== false) {
50771             me.startTime = startTime;
50772             if (!me.paused && !me.currentAttrs) {
50773                 me.initAttrs();
50774             }
50775             me.running = true;
50776         }
50777     },
50778
50779     /*
50780      * @private
50781      * Calculate attribute value at the passed timestamp.
50782      * @returns a hash of the new attributes.
50783      */
50784     runAnim: function(elapsedTime) {
50785         var me = this,
50786             attrs = me.currentAttrs,
50787             duration = me.duration,
50788             easingFn = me.easingFn,
50789             propHandlers = me.propHandlers,
50790             ret = {},
50791             easing, values, attr, lastFrame;
50792
50793         if (elapsedTime >= duration) {
50794             elapsedTime = duration;
50795             lastFrame = true;
50796         }
50797         if (me.reverse) {
50798             elapsedTime = duration - elapsedTime;
50799         }
50800
50801         for (attr in attrs) {
50802             if (attrs.hasOwnProperty(attr)) {
50803                 values = attrs[attr];
50804                 easing = lastFrame ? 1 : easingFn(elapsedTime / duration);
50805                 ret[attr] = propHandlers[attr].set(values, easing);
50806             }
50807         }
50808         return ret;
50809     },
50810
50811     /*
50812      * @private
50813      * Perform lastFrame cleanup and handle iterations
50814      * @returns a hash of the new attributes.
50815      */
50816     lastFrame: function() {
50817         var me = this,
50818             iter = me.iterations,
50819             iterCount = me.currentIteration;
50820
50821         iterCount++;
50822         if (iterCount < iter) {
50823             if (me.alternate) {
50824                 me.reverse = !me.reverse;
50825             }
50826             me.startTime = new Date();
50827             me.currentIteration = iterCount;
50828             // Turn off paused for CSS3 Transitions
50829             me.paused = false;
50830         }
50831         else {
50832             me.currentIteration = 0;
50833             me.end();
50834             me.fireEvent('lastframe', me, me.startTime);
50835         }
50836     },
50837
50838     /*
50839      * Fire afteranimate event and end the animation. Usually called automatically when the
50840      * animation reaches its final frame, but can also be called manually to pre-emptively
50841      * stop and destroy the running animation.
50842      */
50843     end: function() {
50844         var me = this;
50845         me.startTime = 0;
50846         me.paused = false;
50847         me.running = false;
50848         Ext.fx.Manager.removeAnim(me);
50849         me.fireEvent('afteranimate', me, me.startTime);
50850     }
50851 });
50852 // Set flag to indicate that Fx is available. Class might not be available immediately.
50853 Ext.enableFx = true;
50854
50855 /*
50856  * This is a derivative of the similarly named class in the YUI Library.
50857  * The original license:
50858  * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
50859  * Code licensed under the BSD License:
50860  * http://developer.yahoo.net/yui/license.txt
50861  */
50862
50863
50864 /**
50865  * @class Ext.dd.DragDrop
50866  * Defines the interface and base operation of items that that can be
50867  * dragged or can be drop targets.  It was designed to be extended, overriding
50868  * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
50869  * Up to three html elements can be associated with a DragDrop instance:
50870  * <ul>
50871  * <li>linked element: the element that is passed into the constructor.
50872  * This is the element which defines the boundaries for interaction with
50873  * other DragDrop objects.</li>
50874  * <li>handle element(s): The drag operation only occurs if the element that
50875  * was clicked matches a handle element.  By default this is the linked
50876  * element, but there are times that you will want only a portion of the
50877  * linked element to initiate the drag operation, and the setHandleElId()
50878  * method provides a way to define this.</li>
50879  * <li>drag element: this represents the element that would be moved along
50880  * with the cursor during a drag operation.  By default, this is the linked
50881  * element itself as in {@link Ext.dd.DD}.  setDragElId() lets you define
50882  * a separate element that would be moved, as in {@link Ext.dd.DDProxy}.
50883  * </li>
50884  * </ul>
50885  * This class should not be instantiated until the onload event to ensure that
50886  * the associated elements are available.
50887  * The following would define a DragDrop obj that would interact with any
50888  * other DragDrop obj in the "group1" group:
50889  * <pre>
50890  *  dd = new Ext.dd.DragDrop("div1", "group1");
50891  * </pre>
50892  * Since none of the event handlers have been implemented, nothing would
50893  * actually happen if you were to run the code above.  Normally you would
50894  * override this class or one of the default implementations, but you can
50895  * also override the methods you want on an instance of the class...
50896  * <pre>
50897  *  dd.onDragDrop = function(e, id) {
50898  *  &nbsp;&nbsp;alert("dd was dropped on " + id);
50899  *  }
50900  * </pre>
50901  * @constructor
50902  * @param {String} id of the element that is linked to this instance
50903  * @param {String} sGroup the group of related DragDrop objects
50904  * @param {object} config an object containing configurable attributes
50905  *                Valid properties for DragDrop:
50906  *                    padding, isTarget, maintainOffset, primaryButtonOnly
50907  */
50908
50909 Ext.define('Ext.dd.DragDrop', {
50910     requires: ['Ext.dd.DragDropManager'],
50911     constructor: function(id, sGroup, config) {
50912         if(id) {
50913             this.init(id, sGroup, config);
50914         }
50915     },
50916     
50917     /**
50918      * Set to false to enable a DragDrop object to fire drag events while dragging
50919      * over its own Element. Defaults to true - DragDrop objects do not by default
50920      * fire drag events to themselves.
50921      * @property ignoreSelf
50922      * @type Boolean
50923      */
50924
50925     /**
50926      * The id of the element associated with this object.  This is what we
50927      * refer to as the "linked element" because the size and position of
50928      * this element is used to determine when the drag and drop objects have
50929      * interacted.
50930      * @property id
50931      * @type String
50932      */
50933     id: null,
50934
50935     /**
50936      * Configuration attributes passed into the constructor
50937      * @property config
50938      * @type object
50939      */
50940     config: null,
50941
50942     /**
50943      * The id of the element that will be dragged.  By default this is same
50944      * as the linked element, but could be changed to another element. Ex:
50945      * Ext.dd.DDProxy
50946      * @property dragElId
50947      * @type String
50948      * @private
50949      */
50950     dragElId: null,
50951
50952     /**
50953      * The ID of the element that initiates the drag operation.  By default
50954      * this is the linked element, but could be changed to be a child of this
50955      * element.  This lets us do things like only starting the drag when the
50956      * header element within the linked html element is clicked.
50957      * @property handleElId
50958      * @type String
50959      * @private
50960      */
50961     handleElId: null,
50962
50963     /**
50964      * An object who's property names identify HTML tags to be considered invalid as drag handles.
50965      * A non-null property value identifies the tag as invalid. Defaults to the 
50966      * following value which prevents drag operations from being initiated by &lt;a> elements:<pre><code>
50967 {
50968     A: "A"
50969 }</code></pre>
50970      * @property invalidHandleTypes
50971      * @type Object
50972      */
50973     invalidHandleTypes: null,
50974
50975     /**
50976      * An object who's property names identify the IDs of elements to be considered invalid as drag handles.
50977      * A non-null property value identifies the ID as invalid. For example, to prevent
50978      * dragging from being initiated on element ID "foo", use:<pre><code>
50979 {
50980     foo: true
50981 }</code></pre>
50982      * @property invalidHandleIds
50983      * @type Object
50984      */
50985     invalidHandleIds: null,
50986
50987     /**
50988      * An Array of CSS class names for elements to be considered in valid as drag handles.
50989      * @property invalidHandleClasses
50990      * @type Array
50991      */
50992     invalidHandleClasses: null,
50993
50994     /**
50995      * The linked element's absolute X position at the time the drag was
50996      * started
50997      * @property startPageX
50998      * @type int
50999      * @private
51000      */
51001     startPageX: 0,
51002
51003     /**
51004      * The linked element's absolute X position at the time the drag was
51005      * started
51006      * @property startPageY
51007      * @type int
51008      * @private
51009      */
51010     startPageY: 0,
51011
51012     /**
51013      * The group defines a logical collection of DragDrop objects that are
51014      * related.  Instances only get events when interacting with other
51015      * DragDrop object in the same group.  This lets us define multiple
51016      * groups using a single DragDrop subclass if we want.
51017      * @property groups
51018      * @type object An object in the format {'group1':true, 'group2':true}
51019      */
51020     groups: null,
51021
51022     /**
51023      * Individual drag/drop instances can be locked.  This will prevent
51024      * onmousedown start drag.
51025      * @property locked
51026      * @type boolean
51027      * @private
51028      */
51029     locked: false,
51030
51031     /**
51032      * Lock this instance
51033      * @method lock
51034      */
51035     lock: function() {
51036         this.locked = true;
51037     },
51038
51039     /**
51040      * When set to true, other DD objects in cooperating DDGroups do not receive
51041      * notification events when this DD object is dragged over them. Defaults to false.
51042      * @property moveOnly
51043      * @type boolean
51044      */
51045     moveOnly: false,
51046
51047     /**
51048      * Unlock this instace
51049      * @method unlock
51050      */
51051     unlock: function() {
51052         this.locked = false;
51053     },
51054
51055     /**
51056      * By default, all instances can be a drop target.  This can be disabled by
51057      * setting isTarget to false.
51058      * @property isTarget
51059      * @type boolean
51060      */
51061     isTarget: true,
51062
51063     /**
51064      * The padding configured for this drag and drop object for calculating
51065      * the drop zone intersection with this object.
51066      * @property padding
51067      * @type int[] An array containing the 4 padding values: [top, right, bottom, left]
51068      */
51069     padding: null,
51070
51071     /**
51072      * Cached reference to the linked element
51073      * @property _domRef
51074      * @private
51075      */
51076     _domRef: null,
51077
51078     /**
51079      * Internal typeof flag
51080      * @property __ygDragDrop
51081      * @private
51082      */
51083     __ygDragDrop: true,
51084
51085     /**
51086      * Set to true when horizontal contraints are applied
51087      * @property constrainX
51088      * @type boolean
51089      * @private
51090      */
51091     constrainX: false,
51092
51093     /**
51094      * Set to true when vertical contraints are applied
51095      * @property constrainY
51096      * @type boolean
51097      * @private
51098      */
51099     constrainY: false,
51100
51101     /**
51102      * The left constraint
51103      * @property minX
51104      * @type int
51105      * @private
51106      */
51107     minX: 0,
51108
51109     /**
51110      * The right constraint
51111      * @property maxX
51112      * @type int
51113      * @private
51114      */
51115     maxX: 0,
51116
51117     /**
51118      * The up constraint
51119      * @property minY
51120      * @type int
51121      * @private
51122      */
51123     minY: 0,
51124
51125     /**
51126      * The down constraint
51127      * @property maxY
51128      * @type int
51129      * @private
51130      */
51131     maxY: 0,
51132
51133     /**
51134      * Maintain offsets when we resetconstraints.  Set to true when you want
51135      * the position of the element relative to its parent to stay the same
51136      * when the page changes
51137      *
51138      * @property maintainOffset
51139      * @type boolean
51140      */
51141     maintainOffset: false,
51142
51143     /**
51144      * Array of pixel locations the element will snap to if we specified a
51145      * horizontal graduation/interval.  This array is generated automatically
51146      * when you define a tick interval.
51147      * @property xTicks
51148      * @type int[]
51149      */
51150     xTicks: null,
51151
51152     /**
51153      * Array of pixel locations the element will snap to if we specified a
51154      * vertical graduation/interval.  This array is generated automatically
51155      * when you define a tick interval.
51156      * @property yTicks
51157      * @type int[]
51158      */
51159     yTicks: null,
51160
51161     /**
51162      * By default the drag and drop instance will only respond to the primary
51163      * button click (left button for a right-handed mouse).  Set to true to
51164      * allow drag and drop to start with any mouse click that is propogated
51165      * by the browser
51166      * @property primaryButtonOnly
51167      * @type boolean
51168      */
51169     primaryButtonOnly: true,
51170
51171     /**
51172      * The available property is false until the linked dom element is accessible.
51173      * @property available
51174      * @type boolean
51175      */
51176     available: false,
51177
51178     /**
51179      * By default, drags can only be initiated if the mousedown occurs in the
51180      * region the linked element is.  This is done in part to work around a
51181      * bug in some browsers that mis-report the mousedown if the previous
51182      * mouseup happened outside of the window.  This property is set to true
51183      * if outer handles are defined.
51184      *
51185      * @property hasOuterHandles
51186      * @type boolean
51187      * @default false
51188      */
51189     hasOuterHandles: false,
51190
51191     /**
51192      * Code that executes immediately before the startDrag event
51193      * @method b4StartDrag
51194      * @private
51195      */
51196     b4StartDrag: function(x, y) { },
51197
51198     /**
51199      * Abstract method called after a drag/drop object is clicked
51200      * and the drag or mousedown time thresholds have beeen met.
51201      * @method startDrag
51202      * @param {int} X click location
51203      * @param {int} Y click location
51204      */
51205     startDrag: function(x, y) { /* override this */ },
51206
51207     /**
51208      * Code that executes immediately before the onDrag event
51209      * @method b4Drag
51210      * @private
51211      */
51212     b4Drag: function(e) { },
51213
51214     /**
51215      * Abstract method called during the onMouseMove event while dragging an
51216      * object.
51217      * @method onDrag
51218      * @param {Event} e the mousemove event
51219      */
51220     onDrag: function(e) { /* override this */ },
51221
51222     /**
51223      * Abstract method called when this element fist begins hovering over
51224      * another DragDrop obj
51225      * @method onDragEnter
51226      * @param {Event} e the mousemove event
51227      * @param {String|DragDrop[]} id In POINT mode, the element
51228      * id this is hovering over.  In INTERSECT mode, an array of one or more
51229      * dragdrop items being hovered over.
51230      */
51231     onDragEnter: function(e, id) { /* override this */ },
51232
51233     /**
51234      * Code that executes immediately before the onDragOver event
51235      * @method b4DragOver
51236      * @private
51237      */
51238     b4DragOver: function(e) { },
51239
51240     /**
51241      * Abstract method called when this element is hovering over another
51242      * DragDrop obj
51243      * @method onDragOver
51244      * @param {Event} e the mousemove event
51245      * @param {String|DragDrop[]} id In POINT mode, the element
51246      * id this is hovering over.  In INTERSECT mode, an array of dd items
51247      * being hovered over.
51248      */
51249     onDragOver: function(e, id) { /* override this */ },
51250
51251     /**
51252      * Code that executes immediately before the onDragOut event
51253      * @method b4DragOut
51254      * @private
51255      */
51256     b4DragOut: function(e) { },
51257
51258     /**
51259      * Abstract method called when we are no longer hovering over an element
51260      * @method onDragOut
51261      * @param {Event} e the mousemove event
51262      * @param {String|DragDrop[]} id In POINT mode, the element
51263      * id this was hovering over.  In INTERSECT mode, an array of dd items
51264      * that the mouse is no longer over.
51265      */
51266     onDragOut: function(e, id) { /* override this */ },
51267
51268     /**
51269      * Code that executes immediately before the onDragDrop event
51270      * @method b4DragDrop
51271      * @private
51272      */
51273     b4DragDrop: function(e) { },
51274
51275     /**
51276      * Abstract method called when this item is dropped on another DragDrop
51277      * obj
51278      * @method onDragDrop
51279      * @param {Event} e the mouseup event
51280      * @param {String|DragDrop[]} id In POINT mode, the element
51281      * id this was dropped on.  In INTERSECT mode, an array of dd items this
51282      * was dropped on.
51283      */
51284     onDragDrop: function(e, id) { /* override this */ },
51285
51286     /**
51287      * Abstract method called when this item is dropped on an area with no
51288      * drop target
51289      * @method onInvalidDrop
51290      * @param {Event} e the mouseup event
51291      */
51292     onInvalidDrop: function(e) { /* override this */ },
51293
51294     /**
51295      * Code that executes immediately before the endDrag event
51296      * @method b4EndDrag
51297      * @private
51298      */
51299     b4EndDrag: function(e) { },
51300
51301     /**
51302      * Fired when we are done dragging the object
51303      * @method endDrag
51304      * @param {Event} e the mouseup event
51305      */
51306     endDrag: function(e) { /* override this */ },
51307
51308     /**
51309      * Code executed immediately before the onMouseDown event
51310      * @method b4MouseDown
51311      * @param {Event} e the mousedown event
51312      * @private
51313      */
51314     b4MouseDown: function(e) {  },
51315
51316     /**
51317      * Event handler that fires when a drag/drop obj gets a mousedown
51318      * @method onMouseDown
51319      * @param {Event} e the mousedown event
51320      */
51321     onMouseDown: function(e) { /* override this */ },
51322
51323     /**
51324      * Event handler that fires when a drag/drop obj gets a mouseup
51325      * @method onMouseUp
51326      * @param {Event} e the mouseup event
51327      */
51328     onMouseUp: function(e) { /* override this */ },
51329
51330     /**
51331      * Override the onAvailable method to do what is needed after the initial
51332      * position was determined.
51333      * @method onAvailable
51334      */
51335     onAvailable: function () {
51336     },
51337
51338     /**
51339      * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
51340      * @type Object
51341      */
51342     defaultPadding: {
51343         left: 0,
51344         right: 0,
51345         top: 0,
51346         bottom: 0
51347     },
51348
51349     /**
51350      * Initializes the drag drop object's constraints to restrict movement to a certain element.
51351  *
51352  * Usage:
51353  <pre><code>
51354  var dd = new Ext.dd.DDProxy("dragDiv1", "proxytest",
51355                 { dragElId: "existingProxyDiv" });
51356  dd.startDrag = function(){
51357      this.constrainTo("parent-id");
51358  };
51359  </code></pre>
51360  * Or you can initalize it using the {@link Ext.core.Element} object:
51361  <pre><code>
51362  Ext.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
51363      startDrag : function(){
51364          this.constrainTo("parent-id");
51365      }
51366  });
51367  </code></pre>
51368      * @param {Mixed} constrainTo The element to constrain to.
51369      * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
51370      * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
51371      * an object containing the sides to pad. For example: {right:10, bottom:10}
51372      * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
51373      */
51374     constrainTo : function(constrainTo, pad, inContent){
51375         if(Ext.isNumber(pad)){
51376             pad = {left: pad, right:pad, top:pad, bottom:pad};
51377         }
51378         pad = pad || this.defaultPadding;
51379         var b = Ext.get(this.getEl()).getBox(),
51380             ce = Ext.get(constrainTo),
51381             s = ce.getScroll(),
51382             c, 
51383             cd = ce.dom;
51384         if(cd == document.body){
51385             c = { x: s.left, y: s.top, width: Ext.core.Element.getViewWidth(), height: Ext.core.Element.getViewHeight()};
51386         }else{
51387             var xy = ce.getXY();
51388             c = {x : xy[0], y: xy[1], width: cd.clientWidth, height: cd.clientHeight};
51389         }
51390
51391
51392         var topSpace = b.y - c.y,
51393             leftSpace = b.x - c.x;
51394
51395         this.resetConstraints();
51396         this.setXConstraint(leftSpace - (pad.left||0), // left
51397                 c.width - leftSpace - b.width - (pad.right||0), //right
51398                                 this.xTickSize
51399         );
51400         this.setYConstraint(topSpace - (pad.top||0), //top
51401                 c.height - topSpace - b.height - (pad.bottom||0), //bottom
51402                                 this.yTickSize
51403         );
51404     },
51405
51406     /**
51407      * Returns a reference to the linked element
51408      * @method getEl
51409      * @return {HTMLElement} the html element
51410      */
51411     getEl: function() {
51412         if (!this._domRef) {
51413             this._domRef = Ext.getDom(this.id);
51414         }
51415
51416         return this._domRef;
51417     },
51418
51419     /**
51420      * Returns a reference to the actual element to drag.  By default this is
51421      * the same as the html element, but it can be assigned to another
51422      * element. An example of this can be found in Ext.dd.DDProxy
51423      * @method getDragEl
51424      * @return {HTMLElement} the html element
51425      */
51426     getDragEl: function() {
51427         return Ext.getDom(this.dragElId);
51428     },
51429
51430     /**
51431      * Sets up the DragDrop object.  Must be called in the constructor of any
51432      * Ext.dd.DragDrop subclass
51433      * @method init
51434      * @param id the id of the linked element
51435      * @param {String} sGroup the group of related items
51436      * @param {object} config configuration attributes
51437      */
51438     init: function(id, sGroup, config) {
51439         this.initTarget(id, sGroup, config);
51440         Ext.EventManager.on(this.id, "mousedown", this.handleMouseDown, this);
51441         // Ext.EventManager.on(this.id, "selectstart", Event.preventDefault);
51442     },
51443
51444     /**
51445      * Initializes Targeting functionality only... the object does not
51446      * get a mousedown handler.
51447      * @method initTarget
51448      * @param id the id of the linked element
51449      * @param {String} sGroup the group of related items
51450      * @param {object} config configuration attributes
51451      */
51452     initTarget: function(id, sGroup, config) {
51453
51454         // configuration attributes
51455         this.config = config || {};
51456
51457         // create a local reference to the drag and drop manager
51458         this.DDMInstance = Ext.dd.DragDropManager;
51459         // initialize the groups array
51460         this.groups = {};
51461
51462         // assume that we have an element reference instead of an id if the
51463         // parameter is not a string
51464         if (typeof id !== "string") {
51465             id = Ext.id(id);
51466         }
51467
51468         // set the id
51469         this.id = id;
51470
51471         // add to an interaction group
51472         this.addToGroup((sGroup) ? sGroup : "default");
51473
51474         // We don't want to register this as the handle with the manager
51475         // so we just set the id rather than calling the setter.
51476         this.handleElId = id;
51477
51478         // the linked element is the element that gets dragged by default
51479         this.setDragElId(id);
51480
51481         // by default, clicked anchors will not start drag operations.
51482         this.invalidHandleTypes = { A: "A" };
51483         this.invalidHandleIds = {};
51484         this.invalidHandleClasses = [];
51485
51486         this.applyConfig();
51487
51488         this.handleOnAvailable();
51489     },
51490
51491     /**
51492      * Applies the configuration parameters that were passed into the constructor.
51493      * This is supposed to happen at each level through the inheritance chain.  So
51494      * a DDProxy implentation will execute apply config on DDProxy, DD, and
51495      * DragDrop in order to get all of the parameters that are available in
51496      * each object.
51497      * @method applyConfig
51498      */
51499     applyConfig: function() {
51500
51501         // configurable properties:
51502         //    padding, isTarget, maintainOffset, primaryButtonOnly
51503         this.padding           = this.config.padding || [0, 0, 0, 0];
51504         this.isTarget          = (this.config.isTarget !== false);
51505         this.maintainOffset    = (this.config.maintainOffset);
51506         this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
51507
51508     },
51509
51510     /**
51511      * Executed when the linked element is available
51512      * @method handleOnAvailable
51513      * @private
51514      */
51515     handleOnAvailable: function() {
51516         this.available = true;
51517         this.resetConstraints();
51518         this.onAvailable();
51519     },
51520
51521      /**
51522      * Configures the padding for the target zone in px.  Effectively expands
51523      * (or reduces) the virtual object size for targeting calculations.
51524      * Supports css-style shorthand; if only one parameter is passed, all sides
51525      * will have that padding, and if only two are passed, the top and bottom
51526      * will have the first param, the left and right the second.
51527      * @method setPadding
51528      * @param {int} iTop    Top pad
51529      * @param {int} iRight  Right pad
51530      * @param {int} iBot    Bot pad
51531      * @param {int} iLeft   Left pad
51532      */
51533     setPadding: function(iTop, iRight, iBot, iLeft) {
51534         // this.padding = [iLeft, iRight, iTop, iBot];
51535         if (!iRight && 0 !== iRight) {
51536             this.padding = [iTop, iTop, iTop, iTop];
51537         } else if (!iBot && 0 !== iBot) {
51538             this.padding = [iTop, iRight, iTop, iRight];
51539         } else {
51540             this.padding = [iTop, iRight, iBot, iLeft];
51541         }
51542     },
51543
51544     /**
51545      * Stores the initial placement of the linked element.
51546      * @method setInitPosition
51547      * @param {int} diffX   the X offset, default 0
51548      * @param {int} diffY   the Y offset, default 0
51549      */
51550     setInitPosition: function(diffX, diffY) {
51551         var el = this.getEl();
51552
51553         if (!this.DDMInstance.verifyEl(el)) {
51554             return;
51555         }
51556
51557         var dx = diffX || 0;
51558         var dy = diffY || 0;
51559
51560         var p = Ext.core.Element.getXY( el );
51561
51562         this.initPageX = p[0] - dx;
51563         this.initPageY = p[1] - dy;
51564
51565         this.lastPageX = p[0];
51566         this.lastPageY = p[1];
51567
51568         this.setStartPosition(p);
51569     },
51570
51571     /**
51572      * Sets the start position of the element.  This is set when the obj
51573      * is initialized, the reset when a drag is started.
51574      * @method setStartPosition
51575      * @param pos current position (from previous lookup)
51576      * @private
51577      */
51578     setStartPosition: function(pos) {
51579         var p = pos || Ext.core.Element.getXY( this.getEl() );
51580         this.deltaSetXY = null;
51581
51582         this.startPageX = p[0];
51583         this.startPageY = p[1];
51584     },
51585
51586     /**
51587      * Add this instance to a group of related drag/drop objects.  All
51588      * instances belong to at least one group, and can belong to as many
51589      * groups as needed.
51590      * @method addToGroup
51591      * @param sGroup {string} the name of the group
51592      */
51593     addToGroup: function(sGroup) {
51594         this.groups[sGroup] = true;
51595         this.DDMInstance.regDragDrop(this, sGroup);
51596     },
51597
51598     /**
51599      * Remove's this instance from the supplied interaction group
51600      * @method removeFromGroup
51601      * @param {string}  sGroup  The group to drop
51602      */
51603     removeFromGroup: function(sGroup) {
51604         if (this.groups[sGroup]) {
51605             delete this.groups[sGroup];
51606         }
51607
51608         this.DDMInstance.removeDDFromGroup(this, sGroup);
51609     },
51610
51611     /**
51612      * Allows you to specify that an element other than the linked element
51613      * will be moved with the cursor during a drag
51614      * @method setDragElId
51615      * @param id {string} the id of the element that will be used to initiate the drag
51616      */
51617     setDragElId: function(id) {
51618         this.dragElId = id;
51619     },
51620
51621     /**
51622      * Allows you to specify a child of the linked element that should be
51623      * used to initiate the drag operation.  An example of this would be if
51624      * you have a content div with text and links.  Clicking anywhere in the
51625      * content area would normally start the drag operation.  Use this method
51626      * to specify that an element inside of the content div is the element
51627      * that starts the drag operation.
51628      * @method setHandleElId
51629      * @param id {string} the id of the element that will be used to
51630      * initiate the drag.
51631      */
51632     setHandleElId: function(id) {
51633         if (typeof id !== "string") {
51634             id = Ext.id(id);
51635         }
51636         this.handleElId = id;
51637         this.DDMInstance.regHandle(this.id, id);
51638     },
51639
51640     /**
51641      * Allows you to set an element outside of the linked element as a drag
51642      * handle
51643      * @method setOuterHandleElId
51644      * @param id the id of the element that will be used to initiate the drag
51645      */
51646     setOuterHandleElId: function(id) {
51647         if (typeof id !== "string") {
51648             id = Ext.id(id);
51649         }
51650         Ext.EventManager.on(id, "mousedown", this.handleMouseDown, this);
51651         this.setHandleElId(id);
51652
51653         this.hasOuterHandles = true;
51654     },
51655
51656     /**
51657      * Remove all drag and drop hooks for this element
51658      * @method unreg
51659      */
51660     unreg: function() {
51661         Ext.EventManager.un(this.id, "mousedown", this.handleMouseDown, this);
51662         this._domRef = null;
51663         this.DDMInstance._remove(this);
51664     },
51665
51666     destroy : function(){
51667         this.unreg();
51668     },
51669
51670     /**
51671      * Returns true if this instance is locked, or the drag drop mgr is locked
51672      * (meaning that all drag/drop is disabled on the page.)
51673      * @method isLocked
51674      * @return {boolean} true if this obj or all drag/drop is locked, else
51675      * false
51676      */
51677     isLocked: function() {
51678         return (this.DDMInstance.isLocked() || this.locked);
51679     },
51680
51681     /**
51682      * Fired when this object is clicked
51683      * @method handleMouseDown
51684      * @param {Event} e
51685      * @param {Ext.dd.DragDrop} oDD the clicked dd object (this dd obj)
51686      * @private
51687      */
51688     handleMouseDown: function(e, oDD){
51689         if (this.primaryButtonOnly && e.button != 0) {
51690             return;
51691         }
51692
51693         if (this.isLocked()) {
51694             return;
51695         }
51696
51697         this.DDMInstance.refreshCache(this.groups);
51698
51699         var pt = e.getPoint();
51700         if (!this.hasOuterHandles && !this.DDMInstance.isOverTarget(pt, this) )  {
51701         } else {
51702             if (this.clickValidator(e)) {
51703                 // set the initial element position
51704                 this.setStartPosition();
51705                 this.b4MouseDown(e);
51706                 this.onMouseDown(e);
51707
51708                 this.DDMInstance.handleMouseDown(e, this);
51709
51710                 this.DDMInstance.stopEvent(e);
51711             } else {
51712
51713
51714             }
51715         }
51716     },
51717
51718     clickValidator: function(e) {
51719         var target = e.getTarget();
51720         return ( this.isValidHandleChild(target) &&
51721                     (this.id == this.handleElId ||
51722                         this.DDMInstance.handleWasClicked(target, this.id)) );
51723     },
51724
51725     /**
51726      * Allows you to specify a tag name that should not start a drag operation
51727      * when clicked.  This is designed to facilitate embedding links within a
51728      * drag handle that do something other than start the drag.
51729      * @method addInvalidHandleType
51730      * @param {string} tagName the type of element to exclude
51731      */
51732     addInvalidHandleType: function(tagName) {
51733         var type = tagName.toUpperCase();
51734         this.invalidHandleTypes[type] = type;
51735     },
51736
51737     /**
51738      * Lets you to specify an element id for a child of a drag handle
51739      * that should not initiate a drag
51740      * @method addInvalidHandleId
51741      * @param {string} id the element id of the element you wish to ignore
51742      */
51743     addInvalidHandleId: function(id) {
51744         if (typeof id !== "string") {
51745             id = Ext.id(id);
51746         }
51747         this.invalidHandleIds[id] = id;
51748     },
51749
51750     /**
51751      * Lets you specify a css class of elements that will not initiate a drag
51752      * @method addInvalidHandleClass
51753      * @param {string} cssClass the class of the elements you wish to ignore
51754      */
51755     addInvalidHandleClass: function(cssClass) {
51756         this.invalidHandleClasses.push(cssClass);
51757     },
51758
51759     /**
51760      * Unsets an excluded tag name set by addInvalidHandleType
51761      * @method removeInvalidHandleType
51762      * @param {string} tagName the type of element to unexclude
51763      */
51764     removeInvalidHandleType: function(tagName) {
51765         var type = tagName.toUpperCase();
51766         // this.invalidHandleTypes[type] = null;
51767         delete this.invalidHandleTypes[type];
51768     },
51769
51770     /**
51771      * Unsets an invalid handle id
51772      * @method removeInvalidHandleId
51773      * @param {string} id the id of the element to re-enable
51774      */
51775     removeInvalidHandleId: function(id) {
51776         if (typeof id !== "string") {
51777             id = Ext.id(id);
51778         }
51779         delete this.invalidHandleIds[id];
51780     },
51781
51782     /**
51783      * Unsets an invalid css class
51784      * @method removeInvalidHandleClass
51785      * @param {string} cssClass the class of the element(s) you wish to
51786      * re-enable
51787      */
51788     removeInvalidHandleClass: function(cssClass) {
51789         for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
51790             if (this.invalidHandleClasses[i] == cssClass) {
51791                 delete this.invalidHandleClasses[i];
51792             }
51793         }
51794     },
51795
51796     /**
51797      * Checks the tag exclusion list to see if this click should be ignored
51798      * @method isValidHandleChild
51799      * @param {HTMLElement} node the HTMLElement to evaluate
51800      * @return {boolean} true if this is a valid tag type, false if not
51801      */
51802     isValidHandleChild: function(node) {
51803
51804         var valid = true;
51805         // var n = (node.nodeName == "#text") ? node.parentNode : node;
51806         var nodeName;
51807         try {
51808             nodeName = node.nodeName.toUpperCase();
51809         } catch(e) {
51810             nodeName = node.nodeName;
51811         }
51812         valid = valid && !this.invalidHandleTypes[nodeName];
51813         valid = valid && !this.invalidHandleIds[node.id];
51814
51815         for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
51816             valid = !Ext.fly(node).hasCls(this.invalidHandleClasses[i]);
51817         }
51818
51819
51820         return valid;
51821
51822     },
51823
51824     /**
51825      * Create the array of horizontal tick marks if an interval was specified
51826      * in setXConstraint().
51827      * @method setXTicks
51828      * @private
51829      */
51830     setXTicks: function(iStartX, iTickSize) {
51831         this.xTicks = [];
51832         this.xTickSize = iTickSize;
51833
51834         var tickMap = {};
51835
51836         for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
51837             if (!tickMap[i]) {
51838                 this.xTicks[this.xTicks.length] = i;
51839                 tickMap[i] = true;
51840             }
51841         }
51842
51843         for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
51844             if (!tickMap[i]) {
51845                 this.xTicks[this.xTicks.length] = i;
51846                 tickMap[i] = true;
51847             }
51848         }
51849
51850         Ext.Array.sort(this.xTicks, this.DDMInstance.numericSort);
51851     },
51852
51853     /**
51854      * Create the array of vertical tick marks if an interval was specified in
51855      * setYConstraint().
51856      * @method setYTicks
51857      * @private
51858      */
51859     setYTicks: function(iStartY, iTickSize) {
51860         this.yTicks = [];
51861         this.yTickSize = iTickSize;
51862
51863         var tickMap = {};
51864
51865         for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
51866             if (!tickMap[i]) {
51867                 this.yTicks[this.yTicks.length] = i;
51868                 tickMap[i] = true;
51869             }
51870         }
51871
51872         for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
51873             if (!tickMap[i]) {
51874                 this.yTicks[this.yTicks.length] = i;
51875                 tickMap[i] = true;
51876             }
51877         }
51878
51879         Ext.Array.sort(this.yTicks, this.DDMInstance.numericSort);
51880     },
51881
51882     /**
51883      * By default, the element can be dragged any place on the screen.  Use
51884      * this method to limit the horizontal travel of the element.  Pass in
51885      * 0,0 for the parameters if you want to lock the drag to the y axis.
51886      * @method setXConstraint
51887      * @param {int} iLeft the number of pixels the element can move to the left
51888      * @param {int} iRight the number of pixels the element can move to the
51889      * right
51890      * @param {int} iTickSize optional parameter for specifying that the
51891      * element
51892      * should move iTickSize pixels at a time.
51893      */
51894     setXConstraint: function(iLeft, iRight, iTickSize) {
51895         this.leftConstraint = iLeft;
51896         this.rightConstraint = iRight;
51897
51898         this.minX = this.initPageX - iLeft;
51899         this.maxX = this.initPageX + iRight;
51900         if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
51901
51902         this.constrainX = true;
51903     },
51904
51905     /**
51906      * Clears any constraints applied to this instance.  Also clears ticks
51907      * since they can't exist independent of a constraint at this time.
51908      * @method clearConstraints
51909      */
51910     clearConstraints: function() {
51911         this.constrainX = false;
51912         this.constrainY = false;
51913         this.clearTicks();
51914     },
51915
51916     /**
51917      * Clears any tick interval defined for this instance
51918      * @method clearTicks
51919      */
51920     clearTicks: function() {
51921         this.xTicks = null;
51922         this.yTicks = null;
51923         this.xTickSize = 0;
51924         this.yTickSize = 0;
51925     },
51926
51927     /**
51928      * By default, the element can be dragged any place on the screen.  Set
51929      * this to limit the vertical travel of the element.  Pass in 0,0 for the
51930      * parameters if you want to lock the drag to the x axis.
51931      * @method setYConstraint
51932      * @param {int} iUp the number of pixels the element can move up
51933      * @param {int} iDown the number of pixels the element can move down
51934      * @param {int} iTickSize optional parameter for specifying that the
51935      * element should move iTickSize pixels at a time.
51936      */
51937     setYConstraint: function(iUp, iDown, iTickSize) {
51938         this.topConstraint = iUp;
51939         this.bottomConstraint = iDown;
51940
51941         this.minY = this.initPageY - iUp;
51942         this.maxY = this.initPageY + iDown;
51943         if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
51944
51945         this.constrainY = true;
51946
51947     },
51948
51949     /**
51950      * resetConstraints must be called if you manually reposition a dd element.
51951      * @method resetConstraints
51952      * @param {boolean} maintainOffset
51953      */
51954     resetConstraints: function() {
51955         // Maintain offsets if necessary
51956         if (this.initPageX || this.initPageX === 0) {
51957             // figure out how much this thing has moved
51958             var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
51959             var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
51960
51961             this.setInitPosition(dx, dy);
51962
51963         // This is the first time we have detected the element's position
51964         } else {
51965             this.setInitPosition();
51966         }
51967
51968         if (this.constrainX) {
51969             this.setXConstraint( this.leftConstraint,
51970                                  this.rightConstraint,
51971                                  this.xTickSize        );
51972         }
51973
51974         if (this.constrainY) {
51975             this.setYConstraint( this.topConstraint,
51976                                  this.bottomConstraint,
51977                                  this.yTickSize         );
51978         }
51979     },
51980
51981     /**
51982      * Normally the drag element is moved pixel by pixel, but we can specify
51983      * that it move a number of pixels at a time.  This method resolves the
51984      * location when we have it set up like this.
51985      * @method getTick
51986      * @param {int} val where we want to place the object
51987      * @param {int[]} tickArray sorted array of valid points
51988      * @return {int} the closest tick
51989      * @private
51990      */
51991     getTick: function(val, tickArray) {
51992         if (!tickArray) {
51993             // If tick interval is not defined, it is effectively 1 pixel,
51994             // so we return the value passed to us.
51995             return val;
51996         } else if (tickArray[0] >= val) {
51997             // The value is lower than the first tick, so we return the first
51998             // tick.
51999             return tickArray[0];
52000         } else {
52001             for (var i=0, len=tickArray.length; i<len; ++i) {
52002                 var next = i + 1;
52003                 if (tickArray[next] && tickArray[next] >= val) {
52004                     var diff1 = val - tickArray[i];
52005                     var diff2 = tickArray[next] - val;
52006                     return (diff2 > diff1) ? tickArray[i] : tickArray[next];
52007                 }
52008             }
52009
52010             // The value is larger than the last tick, so we return the last
52011             // tick.
52012             return tickArray[tickArray.length - 1];
52013         }
52014     },
52015
52016     /**
52017      * toString method
52018      * @method toString
52019      * @return {string} string representation of the dd obj
52020      */
52021     toString: function() {
52022         return ("DragDrop " + this.id);
52023     }
52024
52025 });
52026 /*
52027  * This is a derivative of the similarly named class in the YUI Library.
52028  * The original license:
52029  * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
52030  * Code licensed under the BSD License:
52031  * http://developer.yahoo.net/yui/license.txt
52032  */
52033
52034
52035 /**
52036  * @class Ext.dd.DD
52037  * A DragDrop implementation where the linked element follows the
52038  * mouse cursor during a drag.
52039  * @extends Ext.dd.DragDrop
52040  * @constructor
52041  * @param {String} id the id of the linked element
52042  * @param {String} sGroup the group of related DragDrop items
52043  * @param {object} config an object containing configurable attributes
52044  *                Valid properties for DD:
52045  *                    scroll
52046  */
52047
52048 Ext.define('Ext.dd.DD', {
52049     extend: 'Ext.dd.DragDrop',
52050     requires: ['Ext.dd.DragDropManager'],
52051     constructor: function(id, sGroup, config) {
52052         if (id) {
52053             this.init(id, sGroup, config);
52054         }
52055     },
52056
52057     /**
52058      * When set to true, the utility automatically tries to scroll the browser
52059      * window when a drag and drop element is dragged near the viewport boundary.
52060      * Defaults to true.
52061      * @property scroll
52062      * @type boolean
52063      */
52064     scroll: true,
52065
52066     /**
52067      * Sets the pointer offset to the distance between the linked element's top
52068      * left corner and the location the element was clicked
52069      * @method autoOffset
52070      * @param {int} iPageX the X coordinate of the click
52071      * @param {int} iPageY the Y coordinate of the click
52072      */
52073     autoOffset: function(iPageX, iPageY) {
52074         var x = iPageX - this.startPageX;
52075         var y = iPageY - this.startPageY;
52076         this.setDelta(x, y);
52077     },
52078
52079     /**
52080      * Sets the pointer offset.  You can call this directly to force the
52081      * offset to be in a particular location (e.g., pass in 0,0 to set it
52082      * to the center of the object)
52083      * @method setDelta
52084      * @param {int} iDeltaX the distance from the left
52085      * @param {int} iDeltaY the distance from the top
52086      */
52087     setDelta: function(iDeltaX, iDeltaY) {
52088         this.deltaX = iDeltaX;
52089         this.deltaY = iDeltaY;
52090     },
52091
52092     /**
52093      * Sets the drag element to the location of the mousedown or click event,
52094      * maintaining the cursor location relative to the location on the element
52095      * that was clicked.  Override this if you want to place the element in a
52096      * location other than where the cursor is.
52097      * @method setDragElPos
52098      * @param {int} iPageX the X coordinate of the mousedown or drag event
52099      * @param {int} iPageY the Y coordinate of the mousedown or drag event
52100      */
52101     setDragElPos: function(iPageX, iPageY) {
52102         // the first time we do this, we are going to check to make sure
52103         // the element has css positioning
52104
52105         var el = this.getDragEl();
52106         this.alignElWithMouse(el, iPageX, iPageY);
52107     },
52108
52109     /**
52110      * Sets the element to the location of the mousedown or click event,
52111      * maintaining the cursor location relative to the location on the element
52112      * that was clicked.  Override this if you want to place the element in a
52113      * location other than where the cursor is.
52114      * @method alignElWithMouse
52115      * @param {HTMLElement} el the element to move
52116      * @param {int} iPageX the X coordinate of the mousedown or drag event
52117      * @param {int} iPageY the Y coordinate of the mousedown or drag event
52118      */
52119     alignElWithMouse: function(el, iPageX, iPageY) {
52120         var oCoord = this.getTargetCoord(iPageX, iPageY),
52121             fly = el.dom ? el : Ext.fly(el, '_dd'),
52122             elSize = fly.getSize(),
52123             EL = Ext.core.Element,
52124             vpSize;
52125
52126         if (!this.deltaSetXY) {
52127             vpSize = this.cachedViewportSize = { width: EL.getDocumentWidth(), height: EL.getDocumentHeight() };
52128             var aCoord = [
52129                 Math.max(0, Math.min(oCoord.x, vpSize.width - elSize.width)),
52130                 Math.max(0, Math.min(oCoord.y, vpSize.height - elSize.height))
52131             ];
52132             fly.setXY(aCoord);
52133             var newLeft = fly.getLeft(true);
52134             var newTop  = fly.getTop(true);
52135             this.deltaSetXY = [newLeft - oCoord.x, newTop - oCoord.y];
52136         } else {
52137             vpSize = this.cachedViewportSize;
52138             fly.setLeftTop(
52139                 Math.max(0, Math.min(oCoord.x + this.deltaSetXY[0], vpSize.width - elSize.width)),
52140                 Math.max(0, Math.min(oCoord.y + this.deltaSetXY[1], vpSize.height - elSize.height))
52141             );
52142         }
52143
52144         this.cachePosition(oCoord.x, oCoord.y);
52145         this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
52146         return oCoord;
52147     },
52148
52149     /**
52150      * Saves the most recent position so that we can reset the constraints and
52151      * tick marks on-demand.  We need to know this so that we can calculate the
52152      * number of pixels the element is offset from its original position.
52153      * @method cachePosition
52154      * @param iPageX the current x position (optional, this just makes it so we
52155      * don't have to look it up again)
52156      * @param iPageY the current y position (optional, this just makes it so we
52157      * don't have to look it up again)
52158      */
52159     cachePosition: function(iPageX, iPageY) {
52160         if (iPageX) {
52161             this.lastPageX = iPageX;
52162             this.lastPageY = iPageY;
52163         } else {
52164             var aCoord = Ext.core.Element.getXY(this.getEl());
52165             this.lastPageX = aCoord[0];
52166             this.lastPageY = aCoord[1];
52167         }
52168     },
52169
52170     /**
52171      * Auto-scroll the window if the dragged object has been moved beyond the
52172      * visible window boundary.
52173      * @method autoScroll
52174      * @param {int} x the drag element's x position
52175      * @param {int} y the drag element's y position
52176      * @param {int} h the height of the drag element
52177      * @param {int} w the width of the drag element
52178      * @private
52179      */
52180     autoScroll: function(x, y, h, w) {
52181
52182         if (this.scroll) {
52183             // The client height
52184             var clientH = Ext.core.Element.getViewHeight();
52185
52186             // The client width
52187             var clientW = Ext.core.Element.getViewWidth();
52188
52189             // The amt scrolled down
52190             var st = this.DDMInstance.getScrollTop();
52191
52192             // The amt scrolled right
52193             var sl = this.DDMInstance.getScrollLeft();
52194
52195             // Location of the bottom of the element
52196             var bot = h + y;
52197
52198             // Location of the right of the element
52199             var right = w + x;
52200
52201             // The distance from the cursor to the bottom of the visible area,
52202             // adjusted so that we don't scroll if the cursor is beyond the
52203             // element drag constraints
52204             var toBot = (clientH + st - y - this.deltaY);
52205
52206             // The distance from the cursor to the right of the visible area
52207             var toRight = (clientW + sl - x - this.deltaX);
52208
52209
52210             // How close to the edge the cursor must be before we scroll
52211             // var thresh = (document.all) ? 100 : 40;
52212             var thresh = 40;
52213
52214             // How many pixels to scroll per autoscroll op.  This helps to reduce
52215             // clunky scrolling. IE is more sensitive about this ... it needs this
52216             // value to be higher.
52217             var scrAmt = (document.all) ? 80 : 30;
52218
52219             // Scroll down if we are near the bottom of the visible page and the
52220             // obj extends below the crease
52221             if ( bot > clientH && toBot < thresh ) {
52222                 window.scrollTo(sl, st + scrAmt);
52223             }
52224
52225             // Scroll up if the window is scrolled down and the top of the object
52226             // goes above the top border
52227             if ( y < st && st > 0 && y - st < thresh ) {
52228                 window.scrollTo(sl, st - scrAmt);
52229             }
52230
52231             // Scroll right if the obj is beyond the right border and the cursor is
52232             // near the border.
52233             if ( right > clientW && toRight < thresh ) {
52234                 window.scrollTo(sl + scrAmt, st);
52235             }
52236
52237             // Scroll left if the window has been scrolled to the right and the obj
52238             // extends past the left border
52239             if ( x < sl && sl > 0 && x - sl < thresh ) {
52240                 window.scrollTo(sl - scrAmt, st);
52241             }
52242         }
52243     },
52244
52245     /**
52246      * Finds the location the element should be placed if we want to move
52247      * it to where the mouse location less the click offset would place us.
52248      * @method getTargetCoord
52249      * @param {int} iPageX the X coordinate of the click
52250      * @param {int} iPageY the Y coordinate of the click
52251      * @return an object that contains the coordinates (Object.x and Object.y)
52252      * @private
52253      */
52254     getTargetCoord: function(iPageX, iPageY) {
52255         var x = iPageX - this.deltaX;
52256         var y = iPageY - this.deltaY;
52257
52258         if (this.constrainX) {
52259             if (x < this.minX) {
52260                 x = this.minX;
52261             }
52262             if (x > this.maxX) {
52263                 x = this.maxX;
52264             }
52265         }
52266
52267         if (this.constrainY) {
52268             if (y < this.minY) {
52269                 y = this.minY;
52270             }
52271             if (y > this.maxY) {
52272                 y = this.maxY;
52273             }
52274         }
52275
52276         x = this.getTick(x, this.xTicks);
52277         y = this.getTick(y, this.yTicks);
52278
52279
52280         return {x: x, y: y};
52281     },
52282
52283     /**
52284      * Sets up config options specific to this class. Overrides
52285      * Ext.dd.DragDrop, but all versions of this method through the
52286      * inheritance chain are called
52287      */
52288     applyConfig: function() {
52289         this.callParent();
52290         this.scroll = (this.config.scroll !== false);
52291     },
52292
52293     /**
52294      * Event that fires prior to the onMouseDown event.  Overrides
52295      * Ext.dd.DragDrop.
52296      */
52297     b4MouseDown: function(e) {
52298         // this.resetConstraints();
52299         this.autoOffset(e.getPageX(), e.getPageY());
52300     },
52301
52302     /**
52303      * Event that fires prior to the onDrag event.  Overrides
52304      * Ext.dd.DragDrop.
52305      */
52306     b4Drag: function(e) {
52307         this.setDragElPos(e.getPageX(), e.getPageY());
52308     },
52309
52310     toString: function() {
52311         return ("DD " + this.id);
52312     }
52313
52314     //////////////////////////////////////////////////////////////////////////
52315     // Debugging ygDragDrop events that can be overridden
52316     //////////////////////////////////////////////////////////////////////////
52317     /*
52318     startDrag: function(x, y) {
52319     },
52320
52321     onDrag: function(e) {
52322     },
52323
52324     onDragEnter: function(e, id) {
52325     },
52326
52327     onDragOver: function(e, id) {
52328     },
52329
52330     onDragOut: function(e, id) {
52331     },
52332
52333     onDragDrop: function(e, id) {
52334     },
52335
52336     endDrag: function(e) {
52337     }
52338
52339     */
52340
52341 });
52342
52343 /*
52344  * This is a derivative of the similarly named class in the YUI Library.
52345  * The original license:
52346  * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
52347  * Code licensed under the BSD License:
52348  * http://developer.yahoo.net/yui/license.txt
52349  */
52350
52351 /**
52352  * @class Ext.dd.DDProxy
52353  * A DragDrop implementation that inserts an empty, bordered div into
52354  * the document that follows the cursor during drag operations.  At the time of
52355  * the click, the frame div is resized to the dimensions of the linked html
52356  * element, and moved to the exact location of the linked element.
52357  *
52358  * References to the "frame" element refer to the single proxy element that
52359  * was created to be dragged in place of all DDProxy elements on the
52360  * page.
52361  *
52362  * @extends Ext.dd.DD
52363  * @constructor
52364  * @param {String} id the id of the linked html element
52365  * @param {String} sGroup the group of related DragDrop objects
52366  * @param {object} config an object containing configurable attributes
52367  *                Valid properties for DDProxy in addition to those in DragDrop:
52368  *                   resizeFrame, centerFrame, dragElId
52369  */
52370 Ext.define('Ext.dd.DDProxy', {
52371     extend: 'Ext.dd.DD',
52372
52373     statics: {
52374         /**
52375          * The default drag frame div id
52376          * @property Ext.dd.DDProxy.dragElId
52377          * @type String
52378          * @static
52379          */
52380         dragElId: "ygddfdiv"
52381     },
52382
52383     constructor: function(id, sGroup, config) {
52384         if (id) {
52385             this.init(id, sGroup, config);
52386             this.initFrame();
52387         }
52388     },
52389
52390     /**
52391      * By default we resize the drag frame to be the same size as the element
52392      * we want to drag (this is to get the frame effect).  We can turn it off
52393      * if we want a different behavior.
52394      * @property resizeFrame
52395      * @type boolean
52396      */
52397     resizeFrame: true,
52398
52399     /**
52400      * By default the frame is positioned exactly where the drag element is, so
52401      * we use the cursor offset provided by Ext.dd.DD.  Another option that works only if
52402      * you do not have constraints on the obj is to have the drag frame centered
52403      * around the cursor.  Set centerFrame to true for this effect.
52404      * @property centerFrame
52405      * @type boolean
52406      */
52407     centerFrame: false,
52408
52409     /**
52410      * Creates the proxy element if it does not yet exist
52411      * @method createFrame
52412      */
52413     createFrame: function() {
52414         var self = this;
52415         var body = document.body;
52416
52417         if (!body || !body.firstChild) {
52418             setTimeout( function() { self.createFrame(); }, 50 );
52419             return;
52420         }
52421
52422         var div = this.getDragEl();
52423
52424         if (!div) {
52425             div    = document.createElement("div");
52426             div.id = this.dragElId;
52427             var s  = div.style;
52428
52429             s.position   = "absolute";
52430             s.visibility = "hidden";
52431             s.cursor     = "move";
52432             s.border     = "2px solid #aaa";
52433             s.zIndex     = 999;
52434
52435             // appendChild can blow up IE if invoked prior to the window load event
52436             // while rendering a table.  It is possible there are other scenarios
52437             // that would cause this to happen as well.
52438             body.insertBefore(div, body.firstChild);
52439         }
52440     },
52441
52442     /**
52443      * Initialization for the drag frame element.  Must be called in the
52444      * constructor of all subclasses
52445      * @method initFrame
52446      */
52447     initFrame: function() {
52448         this.createFrame();
52449     },
52450
52451     applyConfig: function() {
52452         this.callParent();
52453
52454         this.resizeFrame = (this.config.resizeFrame !== false);
52455         this.centerFrame = (this.config.centerFrame);
52456         this.setDragElId(this.config.dragElId || Ext.dd.DDProxy.dragElId);
52457     },
52458
52459     /**
52460      * Resizes the drag frame to the dimensions of the clicked object, positions
52461      * it over the object, and finally displays it
52462      * @method showFrame
52463      * @param {int} iPageX X click position
52464      * @param {int} iPageY Y click position
52465      * @private
52466      */
52467     showFrame: function(iPageX, iPageY) {
52468         var el = this.getEl();
52469         var dragEl = this.getDragEl();
52470         var s = dragEl.style;
52471
52472         this._resizeProxy();
52473
52474         if (this.centerFrame) {
52475             this.setDelta( Math.round(parseInt(s.width,  10)/2),
52476                            Math.round(parseInt(s.height, 10)/2) );
52477         }
52478
52479         this.setDragElPos(iPageX, iPageY);
52480
52481         Ext.fly(dragEl).show();
52482     },
52483
52484     /**
52485      * The proxy is automatically resized to the dimensions of the linked
52486      * element when a drag is initiated, unless resizeFrame is set to false
52487      * @method _resizeProxy
52488      * @private
52489      */
52490     _resizeProxy: function() {
52491         if (this.resizeFrame) {
52492             var el = this.getEl();
52493             Ext.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
52494         }
52495     },
52496
52497     // overrides Ext.dd.DragDrop
52498     b4MouseDown: function(e) {
52499         var x = e.getPageX();
52500         var y = e.getPageY();
52501         this.autoOffset(x, y);
52502         this.setDragElPos(x, y);
52503     },
52504
52505     // overrides Ext.dd.DragDrop
52506     b4StartDrag: function(x, y) {
52507         // show the drag frame
52508         this.showFrame(x, y);
52509     },
52510
52511     // overrides Ext.dd.DragDrop
52512     b4EndDrag: function(e) {
52513         Ext.fly(this.getDragEl()).hide();
52514     },
52515
52516     // overrides Ext.dd.DragDrop
52517     // By default we try to move the element to the last location of the frame.
52518     // This is so that the default behavior mirrors that of Ext.dd.DD.
52519     endDrag: function(e) {
52520
52521         var lel = this.getEl();
52522         var del = this.getDragEl();
52523
52524         // Show the drag frame briefly so we can get its position
52525         del.style.visibility = "";
52526
52527         this.beforeMove();
52528         // Hide the linked element before the move to get around a Safari
52529         // rendering bug.
52530         lel.style.visibility = "hidden";
52531         Ext.dd.DDM.moveToEl(lel, del);
52532         del.style.visibility = "hidden";
52533         lel.style.visibility = "";
52534
52535         this.afterDrag();
52536     },
52537
52538     beforeMove : function(){
52539
52540     },
52541
52542     afterDrag : function(){
52543
52544     },
52545
52546     toString: function() {
52547         return ("DDProxy " + this.id);
52548     }
52549
52550 });
52551
52552 /**
52553  * @class Ext.dd.DragSource
52554  * @extends Ext.dd.DDProxy
52555  * A simple class that provides the basic implementation needed to make any element draggable.
52556  * @constructor
52557  * @param {Mixed} el The container element
52558  * @param {Object} config
52559  */
52560 Ext.define('Ext.dd.DragSource', {
52561     extend: 'Ext.dd.DDProxy',
52562     requires: [
52563         'Ext.dd.StatusProxy',
52564         'Ext.dd.DragDropManager'
52565     ],
52566
52567     /**
52568      * @cfg {String} ddGroup
52569      * A named drag drop group to which this object belongs.  If a group is specified, then this object will only
52570      * interact with other drag drop objects in the same group (defaults to undefined).
52571      */
52572
52573     /**
52574      * @cfg {String} dropAllowed
52575      * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
52576      */
52577
52578     dropAllowed : Ext.baseCSSPrefix + 'dd-drop-ok',
52579     /**
52580      * @cfg {String} dropNotAllowed
52581      * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
52582      */
52583     dropNotAllowed : Ext.baseCSSPrefix + 'dd-drop-nodrop',
52584
52585     /**
52586      * @cfg {Boolean} animRepair
52587      * Defaults to true. If true, animates the proxy element back to the position of the handle element used to trigger the drag.
52588      */
52589     animRepair: true,
52590
52591     /**
52592      * @cfg {String} repairHighlightColor The color to use when visually highlighting the drag source in the afterRepair
52593      * method after a failed drop (defaults to 'c3daf9' - light blue). The color must be a 6 digit hex value, without
52594      * a preceding '#'.
52595      */
52596     repairHighlightColor: 'c3daf9',
52597
52598     constructor: function(el, config) {
52599         this.el = Ext.get(el);
52600         if(!this.dragData){
52601             this.dragData = {};
52602         }
52603
52604         Ext.apply(this, config);
52605
52606         if(!this.proxy){
52607             this.proxy = Ext.create('Ext.dd.StatusProxy', {
52608                 animRepair: this.animRepair
52609             });
52610         }
52611         this.callParent([this.el.dom, this.ddGroup || this.group,
52612               {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true}]);
52613
52614         this.dragging = false;
52615     },
52616
52617     /**
52618      * Returns the data object associated with this drag source
52619      * @return {Object} data An object containing arbitrary data
52620      */
52621     getDragData : function(e){
52622         return this.dragData;
52623     },
52624
52625     // private
52626     onDragEnter : function(e, id){
52627         var target = Ext.dd.DragDropManager.getDDById(id);
52628         this.cachedTarget = target;
52629         if (this.beforeDragEnter(target, e, id) !== false) {
52630             if (target.isNotifyTarget) {
52631                 var status = target.notifyEnter(this, e, this.dragData);
52632                 this.proxy.setStatus(status);
52633             } else {
52634                 this.proxy.setStatus(this.dropAllowed);
52635             }
52636
52637             if (this.afterDragEnter) {
52638                 /**
52639                  * An empty function by default, but provided so that you can perform a custom action
52640                  * when the dragged item enters the drop target by providing an implementation.
52641                  * @param {Ext.dd.DragDrop} target The drop target
52642                  * @param {Event} e The event object
52643                  * @param {String} id The id of the dragged element
52644                  * @method afterDragEnter
52645                  */
52646                 this.afterDragEnter(target, e, id);
52647             }
52648         }
52649     },
52650
52651     /**
52652      * An empty function by default, but provided so that you can perform a custom action
52653      * before the dragged item enters the drop target and optionally cancel the onDragEnter.
52654      * @param {Ext.dd.DragDrop} target The drop target
52655      * @param {Event} e The event object
52656      * @param {String} id The id of the dragged element
52657      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
52658      */
52659     beforeDragEnter: function(target, e, id) {
52660         return true;
52661     },
52662
52663     // private
52664     alignElWithMouse: function() {
52665         this.callParent(arguments);
52666         this.proxy.sync();
52667     },
52668
52669     // private
52670     onDragOver: function(e, id) {
52671         var target = this.cachedTarget || Ext.dd.DragDropManager.getDDById(id);
52672         if (this.beforeDragOver(target, e, id) !== false) {
52673             if(target.isNotifyTarget){
52674                 var status = target.notifyOver(this, e, this.dragData);
52675                 this.proxy.setStatus(status);
52676             }
52677
52678             if (this.afterDragOver) {
52679                 /**
52680                  * An empty function by default, but provided so that you can perform a custom action
52681                  * while the dragged item is over the drop target by providing an implementation.
52682                  * @param {Ext.dd.DragDrop} target The drop target
52683                  * @param {Event} e The event object
52684                  * @param {String} id The id of the dragged element
52685                  * @method afterDragOver
52686                  */
52687                 this.afterDragOver(target, e, id);
52688             }
52689         }
52690     },
52691
52692     /**
52693      * An empty function by default, but provided so that you can perform a custom action
52694      * while the dragged item is over the drop target and optionally cancel the onDragOver.
52695      * @param {Ext.dd.DragDrop} target The drop target
52696      * @param {Event} e The event object
52697      * @param {String} id The id of the dragged element
52698      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
52699      */
52700     beforeDragOver: function(target, e, id) {
52701         return true;
52702     },
52703
52704     // private
52705     onDragOut: function(e, id) {
52706         var target = this.cachedTarget || Ext.dd.DragDropManager.getDDById(id);
52707         if (this.beforeDragOut(target, e, id) !== false) {
52708             if (target.isNotifyTarget) {
52709                 target.notifyOut(this, e, this.dragData);
52710             }
52711             this.proxy.reset();
52712             if (this.afterDragOut) {
52713                 /**
52714                  * An empty function by default, but provided so that you can perform a custom action
52715                  * after the dragged item is dragged out of the target without dropping.
52716                  * @param {Ext.dd.DragDrop} target The drop target
52717                  * @param {Event} e The event object
52718                  * @param {String} id The id of the dragged element
52719                  * @method afterDragOut
52720                  */
52721                 this.afterDragOut(target, e, id);
52722             }
52723         }
52724         this.cachedTarget = null;
52725     },
52726
52727     /**
52728      * An empty function by default, but provided so that you can perform a custom action before the dragged
52729      * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
52730      * @param {Ext.dd.DragDrop} target The drop target
52731      * @param {Event} e The event object
52732      * @param {String} id The id of the dragged element
52733      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
52734      */
52735     beforeDragOut: function(target, e, id){
52736         return true;
52737     },
52738
52739     // private
52740     onDragDrop: function(e, id){
52741         var target = this.cachedTarget || Ext.dd.DragDropManager.getDDById(id);
52742         if (this.beforeDragDrop(target, e, id) !== false) {
52743             if (target.isNotifyTarget) {
52744                 if (target.notifyDrop(this, e, this.dragData) !== false) { // valid drop?
52745                     this.onValidDrop(target, e, id);
52746                 } else {
52747                     this.onInvalidDrop(target, e, id);
52748                 }
52749             } else {
52750                 this.onValidDrop(target, e, id);
52751             }
52752
52753             if (this.afterDragDrop) {
52754                 /**
52755                  * An empty function by default, but provided so that you can perform a custom action
52756                  * after a valid drag drop has occurred by providing an implementation.
52757                  * @param {Ext.dd.DragDrop} target The drop target
52758                  * @param {Event} e The event object
52759                  * @param {String} id The id of the dropped element
52760                  * @method afterDragDrop
52761                  */
52762                 this.afterDragDrop(target, e, id);
52763             }
52764         }
52765         delete this.cachedTarget;
52766     },
52767
52768     /**
52769      * An empty function by default, but provided so that you can perform a custom action before the dragged
52770      * item is dropped onto the target and optionally cancel the onDragDrop.
52771      * @param {Ext.dd.DragDrop} target The drop target
52772      * @param {Event} e The event object
52773      * @param {String} id The id of the dragged element
52774      * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
52775      */
52776     beforeDragDrop: function(target, e, id){
52777         return true;
52778     },
52779
52780     // private
52781     onValidDrop: function(target, e, id){
52782         this.hideProxy();
52783         if(this.afterValidDrop){
52784             /**
52785              * An empty function by default, but provided so that you can perform a custom action
52786              * after a valid drop has occurred by providing an implementation.
52787              * @param {Object} target The target DD
52788              * @param {Event} e The event object
52789              * @param {String} id The id of the dropped element
52790              * @method afterInvalidDrop
52791              */
52792             this.afterValidDrop(target, e, id);
52793         }
52794     },
52795
52796     // private
52797     getRepairXY: function(e, data){
52798         return this.el.getXY();
52799     },
52800
52801     // private
52802     onInvalidDrop: function(target, e, id) {
52803         this.beforeInvalidDrop(target, e, id);
52804         if (this.cachedTarget) {
52805             if(this.cachedTarget.isNotifyTarget){
52806                 this.cachedTarget.notifyOut(this, e, this.dragData);
52807             }
52808             this.cacheTarget = null;
52809         }
52810         this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
52811
52812         if (this.afterInvalidDrop) {
52813             /**
52814              * An empty function by default, but provided so that you can perform a custom action
52815              * after an invalid drop has occurred by providing an implementation.
52816              * @param {Event} e The event object
52817              * @param {String} id The id of the dropped element
52818              * @method afterInvalidDrop
52819              */
52820             this.afterInvalidDrop(e, id);
52821         }
52822     },
52823
52824     // private
52825     afterRepair: function() {
52826         var me = this;
52827         if (Ext.enableFx) {
52828             me.el.highlight(me.repairHighlightColor);
52829         }
52830         me.dragging = false;
52831     },
52832
52833     /**
52834      * An empty function by default, but provided so that you can perform a custom action after an invalid
52835      * drop has occurred.
52836      * @param {Ext.dd.DragDrop} target The drop target
52837      * @param {Event} e The event object
52838      * @param {String} id The id of the dragged element
52839      * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
52840      */
52841     beforeInvalidDrop: function(target, e, id) {
52842         return true;
52843     },
52844
52845     // private
52846     handleMouseDown: function(e) {
52847         if (this.dragging) {
52848             return;
52849         }
52850         var data = this.getDragData(e);
52851         if (data && this.onBeforeDrag(data, e) !== false) {
52852             this.dragData = data;
52853             this.proxy.stop();
52854             this.callParent(arguments);
52855         }
52856     },
52857
52858     /**
52859      * An empty function by default, but provided so that you can perform a custom action before the initial
52860      * drag event begins and optionally cancel it.
52861      * @param {Object} data An object containing arbitrary data to be shared with drop targets
52862      * @param {Event} e The event object
52863      * @return {Boolean} isValid True if the drag event is valid, else false to cancel
52864      */
52865     onBeforeDrag: function(data, e){
52866         return true;
52867     },
52868
52869     /**
52870      * An empty function by default, but provided so that you can perform a custom action once the initial
52871      * drag event has begun.  The drag cannot be canceled from this function.
52872      * @param {Number} x The x position of the click on the dragged object
52873      * @param {Number} y The y position of the click on the dragged object
52874      */
52875     onStartDrag: Ext.emptyFn,
52876
52877     // private override
52878     startDrag: function(x, y) {
52879         this.proxy.reset();
52880         this.dragging = true;
52881         this.proxy.update("");
52882         this.onInitDrag(x, y);
52883         this.proxy.show();
52884     },
52885
52886     // private
52887     onInitDrag: function(x, y) {
52888         var clone = this.el.dom.cloneNode(true);
52889         clone.id = Ext.id(); // prevent duplicate ids
52890         this.proxy.update(clone);
52891         this.onStartDrag(x, y);
52892         return true;
52893     },
52894
52895     /**
52896      * Returns the drag source's underlying {@link Ext.dd.StatusProxy}
52897      * @return {Ext.dd.StatusProxy} proxy The StatusProxy
52898      */
52899     getProxy: function() {
52900         return this.proxy;
52901     },
52902
52903     /**
52904      * Hides the drag source's {@link Ext.dd.StatusProxy}
52905      */
52906     hideProxy: function() {
52907         this.proxy.hide();
52908         this.proxy.reset(true);
52909         this.dragging = false;
52910     },
52911
52912     // private
52913     triggerCacheRefresh: function() {
52914         Ext.dd.DDM.refreshCache(this.groups);
52915     },
52916
52917     // private - override to prevent hiding
52918     b4EndDrag: function(e) {
52919     },
52920
52921     // private - override to prevent moving
52922     endDrag : function(e){
52923         this.onEndDrag(this.dragData, e);
52924     },
52925
52926     // private
52927     onEndDrag : function(data, e){
52928     },
52929
52930     // private - pin to cursor
52931     autoOffset : function(x, y) {
52932         this.setDelta(-12, -20);
52933     },
52934
52935     destroy: function(){
52936         this.callParent();
52937         Ext.destroy(this.proxy);
52938     }
52939 });
52940
52941 // private - DD implementation for Panels
52942 Ext.define('Ext.panel.DD', {
52943     extend: 'Ext.dd.DragSource',
52944     requires: ['Ext.panel.Proxy'],
52945
52946     constructor : function(panel, cfg){
52947         this.panel = panel;
52948         this.dragData = {panel: panel};
52949         this.proxy = Ext.create('Ext.panel.Proxy', panel, cfg);
52950
52951         this.callParent([panel.el, cfg]);
52952
52953         Ext.defer(function() {
52954             var header = panel.header,
52955                 el = panel.body;
52956
52957             if(header){
52958                 this.setHandleElId(header.id);
52959                 el = header.el;
52960             }
52961             el.setStyle('cursor', 'move');
52962             this.scroll = false;
52963         }, 200, this);
52964     },
52965
52966     showFrame: Ext.emptyFn,
52967     startDrag: Ext.emptyFn,
52968     b4StartDrag: function(x, y) {
52969         this.proxy.show();
52970     },
52971     b4MouseDown: function(e) {
52972         var x = e.getPageX(),
52973             y = e.getPageY();
52974         this.autoOffset(x, y);
52975     },
52976     onInitDrag : function(x, y){
52977         this.onStartDrag(x, y);
52978         return true;
52979     },
52980     createFrame : Ext.emptyFn,
52981     getDragEl : function(e){
52982         return this.proxy.ghost.el.dom;
52983     },
52984     endDrag : function(e){
52985         this.proxy.hide();
52986         this.panel.saveState();
52987     },
52988
52989     autoOffset : function(x, y) {
52990         x -= this.startPageX;
52991         y -= this.startPageY;
52992         this.setDelta(x, y);
52993     }
52994 });
52995
52996 /**
52997  * @class Ext.layout.component.Dock
52998  * @extends Ext.layout.component.AbstractDock
52999  * @private
53000  */
53001 Ext.define('Ext.layout.component.Dock', {
53002
53003     /* Begin Definitions */
53004
53005     alias: ['layout.dock'],
53006
53007     extend: 'Ext.layout.component.AbstractDock'
53008
53009     /* End Definitions */
53010
53011 });
53012 /**
53013  * @class Ext.panel.Panel
53014  * @extends Ext.panel.AbstractPanel
53015  * <p>Panel is a container that has specific functionality and structural components that make
53016  * it the perfect building block for application-oriented user interfaces.</p>
53017  * <p>Panels are, by virtue of their inheritance from {@link Ext.container.Container}, capable
53018  * of being configured with a {@link Ext.container.Container#layout layout}, and containing child Components.</p>
53019  * <p>When either specifying child {@link Ext.Component#items items} of a Panel, or dynamically {@link Ext.container.Container#add adding} Components
53020  * to a Panel, remember to consider how you wish the Panel to arrange those child elements, and whether
53021  * those child elements need to be sized using one of Ext&#39;s built-in <code><b>{@link Ext.container.Container#layout layout}</b></code> schemes. By
53022  * default, Panels use the {@link Ext.layout.container.Auto Auto} scheme. This simply renders
53023  * child components, appending them one after the other inside the Container, and <b>does not apply any sizing</b>
53024  * at all.</p>
53025  * {@img Ext.panel.Panel/panel.png Panel components}
53026  * <p>A Panel may also contain {@link #bbar bottom} and {@link #tbar top} toolbars, along with separate
53027  * {@link #header}, {@link #footer} and {@link #body} sections (see {@link #frame} for additional
53028  * information).</p>
53029  * <p>Panel also provides built-in {@link #collapsible collapsible, expandable} and {@link #closable} behavior.
53030  * Panels can be easily dropped into any {@link Ext.container.Container Container} or layout, and the
53031  * layout and rendering pipeline is {@link Ext.container.Container#add completely managed by the framework}.</p>
53032  * <p><b>Note:</b> By default, the <code>{@link #closable close}</code> header tool <i>destroys</i> the Panel resulting in removal of the Panel
53033  * and the destruction of any descendant Components. This makes the Panel object, and all its descendants <b>unusable</b>. To enable the close
53034  * tool to simply <i>hide</i> a Panel for later re-use, configure the Panel with <b><code>{@link #closeAction closeAction: 'hide'}</code></b>.</p>
53035  * <p>Usually, Panels are used as constituents within an application, in which case, they would be used as child items of Containers,
53036  * and would themselves use Ext.Components as child {@link #items}. However to illustrate simply rendering a Panel into the document,
53037  * here&#39;s how to do it:<pre><code>
53038 Ext.create('Ext.panel.Panel', {
53039     title: 'Hello',
53040     width: 200,
53041     html: '&lt;p&gt;World!&lt;/p&gt;',
53042     renderTo: document.body
53043 });
53044 </code></pre></p>
53045  * <p>A more realistic scenario is a Panel created to house input fields which will not be rendered, but used as a constituent part of a Container:<pre><code>
53046 var filterPanel = Ext.create('Ext.panel.Panel', {
53047     bodyPadding: 5,  // Don&#39;t want content to crunch against the borders
53048     title: 'Filters',
53049     items: [{
53050         xtype: 'datefield',
53051         fieldLabel: 'Start date'
53052     }, {
53053         xtype: 'datefield',
53054         fieldLabel: 'End date'
53055     }]
53056 });
53057 </code></pre></p>
53058  * <p>Note that the Panel above is not configured to render into the document, nor is it configured with a size or position. In a real world scenario,
53059  * the Container into which the Panel is added will use a {@link #layout} to render, size and position its child Components.</p>
53060  * <p>Panels will often use specific {@link #layout}s to provide an application with shape and structure by containing and arranging child
53061  * Components: <pre><code>
53062 var resultsPanel = Ext.create('Ext.panel.Panel', {
53063     title: 'Results',
53064     width: 600,
53065     height: 400,
53066     renderTo: document.body,
53067     layout: {
53068         type: 'vbox',       // Arrange child items vertically
53069         align: 'stretch',    // Each takes up full width
53070         padding: 5
53071     },
53072     items: [{               // Results grid specified as a config object with an xtype of 'grid'
53073         xtype: 'grid',
53074         columns: [{header: 'Column One'}],            // One header just for show. There&#39;s no data,
53075         store: Ext.create('Ext.data.ArrayStore', {}), // A dummy empty data store
53076         flex: 1                                       // Use 1/3 of Container&#39;s height (hint to Box layout)
53077     }, {
53078         xtype: 'splitter'   // A splitter between the two child items
53079     }, {                    // Details Panel specified as a config object (no xtype defaults to 'panel').
53080         title: 'Details',
53081         bodyPadding: 5,
53082         items: [{
53083             fieldLabel: 'Data item',
53084             xtype: 'textfield'
53085         }], // An array of form fields
53086         flex: 2             // Use 2/3 of Container&#39;s height (hint to Box layout)
53087     }]
53088 });
53089 </code></pre>
53090  * The example illustrates one possible method of displaying search results. The Panel contains a grid with the resulting data arranged
53091  * in rows. Each selected row may be displayed in detail in the Panel below. The {@link Ext.layout.container.VBox vbox} layout is used
53092  * to arrange the two vertically. It is configured to stretch child items horizontally to full width. Child items may either be configured
53093  * with a numeric height, or with a <code>flex</code> value to distribute available space proportionately.</p>
53094  * <p>This Panel itself may be a child item of, for exaple, a {@link Ext.tab.Panel} which will size its child items to fit within its
53095  * content area.</p>
53096  * <p>Using these techniques, as long as the <b>layout</b> is chosen and configured correctly, an application may have any level of
53097  * nested containment, all dynamically sized according to configuration, the user&#39;s preference and available browser size.</p>
53098  * @constructor
53099  * @param {Object} config The config object
53100  * @xtype panel
53101  */
53102 Ext.define('Ext.panel.Panel', {
53103     extend: 'Ext.panel.AbstractPanel',
53104     requires: [
53105         'Ext.panel.Header',
53106         'Ext.fx.Anim',
53107         'Ext.util.KeyMap',
53108         'Ext.panel.DD',
53109         'Ext.XTemplate',
53110         'Ext.layout.component.Dock'
53111     ],
53112     alias: 'widget.panel',
53113     alternateClassName: 'Ext.Panel',
53114
53115     /**
53116      * @cfg {String} collapsedCls
53117      * A CSS class to add to the panel&#39;s element after it has been collapsed (defaults to
53118      * <code>'collapsed'</code>).
53119      */
53120     collapsedCls: 'collapsed',
53121
53122     /**
53123      * @cfg {Boolean} animCollapse
53124      * <code>true</code> to animate the transition when the panel is collapsed, <code>false</code> to skip the
53125      * animation (defaults to <code>true</code> if the {@link Ext.fx.Anim} class is available, otherwise <code>false</code>).
53126      * May also be specified as the animation duration in milliseconds.
53127      */
53128     animCollapse: Ext.enableFx,
53129
53130     /**
53131      * @cfg {Number} minButtonWidth
53132      * Minimum width of all footer toolbar buttons in pixels (defaults to <tt>75</tt>). If set, this will
53133      * be used as the default value for the <tt>{@link Ext.button.Button#minWidth}</tt> config of
53134      * each Button added to the <b>footer toolbar</b> via the {@link #fbar} or {@link #buttons} configurations.
53135      * It will be ignored for buttons that have a minWidth configured some other way, e.g. in their own config
53136      * object or via the {@link Ext.container.Container#config-defaults defaults} of their parent container.
53137      */
53138     minButtonWidth: 75,
53139
53140     /**
53141      * @cfg {Boolean} collapsed
53142      * <code>true</code> to render the panel collapsed, <code>false</code> to render it expanded (defaults to
53143      * <code>false</code>).
53144      */
53145     collapsed: false,
53146
53147     /**
53148      * @cfg {Boolean} collapseFirst
53149      * <code>true</code> to make sure the collapse/expand toggle button always renders first (to the left of)
53150      * any other tools in the panel&#39;s title bar, <code>false</code> to render it last (defaults to <code>true</code>).
53151      */
53152     collapseFirst: true,
53153
53154     /**
53155      * @cfg {Boolean} hideCollapseTool
53156      * <code>true</code> to hide the expand/collapse toggle button when <code>{@link #collapsible} == true</code>,
53157      * <code>false</code> to display it (defaults to <code>false</code>).
53158      */
53159     hideCollapseTool: false,
53160
53161     /**
53162      * @cfg {Boolean} titleCollapse
53163      * <code>true</code> to allow expanding and collapsing the panel (when <code>{@link #collapsible} = true</code>)
53164      * by clicking anywhere in the header bar, <code>false</code>) to allow it only by clicking to tool button
53165      * (defaults to <code>false</code>)).
53166      */
53167     titleCollapse: false,
53168
53169     /**
53170      * @cfg {String} collapseMode
53171      * <p><b>Important: this config is only effective for {@link #collapsible} Panels which are direct child items of a {@link Ext.layout.container.Border border layout}.</b></p>
53172      * <p>When <i>not</i> a direct child item of a {@link Ext.layout.container.Border border layout}, then the Panel&#39;s header remains visible, and the body is collapsed to zero dimensions.
53173      * If the Panel has no header, then a new header (orientated correctly depending on the {@link #collapseDirection}) will be inserted to show a the title and a re-expand tool.</p>
53174      * <p>When a child item of a {@link Ext.layout.container.Border border layout}, this config has two options:
53175      * <div class="mdetail-params"><ul>
53176      * <li><b><code>undefined/omitted</code></b><div class="sub-desc">When collapsed, a placeholder {@link Ext.panel.Header Header} is injected into the layout to represent the Panel
53177      * and to provide a UI with a Tool to allow the user to re-expand the Panel.</div></li>
53178      * <li><b><code>header</code></b> : <div class="sub-desc">The Panel collapses to leave its header visible as when not inside a {@link Ext.layout.container.Border border layout}.</div></li>
53179      * </ul></div></p>
53180      */
53181
53182     /**
53183      * @cfg {Mixed} placeholder
53184      * <p><b>Important: This config is only effective for {@link #collapsible} Panels which are direct child items of a {@link Ext.layout.container.Border border layout}
53185      * when not using the <code>'header'</code> {@link #collapseMode}.</b></p>
53186      * <p><b>Optional.</b> A Component (or config object for a Component) to show in place of this Panel when this Panel is collapsed by a
53187      * {@link Ext.layout.container.Border border layout}. Defaults to a generated {@link Ext.panel.Header Header}
53188      * containing a {@link Ext.panel.Tool Tool} to re-expand the Panel.</p>
53189      */
53190
53191     /**
53192      * @cfg {Boolean} floatable
53193      * <p><b>Important: This config is only effective for {@link #collapsible} Panels which are direct child items of a {@link Ext.layout.container.Border border layout}.</b></p>
53194      * <tt>true</tt> to allow clicking a collapsed Panel&#39;s {@link #placeholder} to display the Panel floated
53195      * above the layout, <tt>false</tt> to force the user to fully expand a collapsed region by
53196      * clicking the expand button to see it again (defaults to <tt>true</tt>).
53197      */
53198     floatable: true,
53199
53200     /**
53201      * @cfg {Boolean} collapsible
53202      * <p>True to make the panel collapsible and have an expand/collapse toggle Tool added into
53203      * the header tool button area. False to keep the panel sized either statically, or by an owning layout manager, with no toggle Tool (defaults to false).</p>
53204      * See {@link #collapseMode} and {@link #collapseDirection}
53205      */
53206     collapsible: false,
53207
53208     /**
53209      * @cfg {Boolean} collapseDirection
53210      * <p>The direction to collapse the Panel when the toggle button is clicked.</p>
53211      * <p>Defaults to the {@link #headerPosition}</p>
53212      * <p><b>Important: This config is <u>ignored</u> for {@link #collapsible} Panels which are direct child items of a {@link Ext.layout.container.Border border layout}.</b></p>
53213      * <p>Specify as <code>'top'</code>, <code>'bottom'</code>, <code>'left'</code> or <code>'right'</code>.</p>
53214      */
53215
53216     /**
53217      * @cfg {Boolean} closable
53218      * <p>True to display the 'close' tool button and allow the user to close the window, false to
53219      * hide the button and disallow closing the window (defaults to <code>false</code>).</p>
53220      * <p>By default, when close is requested by clicking the close button in the header, the {@link #close}
53221      * method will be called. This will <i>{@link Ext.Component#destroy destroy}</i> the Panel and its content
53222      * meaning that it may not be reused.</p>
53223      * <p>To make closing a Panel <i>hide</i> the Panel so that it may be reused, set
53224      * {@link #closeAction} to 'hide'.</p>
53225      */
53226     closable: false,
53227
53228     /**
53229      * @cfg {String} closeAction
53230      * <p>The action to take when the close header tool is clicked:
53231      * <div class="mdetail-params"><ul>
53232      * <li><b><code>'{@link #destroy}'</code></b> : <b>Default</b><div class="sub-desc">
53233      * {@link #destroy remove} the window from the DOM and {@link Ext.Component#destroy destroy}
53234      * it and all descendant Components. The window will <b>not</b> be available to be
53235      * redisplayed via the {@link #show} method.
53236      * </div></li>
53237      * <li><b><code>'{@link #hide}'</code></b> : <div class="sub-desc">
53238      * {@link #hide} the window by setting visibility to hidden and applying negative offsets.
53239      * The window will be available to be redisplayed via the {@link #show} method.
53240      * </div></li>
53241      * </ul></div>
53242      * <p><b>Note:</b> This behavior has changed! setting *does* affect the {@link #close} method
53243      * which will invoke the approriate closeAction.
53244      */
53245     closeAction: 'destroy',
53246
53247     /**
53248      * @cfg {Object/Array} dockedItems
53249      * A component or series of components to be added as docked items to this panel.
53250      * The docked items can be docked to either the top, right, left or bottom of a panel.
53251      * This is typically used for things like toolbars or tab bars:
53252      * <pre><code>
53253 var panel = new Ext.panel.Panel({
53254     dockedItems: [{
53255         xtype: 'toolbar',
53256         dock: 'top',
53257         items: [{
53258             text: 'Docked to the top'
53259         }]
53260     }]
53261 });</pre></code>
53262      */
53263
53264     /**
53265       * @cfg {Boolean} preventHeader Prevent a Header from being created and shown. Defaults to false.
53266       */
53267     preventHeader: false,
53268
53269      /**
53270       * @cfg {String} headerPosition Specify as <code>'top'</code>, <code>'bottom'</code>, <code>'left'</code> or <code>'right'</code>. Defaults to <code>'top'</code>.
53271       */
53272     headerPosition: 'top',
53273
53274      /**
53275      * @cfg {Boolean} frame
53276      * True to apply a frame to the panel.
53277      */
53278     frame: false,
53279
53280     /**
53281      * @cfg {Boolean} frameHeader
53282      * True to apply a frame to the panel panels header (if 'frame' is true).
53283      */
53284     frameHeader: true,
53285
53286     /**
53287      * @cfg {Array} tools
53288      * An array of {@link Ext.panel.Tool} configs/instances to be added to the header tool area. The tools are stored as child
53289      * components of the header container. They can be accessed using {@link #down} and {#query}, as well as the other
53290      * component methods. The toggle tool is automatically created if {@link #collapsible} is set to true.
53291      * <p>Note that, apart from the toggle tool which is provided when a panel is collapsible, these
53292      * tools only provide the visual button. Any required functionality must be provided by adding
53293      * handlers that implement the necessary behavior.</p>
53294      * <p>Example usage:</p>
53295      * <pre><code>
53296 tools:[{
53297     type:'refresh',
53298     qtip: 'Refresh form Data',
53299     // hidden:true,
53300     handler: function(event, toolEl, panel){
53301         // refresh logic
53302     }
53303 },
53304 {
53305     type:'help',
53306     qtip: 'Get Help',
53307     handler: function(event, toolEl, panel){
53308         // show help here
53309     }
53310 }]
53311 </code></pre>
53312      */
53313
53314
53315     initComponent: function() {
53316         var me = this,
53317             cls;
53318
53319         me.addEvents(
53320         /**
53321          * @event titlechange
53322          * Fires after the Panel title has been set or changed.
53323          * @param {Ext.panel.Panel} p the Panel which has been resized.
53324          * @param {String} newTitle The new title.
53325          * @param {String} oldTitle The previous panel title.
53326          */
53327             'titlechange',
53328         /**
53329          * @event iconchange
53330          * Fires after the Panel iconCls has been set or changed.
53331          * @param {Ext.panel.Panel} p the Panel which has been resized.
53332          * @param {String} newIconCls The new iconCls.
53333          * @param {String} oldIconCls The previous panel iconCls.
53334          */
53335             'iconchange'
53336         );
53337
53338         if (me.unstyled) {
53339             me.setUI('plain');
53340         }
53341
53342         if (me.frame) {
53343             me.setUI('default-framed');
53344         }
53345
53346         me.callParent();
53347
53348         me.collapseDirection = me.collapseDirection || me.headerPosition || Ext.Component.DIRECTION_TOP;
53349
53350         // Backwards compatibility
53351         me.bridgeToolbars();
53352     },
53353
53354     setBorder: function(border) {
53355         // var me     = this,
53356         //     method = (border === false || border === 0) ? 'addClsWithUI' : 'removeClsWithUI';
53357         // 
53358         // me.callParent(arguments);
53359         // 
53360         // if (me.collapsed) {
53361         //     me[method](me.collapsedCls + '-noborder');
53362         // }
53363         // 
53364         // if (me.header) {
53365         //     me.header.setBorder(border);
53366         //     if (me.collapsed) {
53367         //         me.header[method](me.collapsedCls + '-noborder');
53368         //     }
53369         // }
53370         
53371         this.callParent(arguments);
53372     },
53373
53374     beforeDestroy: function() {
53375         Ext.destroy(
53376             this.ghostPanel,
53377             this.dd
53378         );
53379         this.callParent();
53380     },
53381
53382     initAria: function() {
53383         this.callParent();
53384         this.initHeaderAria();
53385     },
53386
53387     initHeaderAria: function() {
53388         var me = this,
53389             el = me.el,
53390             header = me.header;
53391         if (el && header) {
53392             el.dom.setAttribute('aria-labelledby', header.titleCmp.id);
53393         }
53394     },
53395
53396     getHeader: function() {
53397         return this.header;
53398     },
53399
53400     /**
53401      * Set a title for the panel&#39;s header. See {@link Ext.panel.Header#title}.
53402      * @param {String} newTitle
53403      */
53404     setTitle: function(newTitle) {
53405         var me = this,
53406         oldTitle = this.title;
53407
53408         me.title = newTitle;
53409         if (me.header) {
53410             me.header.setTitle(newTitle);
53411         } else {
53412             me.updateHeader();
53413         }
53414
53415         if (me.reExpander) {
53416             me.reExpander.setTitle(newTitle);
53417         }
53418         me.fireEvent('titlechange', me, newTitle, oldTitle);
53419     },
53420
53421     /**
53422      * Set the iconCls for the panel&#39;s header. See {@link Ext.panel.Header#iconCls}.
53423      * @param {String} newIconCls
53424      */
53425     setIconCls: function(newIconCls) {
53426         var me = this,
53427             oldIconCls = me.iconCls;
53428
53429         me.iconCls = newIconCls;
53430         var header = me.header;
53431         if (header) {
53432             header.setIconCls(newIconCls);
53433         }
53434         me.fireEvent('iconchange', me, newIconCls, oldIconCls);
53435     },
53436
53437     bridgeToolbars: function() {
53438         var me = this,
53439             fbar,
53440             fbarDefaults,
53441             minButtonWidth = me.minButtonWidth;
53442
53443         function initToolbar (toolbar, pos) {
53444             if (Ext.isArray(toolbar)) {
53445                 toolbar = {
53446                     xtype: 'toolbar',
53447                     items: toolbar
53448                 };
53449             }
53450             else if (!toolbar.xtype) {
53451                 toolbar.xtype = 'toolbar';
53452             }
53453             toolbar.dock = pos;
53454             if (pos == 'left' || pos == 'right') {
53455                 toolbar.vertical = true;
53456             }
53457             return toolbar;
53458         }
53459
53460         // Backwards compatibility
53461
53462         /**
53463          * @cfg {Object/Array} tbar
53464
53465 Convenience method. Short for 'Top Bar'.
53466
53467     tbar: [
53468       { xtype: 'button', text: 'Button 1' }
53469     ]
53470
53471 is equivalent to
53472
53473     dockedItems: [{
53474         xtype: 'toolbar',
53475         dock: 'top',
53476         items: [
53477             { xtype: 'button', text: 'Button 1' }
53478         ]
53479     }]
53480
53481          * @markdown
53482          */
53483         if (me.tbar) {
53484             me.addDocked(initToolbar(me.tbar, 'top'));
53485             me.tbar = null;
53486         }
53487
53488         /**
53489          * @cfg {Object/Array} bbar
53490
53491 Convenience method. Short for 'Bottom Bar'.
53492
53493     bbar: [
53494       { xtype: 'button', text: 'Button 1' }
53495     ]
53496
53497 is equivalent to
53498
53499     dockedItems: [{
53500         xtype: 'toolbar',
53501         dock: 'bottom',
53502         items: [
53503             { xtype: 'button', text: 'Button 1' }
53504         ]
53505     }]
53506
53507          * @markdown
53508          */
53509         if (me.bbar) {
53510             me.addDocked(initToolbar(me.bbar, 'bottom'));
53511             me.bbar = null;
53512         }
53513
53514         /**
53515          * @cfg {Object/Array} buttons
53516
53517 Convenience method used for adding buttons docked to the bottom right of the panel. This is a
53518 synonym for the {@link #fbar} config.
53519
53520     buttons: [
53521       { text: 'Button 1' }
53522     ]
53523
53524 is equivalent to
53525
53526     dockedItems: [{
53527         xtype: 'toolbar',
53528         dock: 'bottom',
53529         defaults: {minWidth: {@link #minButtonWidth}},
53530         items: [
53531             { xtype: 'component', flex: 1 },
53532             { xtype: 'button', text: 'Button 1' }
53533         ]
53534     }]
53535
53536 The {@link #minButtonWidth} is used as the default {@link Ext.button.Button#minWidth minWidth} for
53537 each of the buttons in the buttons toolbar.
53538
53539          * @markdown
53540          */
53541         if (me.buttons) {
53542             me.fbar = me.buttons;
53543             me.buttons = null;
53544         }
53545
53546         /**
53547          * @cfg {Object/Array} fbar
53548
53549 Convenience method used for adding items to the bottom right of the panel. Short for Footer Bar.
53550
53551     fbar: [
53552       { type: 'button', text: 'Button 1' }
53553     ]
53554
53555 is equivalent to
53556
53557     dockedItems: [{
53558         xtype: 'toolbar',
53559         dock: 'bottom',
53560         defaults: {minWidth: {@link #minButtonWidth}},
53561         items: [
53562             { xtype: 'component', flex: 1 },
53563             { xtype: 'button', text: 'Button 1' }
53564         ]
53565     }]
53566
53567 The {@link #minButtonWidth} is used as the default {@link Ext.button.Button#minWidth minWidth} for
53568 each of the buttons in the fbar.
53569
53570          * @markdown
53571          */
53572         if (me.fbar) {
53573             fbar = initToolbar(me.fbar, 'bottom');
53574             fbar.ui = 'footer';
53575
53576             // Apply the minButtonWidth config to buttons in the toolbar
53577             if (minButtonWidth) {
53578                 fbarDefaults = fbar.defaults;
53579                 fbar.defaults = function(config) {
53580                     var defaults = fbarDefaults || {};
53581                     if ((!config.xtype || config.xtype === 'button' || (config.isComponent && config.isXType('button'))) &&
53582                             !('minWidth' in defaults)) {
53583                         defaults = Ext.apply({minWidth: minButtonWidth}, defaults);
53584                     }
53585                     return defaults;
53586                 };
53587             }
53588
53589             fbar = me.addDocked(fbar)[0];
53590             fbar.insert(0, {
53591                 flex: 1,
53592                 xtype: 'component',
53593                 focusable: false
53594             });
53595             me.fbar = null;
53596         }
53597
53598         /**
53599          * @cfg {Object/Array} lbar
53600          *
53601          * Convenience method. Short for 'Left Bar' (left-docked, vertical toolbar).
53602          *
53603          *    lbar: [
53604          *      { xtype: 'button', text: 'Button 1' }
53605          *    ]
53606          *
53607          * is equivalent to
53608          *
53609          *    dockedItems: [{
53610          *        xtype: 'toolbar',
53611          *        dock: 'left',
53612          *        items: [
53613          *            { xtype: 'button', text: 'Button 1' }
53614          *        ]
53615          *    }]
53616          *
53617          * @markdown
53618          */
53619         if (me.lbar) {
53620             me.addDocked(initToolbar(me.lbar, 'left'));
53621             me.lbar = null;
53622         }
53623
53624         /**
53625          * @cfg {Object/Array} rbar
53626          *
53627          * Convenience method. Short for 'Right Bar' (right-docked, vertical toolbar).
53628          *
53629          *    rbar: [
53630          *      { xtype: 'button', text: 'Button 1' }
53631          *    ]
53632          *
53633          * is equivalent to
53634          *
53635          *    dockedItems: [{
53636          *        xtype: 'toolbar',
53637          *        dock: 'right',
53638          *        items: [
53639          *            { xtype: 'button', text: 'Button 1' }
53640          *        ]
53641          *    }]
53642          *
53643          * @markdown
53644          */
53645         if (me.rbar) {
53646             me.addDocked(initToolbar(me.rbar, 'right'));
53647             me.rbar = null;
53648         }
53649     },
53650
53651     /**
53652      * @private
53653      * Tools are a Panel-specific capabilty.
53654      * Panel uses initTools. Subclasses may contribute tools by implementing addTools.
53655      */
53656     initTools: function() {
53657         var me = this;
53658
53659         me.tools = me.tools || [];
53660
53661         // Add a collapse tool unless configured to not show a collapse tool
53662         // or to not even show a header.
53663         if (me.collapsible && !(me.hideCollapseTool || me.header === false)) {
53664             me.collapseDirection = me.collapseDirection || me.headerPosition || 'top';
53665             me.collapseTool = me.expandTool = me.createComponent({
53666                 xtype: 'tool',
53667                 type: 'collapse-' + me.collapseDirection,
53668                 expandType: me.getOppositeDirection(me.collapseDirection),
53669                 handler: me.toggleCollapse,
53670                 scope: me
53671             });
53672
53673             // Prepend collapse tool is configured to do so.
53674             if (me.collapseFirst) {
53675                 me.tools.unshift(me.collapseTool);
53676             }
53677         }
53678
53679         // Add subclass-specific tools.
53680         me.addTools();
53681
53682         // Make Panel closable.
53683         if (me.closable) {
53684             me.addClsWithUI('closable');
53685             me.addTool({
53686                 type: 'close',
53687                 handler: Ext.Function.bind(me.close, this, [])
53688             });
53689         }
53690
53691         // Append collapse tool if needed.
53692         if (me.collapseTool && !me.collapseFirst) {
53693             me.tools.push(me.collapseTool);
53694         }
53695     },
53696
53697     /**
53698      * @private
53699      * Template method to be implemented in subclasses to add their tools after the collapsible tool.
53700      */
53701     addTools: Ext.emptyFn,
53702
53703     /**
53704      * <p>Closes the Panel. By default, this method, removes it from the DOM, {@link Ext.Component#destroy destroy}s
53705      * the Panel object and all its descendant Components. The {@link #beforeclose beforeclose}
53706      * event is fired before the close happens and will cancel the close action if it returns false.<p>
53707      * <p><b>Note:</b> This method is not affected by the {@link #closeAction} setting which
53708      * only affects the action triggered when clicking the {@link #closable 'close' tool in the header}.
53709      * To hide the Panel without destroying it, call {@link #hide}.</p>
53710      */
53711     close: function() {
53712         if (this.fireEvent('beforeclose', this) !== false) {
53713             this.doClose();
53714         }
53715     },
53716
53717     // private
53718     doClose: function() {
53719         this.fireEvent('close', this);
53720         this[this.closeAction]();
53721     },
53722
53723     onRender: function(ct, position) {
53724         var me = this,
53725             topContainer;
53726
53727         // Add class-specific header tools.
53728         // Panel adds collapsible and closable.
53729         me.initTools();
53730
53731         // Dock the header/title
53732         me.updateHeader();
53733
53734         // If initially collapsed, collapsed flag must indicate true current state at this point.
53735         // Do collapse after the first time the Panel's structure has been laid out.
53736         if (me.collapsed) {
53737             me.collapsed = false;
53738             topContainer = me.findLayoutController();
53739             if (!me.hidden && topContainer) {
53740                 topContainer.on({
53741                     afterlayout: function() {
53742                         me.collapse(null, false, true);
53743                     },
53744                     single: true
53745                 });
53746             } else {
53747                 me.afterComponentLayout = function() {
53748                     delete me.afterComponentLayout;
53749                     Ext.getClass(me).prototype.afterComponentLayout.apply(me, arguments);
53750                     me.collapse(null, false, true);
53751                 };
53752             }
53753         }
53754
53755         // Call to super after adding the header, to prevent an unnecessary re-layout
53756         me.callParent(arguments);
53757     },
53758
53759     /**
53760      * Create, hide, or show the header component as appropriate based on the current config.
53761      * @private
53762      * @param {Boolean} force True to force the the header to be created
53763      */
53764     updateHeader: function(force) {
53765         var me = this,
53766             header = me.header,
53767             title = me.title,
53768             tools = me.tools;
53769
53770         if (!me.preventHeader && (force || title || (tools && tools.length))) {
53771             if (!header) {
53772                 header = me.header = Ext.create('Ext.panel.Header', {
53773                     title       : title,
53774                     orientation : (me.headerPosition == 'left' || me.headerPosition == 'right') ? 'vertical' : 'horizontal',
53775                     dock        : me.headerPosition || 'top',
53776                     textCls     : me.headerTextCls,
53777                     iconCls     : me.iconCls,
53778                     baseCls     : me.baseCls + '-header',
53779                     tools       : tools,
53780                     ui          : me.ui,
53781                     indicateDrag: me.draggable,
53782                     border      : me.border,
53783                     frame       : me.frame && me.frameHeader,
53784                     ignoreParentFrame : me.frame || me.overlapHeader,
53785                     ignoreBorderManagement: me.frame || me.ignoreHeaderBorderManagement,
53786                     listeners   : me.collapsible && me.titleCollapse ? {
53787                         click: me.toggleCollapse,
53788                         scope: me
53789                     } : null
53790                 });
53791                 me.addDocked(header, 0);
53792
53793                 // Reference the Header's tool array.
53794                 // Header injects named references.
53795                 me.tools = header.tools;
53796             }
53797             header.show();
53798             me.initHeaderAria();
53799         } else if (header) {
53800             header.hide();
53801         }
53802     },
53803
53804     // inherit docs
53805     setUI: function(ui) {
53806         var me = this;
53807
53808         me.callParent(arguments);
53809
53810         if (me.header) {
53811             me.header.setUI(ui);
53812         }
53813     },
53814
53815     // private
53816     getContentTarget: function() {
53817         return this.body;
53818     },
53819
53820     getTargetEl: function() {
53821         return this.body || this.frameBody || this.el;
53822     },
53823
53824     addTool: function(tool) {
53825         this.tools.push(tool);
53826         var header = this.header;
53827         if (header) {
53828             header.addTool(tool);
53829         }
53830         this.updateHeader();
53831     },
53832
53833     getOppositeDirection: function(d) {
53834         var c = Ext.Component;
53835         switch (d) {
53836             case c.DIRECTION_TOP:
53837                 return c.DIRECTION_BOTTOM;
53838             case c.DIRECTION_RIGHT:
53839                 return c.DIRECTION_LEFT;
53840             case c.DIRECTION_BOTTOM:
53841                 return c.DIRECTION_TOP;
53842             case c.DIRECTION_LEFT:
53843                 return c.DIRECTION_RIGHT;
53844         }
53845     },
53846
53847     /**
53848      * Collapses the panel body so that the body becomes hidden. Docked Components parallel to the
53849      * border towards which the collapse takes place will remain visible.  Fires the {@link #beforecollapse} event which will
53850      * cancel the collapse action if it returns false.
53851      * @param {Number} direction. The direction to collapse towards. Must be one of<ul>
53852      * <li>Ext.Component.DIRECTION_TOP</li>
53853      * <li>Ext.Component.DIRECTION_RIGHT</li>
53854      * <li>Ext.Component.DIRECTION_BOTTOM</li>
53855      * <li>Ext.Component.DIRECTION_LEFT</li></ul>
53856      * @param {Boolean} animate True to animate the transition, else false (defaults to the value of the
53857      * {@link #animCollapse} panel config)
53858      * @return {Ext.panel.Panel} this
53859      */
53860     collapse: function(direction, animate, /* private - passed if called at render time */ internal) {
53861         var me = this,
53862             c = Ext.Component,
53863             height = me.getHeight(),
53864             width = me.getWidth(),
53865             frameInfo,
53866             newSize = 0,
53867             dockedItems = me.dockedItems.items,
53868             dockedItemCount = dockedItems.length,
53869             i = 0,
53870             comp,
53871             pos,
53872             anim = {
53873                 from: {
53874                     height: height,
53875                     width: width
53876                 },
53877                 to: {
53878                     height: height,
53879                     width: width
53880                 },
53881                 listeners: {
53882                     afteranimate: me.afterCollapse,
53883                     scope: me
53884                 },
53885                 duration: Ext.Number.from(animate, Ext.fx.Anim.prototype.duration)
53886             },
53887             reExpander,
53888             reExpanderOrientation,
53889             reExpanderDock,
53890             getDimension,
53891             setDimension,
53892             collapseDimension;
53893
53894         if (!direction) {
53895             direction = me.collapseDirection;
53896         }
53897
53898         // If internal (Called because of initial collapsed state), then no animation, and no events.
53899         if (internal) {
53900             animate = false;
53901         } else if (me.collapsed || me.fireEvent('beforecollapse', me, direction, animate) === false) {
53902             return false;
53903         }
53904
53905         reExpanderDock = direction;
53906         me.expandDirection = me.getOppositeDirection(direction);
53907
53908         // Track docked items which we hide during collapsed state
53909         me.hiddenDocked = [];
53910
53911         switch (direction) {
53912             case c.DIRECTION_TOP:
53913             case c.DIRECTION_BOTTOM:
53914                 me.expandedSize = me.getHeight();
53915                 reExpanderOrientation = 'horizontal';
53916                 collapseDimension = 'height';
53917                 getDimension = 'getHeight';
53918                 setDimension = 'setHeight';
53919
53920                 // Collect the height of the visible header.
53921                 // Hide all docked items except the header.
53922                 // Hide *ALL* docked items if we're going to end up hiding the whole Panel anyway
53923                 for (; i < dockedItemCount; i++) {
53924                     comp = dockedItems[i];
53925                     if (comp.isVisible()) {
53926                         if (comp.isHeader && (!comp.dock || comp.dock == 'top' || comp.dock == 'bottom')) {
53927                             reExpander = comp;
53928                         } else {
53929                             me.hiddenDocked.push(comp);
53930                         }
53931                     }
53932                 }
53933
53934                 if (direction == Ext.Component.DIRECTION_BOTTOM) {
53935                     pos = me.getPosition()[1] - Ext.fly(me.el.dom.offsetParent).getRegion().top;
53936                     anim.from.top = pos;
53937                 }
53938                 break;
53939
53940             case c.DIRECTION_LEFT:
53941             case c.DIRECTION_RIGHT:
53942                 me.expandedSize = me.getWidth();
53943                 reExpanderOrientation = 'vertical';
53944                 collapseDimension = 'width';
53945                 getDimension = 'getWidth';
53946                 setDimension = 'setWidth';
53947
53948                 // Collect the height of the visible header.
53949                 // Hide all docked items except the header.
53950                 // Hide *ALL* docked items if we're going to end up hiding the whole Panel anyway
53951                 for (; i < dockedItemCount; i++) {
53952                     comp = dockedItems[i];
53953                     if (comp.isVisible()) {
53954                         if (comp.isHeader && (comp.dock == 'left' || comp.dock == 'right')) {
53955                             reExpander = comp;
53956                         } else {
53957                             me.hiddenDocked.push(comp);
53958                         }
53959                     }
53960                 }
53961
53962                 if (direction == Ext.Component.DIRECTION_RIGHT) {
53963                     pos = me.getPosition()[0] - Ext.fly(me.el.dom.offsetParent).getRegion().left;
53964                     anim.from.left = pos;
53965                 }
53966                 break;
53967
53968             default:
53969                 throw('Panel collapse must be passed a valid Component collapse direction');
53970         }
53971
53972         // No scrollbars when we shrink this Panel
53973         // And no laying out of any children... we're effectively *hiding* the body
53974         me.setAutoScroll(false);
53975         me.suspendLayout = true;
53976         me.body.setVisibilityMode(Ext.core.Element.DISPLAY);
53977
53978         // Disable toggle tool during animated collapse
53979         if (animate && me.collapseTool) {
53980             me.collapseTool.disable();
53981         }
53982
53983         // Add the collapsed class now, so that collapsed CSS rules are applied before measurements are taken.
53984         me.addClsWithUI(me.collapsedCls);
53985         // if (me.border === false) {
53986         //     me.addClsWithUI(me.collapsedCls + '-noborder');
53987         // }
53988
53989         // We found a header: Measure it to find the collapse-to size.
53990         if (reExpander) {
53991             //we must add the collapsed cls to the header and then remove to get the proper height
53992             reExpander.addClsWithUI(me.collapsedCls);
53993             reExpander.addClsWithUI(me.collapsedCls + '-' + reExpander.dock);
53994             if (me.border && (!me.frame || (me.frame && Ext.supports.CSS3BorderRadius))) {
53995                 reExpander.addClsWithUI(me.collapsedCls + '-border-' + reExpander.dock);
53996             }
53997
53998             frameInfo = reExpander.getFrameInfo();
53999                         
54000             //get the size
54001             newSize = reExpander[getDimension]() + (frameInfo ? frameInfo[direction] : 0);
54002
54003             //and remove
54004             reExpander.removeClsWithUI(me.collapsedCls);
54005             reExpander.removeClsWithUI(me.collapsedCls + '-' + reExpander.dock);              
54006             if (me.border && (!me.frame || (me.frame && Ext.supports.CSS3BorderRadius))) {
54007                 reExpander.removeClsWithUI(me.collapsedCls + '-border-' + reExpander.dock);
54008             }
54009         }
54010         // No header: Render and insert a temporary one, and then measure it.
54011         else {
54012             reExpander = {
54013                 hideMode: 'offsets',
54014                 temporary: true,
54015                 title: me.title,
54016                 orientation: reExpanderOrientation,
54017                 dock: reExpanderDock,
54018                 textCls: me.headerTextCls,
54019                 iconCls: me.iconCls,
54020                 baseCls: me.baseCls + '-header',
54021                 ui: me.ui,
54022                 frame: me.frame && me.frameHeader,
54023                 ignoreParentFrame: me.frame || me.overlapHeader,
54024                 indicateDrag: me.draggable,
54025                 cls: me.baseCls + '-collapsed-placeholder ' + ' ' + Ext.baseCSSPrefix + 'docked ' + me.baseCls + '-' + me.ui + '-collapsed',
54026                 renderTo: me.el
54027             };
54028             reExpander[(reExpander.orientation == 'horizontal') ? 'tools' : 'items'] = [{
54029                 xtype: 'tool',
54030                 type: 'expand-' + me.expandDirection,
54031                 handler: me.toggleCollapse,
54032                 scope: me
54033             }];
54034
54035             // Capture the size of the re-expander.
54036             // For vertical headers in IE6 and IE7, this will be sized by a CSS rule in _panel.scss
54037             reExpander = me.reExpander = Ext.create('Ext.panel.Header', reExpander);
54038             newSize = reExpander[getDimension]() + ((reExpander.frame) ? reExpander.frameSize[direction] : 0);
54039             reExpander.hide();
54040
54041             // Insert the new docked item
54042             me.insertDocked(0, reExpander);
54043         }
54044
54045         me.reExpander = reExpander;
54046         me.reExpander.addClsWithUI(me.collapsedCls);
54047         me.reExpander.addClsWithUI(me.collapsedCls + '-' + reExpander.dock);
54048         if (me.border && (!me.frame || (me.frame && Ext.supports.CSS3BorderRadius))) {
54049             me.reExpander.addClsWithUI(me.collapsedCls + '-border-' + me.reExpander.dock);
54050         }
54051
54052         // If collapsing right or down, we'll be also animating the left or top.
54053         if (direction == Ext.Component.DIRECTION_RIGHT) {
54054             anim.to.left = pos + (width - newSize);
54055         } else if (direction == Ext.Component.DIRECTION_BOTTOM) {
54056             anim.to.top = pos + (height - newSize);
54057         }
54058
54059         // Animate to the new size
54060         anim.to[collapseDimension] = newSize;
54061
54062         // Remove any flex config before we attempt to collapse.
54063         me.savedFlex = me.flex;
54064         me.savedMinWidth = me.minWidth;
54065         me.savedMinHeight = me.minHeight;
54066         me.minWidth = 0;
54067         me.minHeight = 0;
54068         delete me.flex;
54069
54070         if (animate) {
54071             me.animate(anim);
54072         } else {
54073             me.setSize(anim.to.width, anim.to.height);
54074             if (Ext.isDefined(anim.to.left) || Ext.isDefined(anim.to.top)) {
54075                 me.setPosition(anim.to.left, anim.to.top);
54076             }
54077             me.afterCollapse(false, internal);
54078         }
54079         return me;
54080     },
54081
54082     afterCollapse: function(animated, internal) {
54083         var me = this,
54084             i = 0,
54085             l = me.hiddenDocked.length;
54086
54087         me.minWidth = me.savedMinWidth;
54088         me.minHeight = me.savedMinHeight;
54089
54090         me.body.hide();
54091         for (; i < l; i++) {
54092             me.hiddenDocked[i].hide();
54093         }
54094         if (me.reExpander) {
54095             me.reExpander.updateFrame();
54096             me.reExpander.show();
54097         }
54098         me.collapsed = true;
54099
54100         if (!internal) {
54101             me.doComponentLayout();
54102         }
54103
54104         if (me.resizer) {
54105             me.resizer.disable();
54106         }
54107
54108         // If me Panel was configured with a collapse tool in its header, flip it's type
54109         if (me.collapseTool) {
54110             me.collapseTool.setType('expand-' + me.expandDirection);
54111         }
54112         if (!internal) {
54113             me.fireEvent('collapse', me);
54114         }
54115
54116         // Re-enable the toggle tool after an animated collapse
54117         if (animated && me.collapseTool) {
54118             me.collapseTool.enable();
54119         }
54120     },
54121
54122     /**
54123      * Expands the panel body so that it becomes visible.  Fires the {@link #beforeexpand} event which will
54124      * cancel the expand action if it returns false.
54125      * @param {Boolean} animate True to animate the transition, else false (defaults to the value of the
54126      * {@link #animCollapse} panel config)
54127      * @return {Ext.panel.Panel} this
54128      */
54129     expand: function(animate) {
54130         if (!this.collapsed || this.fireEvent('beforeexpand', this, animate) === false) {
54131             return false;
54132         }
54133         var me = this,
54134             i = 0,
54135             l = me.hiddenDocked.length,
54136             direction = me.expandDirection,
54137             height = me.getHeight(),
54138             width = me.getWidth(),
54139             pos, anim, satisfyJSLint;
54140
54141         // Disable toggle tool during animated expand
54142         if (animate && me.collapseTool) {
54143             me.collapseTool.disable();
54144         }
54145
54146         // Show any docked items that we hid on collapse
54147         // And hide the injected reExpander Header
54148         for (; i < l; i++) {
54149             me.hiddenDocked[i].hidden = false;
54150             me.hiddenDocked[i].el.show();
54151         }
54152         if (me.reExpander) {
54153             if (me.reExpander.temporary) {
54154                 me.reExpander.hide();
54155             } else {
54156                 me.reExpander.removeClsWithUI(me.collapsedCls);
54157                 me.reExpander.removeClsWithUI(me.collapsedCls + '-' + me.reExpander.dock);
54158                 if (me.border && (!me.frame || (me.frame && Ext.supports.CSS3BorderRadius))) {
54159                     me.reExpander.removeClsWithUI(me.collapsedCls + '-border-' + me.reExpander.dock);
54160                 }
54161                 me.reExpander.updateFrame();
54162             }
54163         }
54164
54165         // If me Panel was configured with a collapse tool in its header, flip it's type
54166         if (me.collapseTool) {
54167             me.collapseTool.setType('collapse-' + me.collapseDirection);
54168         }
54169
54170         // Unset the flag before the potential call to calculateChildBox to calculate our newly flexed size
54171         me.collapsed = false;
54172
54173         // Collapsed means body element was hidden
54174         me.body.show();
54175
54176         // Remove any collapsed styling before any animation begins
54177         me.removeClsWithUI(me.collapsedCls);
54178         // if (me.border === false) {
54179         //     me.removeClsWithUI(me.collapsedCls + '-noborder');
54180         // }
54181
54182         anim = {
54183             to: {
54184             },
54185             from: {
54186                 height: height,
54187                 width: width
54188             },
54189             listeners: {
54190                 afteranimate: me.afterExpand,
54191                 scope: me
54192             }
54193         };
54194
54195         if ((direction == Ext.Component.DIRECTION_TOP) || (direction == Ext.Component.DIRECTION_BOTTOM)) {
54196
54197             // If autoHeight, measure the height now we have shown the body element.
54198             if (me.autoHeight) {
54199                 me.setCalculatedSize(me.width, null);
54200                 anim.to.height = me.getHeight();
54201
54202                 // Must size back down to collapsed for the animation.
54203                 me.setCalculatedSize(me.width, anim.from.height);
54204             }
54205             // If we were flexed, then we can't just restore to the saved size.
54206             // We must restore to the currently correct, flexed size, so we much ask the Box layout what that is.
54207             else if (me.savedFlex) {
54208                 me.flex = me.savedFlex;
54209                 anim.to.height = me.ownerCt.layout.calculateChildBox(me).height;
54210                 delete me.flex;
54211             }
54212             // Else, restore to saved height
54213             else {
54214                 anim.to.height = me.expandedSize;
54215             }
54216
54217             // top needs animating upwards
54218             if (direction == Ext.Component.DIRECTION_TOP) {
54219                 pos = me.getPosition()[1] - Ext.fly(me.el.dom.offsetParent).getRegion().top;
54220                 anim.from.top = pos;
54221                 anim.to.top = pos - (anim.to.height - height);
54222             }
54223         } else if ((direction == Ext.Component.DIRECTION_LEFT) || (direction == Ext.Component.DIRECTION_RIGHT)) {
54224
54225             // If autoWidth, measure the width now we have shown the body element.
54226             if (me.autoWidth) {
54227                 me.setCalculatedSize(null, me.height);
54228                 anim.to.width = me.getWidth();
54229
54230                 // Must size back down to collapsed for the animation.
54231                 me.setCalculatedSize(anim.from.width, me.height);
54232             }
54233             // If we were flexed, then we can't just restore to the saved size.
54234             // We must restore to the currently correct, flexed size, so we much ask the Box layout what that is.
54235             else if (me.savedFlex) {
54236                 me.flex = me.savedFlex;
54237                 anim.to.width = me.ownerCt.layout.calculateChildBox(me).width;
54238                 delete me.flex;
54239             }
54240             // Else, restore to saved width
54241             else {
54242                 anim.to.width = me.expandedSize;
54243             }
54244
54245             // left needs animating leftwards
54246             if (direction == Ext.Component.DIRECTION_LEFT) {
54247                 pos = me.getPosition()[0] - Ext.fly(me.el.dom.offsetParent).getRegion().left;
54248                 anim.from.left = pos;
54249                 anim.to.left = pos - (anim.to.width - width);
54250             }
54251         }
54252
54253         if (animate) {
54254             me.animate(anim);
54255         } else {
54256             me.setSize(anim.to.width, anim.to.height);
54257             if (anim.to.x) {
54258                 me.setLeft(anim.to.x);
54259             }
54260             if (anim.to.y) {
54261                 me.setTop(anim.to.y);
54262             }
54263             me.afterExpand(false);
54264         }
54265
54266         return me;
54267     },
54268
54269     afterExpand: function(animated) {
54270         var me = this;
54271         me.setAutoScroll(me.initialConfig.autoScroll);
54272
54273         // Restored to a calculated flex. Delete the set width and height properties so that flex works from now on.
54274         if (me.savedFlex) {
54275             me.flex = me.savedFlex;
54276             delete me.savedFlex;
54277             delete me.width;
54278             delete me.height;
54279         }
54280
54281         // Reinstate layout out after Panel has re-expanded
54282         delete me.suspendLayout;
54283         if (animated && me.ownerCt) {
54284             me.ownerCt.doLayout();
54285         }
54286
54287         if (me.resizer) {
54288             me.resizer.enable();
54289         }
54290
54291         me.fireEvent('expand', me);
54292
54293         // Re-enable the toggle tool after an animated expand
54294         if (animated && me.collapseTool) {
54295             me.collapseTool.enable();
54296         }
54297     },
54298
54299     /**
54300      * Shortcut for performing an {@link #expand} or {@link #collapse} based on the current state of the panel.
54301      * @return {Ext.panel.Panel} this
54302      */
54303     toggleCollapse: function() {
54304         if (this.collapsed) {
54305             this.expand(this.animCollapse);
54306         } else {
54307             this.collapse(this.collapseDirection, this.animCollapse);
54308         }
54309         return this;
54310     },
54311
54312     // private
54313     getKeyMap : function(){
54314         if(!this.keyMap){
54315             this.keyMap = Ext.create('Ext.util.KeyMap', this.el, this.keys);
54316         }
54317         return this.keyMap;
54318     },
54319
54320     // private
54321     initDraggable : function(){
54322         /**
54323          * <p>If this Panel is configured {@link #draggable}, this property will contain
54324          * an instance of {@link Ext.dd.DragSource} which handles dragging the Panel.</p>
54325          * The developer must provide implementations of the abstract methods of {@link Ext.dd.DragSource}
54326          * in order to supply behaviour for each stage of the drag/drop process. See {@link #draggable}.
54327          * @type Ext.dd.DragSource.
54328          * @property dd
54329          */
54330         this.dd = Ext.create('Ext.panel.DD', this, Ext.isBoolean(this.draggable) ? null : this.draggable);
54331     },
54332
54333     // private - helper function for ghost
54334     ghostTools : function() {
54335         var tools = [],
54336             origTools = this.initialConfig.tools;
54337
54338         if (origTools) {
54339             Ext.each(origTools, function(tool) {
54340                 // Some tools can be full components, and copying them into the ghost
54341                 // actually removes them from the owning panel. You could also potentially
54342                 // end up with duplicate DOM ids as well. To avoid any issues we just make
54343                 // a simple bare-minimum clone of each tool for ghosting purposes.
54344                 tools.push({
54345                     type: tool.type
54346                 });
54347             });
54348         }
54349         else {
54350             tools = [{
54351                 type: 'placeholder'
54352             }];
54353         }
54354         return tools;
54355     },
54356
54357     // private - used for dragging
54358     ghost: function(cls) {
54359         var me = this,
54360             ghostPanel = me.ghostPanel,
54361             box = me.getBox();
54362
54363         if (!ghostPanel) {
54364             ghostPanel = Ext.create('Ext.panel.Panel', {
54365                 renderTo: document.body,
54366                 floating: {
54367                     shadow: false
54368                 },
54369                 frame: Ext.supports.CSS3BorderRadius ? me.frame : false,
54370                 title: me.title,
54371                 overlapHeader: me.overlapHeader,
54372                 headerPosition: me.headerPosition,
54373                 width: me.getWidth(),
54374                 height: me.getHeight(),
54375                 iconCls: me.iconCls,
54376                 baseCls: me.baseCls,
54377                 tools: me.ghostTools(),
54378                 cls: me.baseCls + '-ghost ' + (cls ||'')
54379             });
54380             me.ghostPanel = ghostPanel;
54381         }
54382         ghostPanel.floatParent = me.floatParent;
54383         if (me.floating) {
54384             ghostPanel.setZIndex(Ext.Number.from(me.el.getStyle('zIndex'), 0));
54385         } else {
54386             ghostPanel.toFront();
54387         }
54388         ghostPanel.el.show();
54389         ghostPanel.setPosition(box.x, box.y);
54390         ghostPanel.setSize(box.width, box.height);
54391         me.el.hide();
54392         if (me.floatingItems) {
54393             me.floatingItems.hide();
54394         }
54395         return ghostPanel;
54396     },
54397
54398     // private
54399     unghost: function(show, matchPosition) {
54400         var me = this;
54401         if (!me.ghostPanel) {
54402             return;
54403         }
54404         if (show !== false) {
54405             me.el.show();
54406             if (matchPosition !== false) {
54407                 me.setPosition(me.ghostPanel.getPosition());
54408             }
54409             if (me.floatingItems) {
54410                 me.floatingItems.show();
54411             }
54412             Ext.defer(me.focus, 10, me);
54413         }
54414         me.ghostPanel.el.hide();
54415     },
54416
54417     initResizable: function(resizable) {
54418         if (this.collapsed) {
54419             resizable.disabled = true;
54420         }
54421         this.callParent([resizable]);
54422     }
54423 });
54424
54425 /**
54426  * Component layout for Tip/ToolTip/etc. components
54427  * @class Ext.layout.component.Tip
54428  * @extends Ext.layout.component.Dock
54429  * @private
54430  */
54431
54432 Ext.define('Ext.layout.component.Tip', {
54433
54434     /* Begin Definitions */
54435
54436     alias: ['layout.tip'],
54437
54438     extend: 'Ext.layout.component.Dock',
54439
54440     /* End Definitions */
54441
54442     type: 'tip',
54443     
54444     onLayout: function(width, height) {
54445         var me = this,
54446             owner = me.owner,
54447             el = owner.el,
54448             minWidth,
54449             maxWidth,
54450             naturalWidth,
54451             constrainedWidth,
54452             xy = el.getXY();
54453
54454         // Position offscreen so the natural width is not affected by the viewport's right edge
54455         el.setXY([-9999,-9999]);
54456
54457         // Calculate initial layout
54458         this.callParent(arguments);
54459
54460         // Handle min/maxWidth for auto-width tips
54461         if (!Ext.isNumber(width)) {
54462             minWidth = owner.minWidth;
54463             maxWidth = owner.maxWidth;
54464             // IE6/7 in strict mode have a problem doing an autoWidth
54465             if (Ext.isStrict && (Ext.isIE6 || Ext.isIE7)) {
54466                 constrainedWidth = me.doAutoWidth();
54467             } else {
54468                 naturalWidth = el.getWidth();
54469             }
54470             if (naturalWidth < minWidth) {
54471                 constrainedWidth = minWidth;
54472             }
54473             else if (naturalWidth > maxWidth) {
54474                 constrainedWidth = maxWidth;
54475             }
54476             if (constrainedWidth) {
54477                 this.callParent([constrainedWidth, height]);
54478             }
54479         }
54480
54481         // Restore position
54482         el.setXY(xy);
54483     },
54484     
54485     doAutoWidth: function(){
54486         var me = this,
54487             owner = me.owner,
54488             body = owner.body,
54489             width = body.getTextWidth();
54490             
54491         if (owner.header) {
54492             width = Math.max(width, owner.header.getWidth());
54493         }
54494         if (!Ext.isDefined(me.frameWidth)) {
54495             me.frameWidth = owner.el.getWidth() - body.getWidth();
54496         }
54497         width += me.frameWidth + body.getPadding('lr');
54498         return width;
54499     }
54500 });
54501
54502 /**
54503  * @class Ext.tip.Tip
54504  * @extends Ext.panel.Panel
54505  * This is the base class for {@link Ext.tip.QuickTip} and {@link Ext.tip.ToolTip} that provides the basic layout and
54506  * positioning that all tip-based classes require. This class can be used directly for simple, statically-positioned
54507  * tips that are displayed programmatically, or it can be extended to provide custom tip implementations.
54508  * @constructor
54509  * Create a new Tip
54510  * @param {Object} config The configuration options
54511  * @xtype tip
54512  */
54513 Ext.define('Ext.tip.Tip', {
54514     extend: 'Ext.panel.Panel',
54515     requires: [ 'Ext.layout.component.Tip' ],
54516     alternateClassName: 'Ext.Tip',
54517     /**
54518      * @cfg {Boolean} closable True to render a close tool button into the tooltip header (defaults to false).
54519      */
54520     /**
54521      * @cfg {Number} width
54522      * Width in pixels of the tip (defaults to auto).  Width will be ignored if it exceeds the bounds of
54523      * {@link #minWidth} or {@link #maxWidth}.  The maximum supported value is 500.
54524      */
54525     /**
54526      * @cfg {Number} minWidth The minimum width of the tip in pixels (defaults to 40).
54527      */
54528     minWidth : 40,
54529     /**
54530      * @cfg {Number} maxWidth The maximum width of the tip in pixels (defaults to 300).  The maximum supported value is 500.
54531      */
54532     maxWidth : 300,
54533     /**
54534      * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop"
54535      * for bottom-right shadow (defaults to "sides").
54536      */
54537     shadow : "sides",
54538
54539     /**
54540      * @cfg {String} defaultAlign <b>Experimental</b>. The default {@link Ext.core.Element#alignTo} anchor position value
54541      * for this tip relative to its element of origin (defaults to "tl-bl?").
54542      */
54543     defaultAlign : "tl-bl?",
54544     /**
54545      * @cfg {Boolean} constrainPosition If true, then the tooltip will be automatically constrained to stay within
54546      * the browser viewport. Defaults to false.
54547      */
54548     constrainPosition : true,
54549
54550     /**
54551      * @inherited
54552      */
54553     frame: false,
54554
54555     // private panel overrides
54556     autoRender: true,
54557     hidden: true,
54558     baseCls: Ext.baseCSSPrefix + 'tip',
54559     floating: {
54560         shadow: true,
54561         shim: true,
54562         constrain: true
54563     },
54564     focusOnToFront: false,
54565     componentLayout: 'tip',
54566
54567     closeAction: 'hide',
54568
54569     ariaRole: 'tooltip',
54570
54571     initComponent: function() {
54572         this.callParent(arguments);
54573
54574         // Or in the deprecated config. Floating.doConstrain only constrains if the constrain property is truthy.
54575         this.constrain = this.constrain || this.constrainPosition;
54576     },
54577
54578     /**
54579      * Shows this tip at the specified XY position.  Example usage:
54580      * <pre><code>
54581 // Show the tip at x:50 and y:100
54582 tip.showAt([50,100]);
54583 </code></pre>
54584      * @param {Array} xy An array containing the x and y coordinates
54585      */
54586     showAt : function(xy){
54587         var me = this;
54588         this.callParent();
54589         // Show may have been vetoed.
54590         if (me.isVisible()) {
54591             me.setPagePosition(xy[0], xy[1]);
54592             if (me.constrainPosition || me.constrain) {
54593                 me.doConstrain();
54594             }
54595             me.toFront(true);
54596         }
54597     },
54598
54599     /**
54600      * <b>Experimental</b>. Shows this tip at a position relative to another element using a standard {@link Ext.core.Element#alignTo}
54601      * anchor position value.  Example usage:
54602      * <pre><code>
54603 // Show the tip at the default position ('tl-br?')
54604 tip.showBy('my-el');
54605
54606 // Show the tip's top-left corner anchored to the element's top-right corner
54607 tip.showBy('my-el', 'tl-tr');
54608 </code></pre>
54609      * @param {Mixed} el An HTMLElement, Ext.core.Element or string id of the target element to align to
54610      * @param {String} position (optional) A valid {@link Ext.core.Element#alignTo} anchor position (defaults to 'tl-br?' or
54611      * {@link #defaultAlign} if specified).
54612      */
54613     showBy : function(el, pos) {
54614         this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign));
54615     },
54616
54617     /**
54618      * @private
54619      * @override
54620      * Set Tip draggable using base Component's draggability
54621      */
54622     initDraggable : function(){
54623         var me = this;
54624         me.draggable = {
54625             el: me.getDragEl(),
54626             delegate: me.header.el,
54627             constrain: me,
54628             constrainTo: me.el.dom.parentNode
54629         };
54630         // Important: Bypass Panel's initDraggable. Call direct to Component's implementation.
54631         Ext.Component.prototype.initDraggable.call(me);
54632     },
54633
54634     // Tip does not ghost. Drag is "live"
54635     ghost: undefined,
54636     unghost: undefined
54637 });
54638
54639 /**
54640  * @class Ext.tip.ToolTip
54641  * @extends Ext.tip.Tip
54642  * 
54643  * ToolTip is a {@link Ext.tip.Tip} implementation that handles the common case of displaying a
54644  * tooltip when hovering over a certain element or elements on the page. It allows fine-grained
54645  * control over the tooltip's alignment relative to the target element or mouse, and the timing
54646  * of when it is automatically shown and hidden.
54647  * 
54648  * This implementation does **not** have a built-in method of automatically populating the tooltip's
54649  * text based on the target element; you must either configure a fixed {@link #html} value for each
54650  * ToolTip instance, or implement custom logic (e.g. in a {@link #beforeshow} event listener) to
54651  * generate the appropriate tooltip content on the fly. See {@link Ext.tip.QuickTip} for a more
54652  * convenient way of automatically populating and configuring a tooltip based on specific DOM
54653  * attributes of each target element.
54654  * 
54655  * ## Basic Example
54656  * 
54657  *     var tip = Ext.create('Ext.tip.ToolTip', {
54658  *         target: 'clearButton',
54659  *         html: 'Press this button to clear the form'
54660  *     });
54661  * 
54662  * {@img Ext.tip.ToolTip/Ext.tip.ToolTip1.png Basic Ext.tip.ToolTip}
54663  * 
54664  * ## Delegation
54665  * 
54666  * In addition to attaching a ToolTip to a single element, you can also use delegation to attach
54667  * one ToolTip to many elements under a common parent. This is more efficient than creating many
54668  * ToolTip instances. To do this, point the {@link #target} config to a common ancestor of all the
54669  * elements, and then set the {@link #delegate} config to a CSS selector that will select all the
54670  * appropriate sub-elements.
54671  * 
54672  * When using delegation, it is likely that you will want to programmatically change the content
54673  * of the ToolTip based on each delegate element; you can do this by implementing a custom
54674  * listener for the {@link #beforeshow} event. Example:
54675  * 
54676  *     var myGrid = Ext.create('Ext.grid.GridPanel', gridConfig);
54677  *     myGrid.on('render', function(grid) {
54678  *         var view = grid.getView();    // Capture the grid's view.
54679  *         grid.tip = Ext.create('Ext.tip.ToolTip', {
54680  *             target: view.el,          // The overall target element.
54681  *             delegate: view.itemSelector, // Each grid row causes its own seperate show and hide.
54682  *             trackMouse: true,         // Moving within the row should not hide the tip.
54683  *             renderTo: Ext.getBody(),  // Render immediately so that tip.body can be referenced prior to the first show.
54684  *             listeners: {              // Change content dynamically depending on which element triggered the show.
54685  *                 beforeshow: function updateTipBody(tip) {
54686  *                     tip.update('Over company "' + view.getRecord(tip.triggerElement).get('company') + '"');
54687  *                 }
54688  *             }
54689  *         });
54690  *     });
54691  * 
54692  * {@img Ext.tip.ToolTip/Ext.tip.ToolTip2.png Ext.tip.ToolTip with delegation}
54693  * 
54694  * ## Alignment
54695  * 
54696  * The following configuration properties allow control over how the ToolTip is aligned relative to
54697  * the target element and/or mouse pointer:
54698  * 
54699  *  - {@link #anchor}
54700  *  - {@link #anchorToTarget}
54701  *  - {@link #anchorOffset}
54702  *  - {@link #trackMouse}
54703  *  - {@link #mouseOffset}
54704  * 
54705  * ## Showing/Hiding
54706  * 
54707  * The following configuration properties allow control over how and when the ToolTip is automatically
54708  * shown and hidden:
54709  * 
54710  *  - {@link #autoHide}
54711  *  - {@link #showDelay}
54712  *  - {@link #hideDelay}
54713  *  - {@link #dismissDelay}
54714  * 
54715  * @constructor
54716  * Create a new ToolTip instance
54717  * @param {Object} config The configuration options
54718  * @xtype tooltip
54719  * @markdown
54720  * @docauthor Jason Johnston <jason@sencha.com>
54721  */
54722 Ext.define('Ext.tip.ToolTip', {
54723     extend: 'Ext.tip.Tip',
54724     alias: 'widget.tooltip',
54725     alternateClassName: 'Ext.ToolTip',
54726     /**
54727      * When a ToolTip is configured with the <code>{@link #delegate}</code>
54728      * option to cause selected child elements of the <code>{@link #target}</code>
54729      * Element to each trigger a seperate show event, this property is set to
54730      * the DOM element which triggered the show.
54731      * @type DOMElement
54732      * @property triggerElement
54733      */
54734     /**
54735      * @cfg {Mixed} target The target HTMLElement, Ext.core.Element or id to monitor
54736      * for mouseover events to trigger showing this ToolTip.
54737      */
54738     /**
54739      * @cfg {Boolean} autoHide True to automatically hide the tooltip after the
54740      * mouse exits the target element or after the <code>{@link #dismissDelay}</code>
54741      * has expired if set (defaults to true).  If <code>{@link #closable} = true</code>
54742      * a close tool button will be rendered into the tooltip header.
54743      */
54744     /**
54745      * @cfg {Number} showDelay Delay in milliseconds before the tooltip displays
54746      * after the mouse enters the target element (defaults to 500)
54747      */
54748     showDelay: 500,
54749     /**
54750      * @cfg {Number} hideDelay Delay in milliseconds after the mouse exits the
54751      * target element but before the tooltip actually hides (defaults to 200).
54752      * Set to 0 for the tooltip to hide immediately.
54753      */
54754     hideDelay: 200,
54755     /**
54756      * @cfg {Number} dismissDelay Delay in milliseconds before the tooltip
54757      * automatically hides (defaults to 5000). To disable automatic hiding, set
54758      * dismissDelay = 0.
54759      */
54760     dismissDelay: 5000,
54761     /**
54762      * @cfg {Array} mouseOffset An XY offset from the mouse position where the
54763      * tooltip should be shown (defaults to [15,18]).
54764      */
54765     /**
54766      * @cfg {Boolean} trackMouse True to have the tooltip follow the mouse as it
54767      * moves over the target element (defaults to false).
54768      */
54769     trackMouse: false,
54770     /**
54771      * @cfg {String} anchor If specified, indicates that the tip should be anchored to a
54772      * particular side of the target element or mouse pointer ("top", "right", "bottom",
54773      * or "left"), with an arrow pointing back at the target or mouse pointer. If
54774      * {@link #constrainPosition} is enabled, this will be used as a preferred value
54775      * only and may be flipped as needed.
54776      */
54777     /**
54778      * @cfg {Boolean} anchorToTarget True to anchor the tooltip to the target
54779      * element, false to anchor it relative to the mouse coordinates (defaults
54780      * to true).  When <code>anchorToTarget</code> is true, use
54781      * <code>{@link #defaultAlign}</code> to control tooltip alignment to the
54782      * target element.  When <code>anchorToTarget</code> is false, use
54783      * <code>{@link #anchorPosition}</code> instead to control alignment.
54784      */
54785     anchorToTarget: true,
54786     /**
54787      * @cfg {Number} anchorOffset A numeric pixel value used to offset the
54788      * default position of the anchor arrow (defaults to 0).  When the anchor
54789      * position is on the top or bottom of the tooltip, <code>anchorOffset</code>
54790      * will be used as a horizontal offset.  Likewise, when the anchor position
54791      * is on the left or right side, <code>anchorOffset</code> will be used as
54792      * a vertical offset.
54793      */
54794     anchorOffset: 0,
54795     /**
54796      * @cfg {String} delegate <p>Optional. A {@link Ext.DomQuery DomQuery}
54797      * selector which allows selection of individual elements within the
54798      * <code>{@link #target}</code> element to trigger showing and hiding the
54799      * ToolTip as the mouse moves within the target.</p>
54800      * <p>When specified, the child element of the target which caused a show
54801      * event is placed into the <code>{@link #triggerElement}</code> property
54802      * before the ToolTip is shown.</p>
54803      * <p>This may be useful when a Component has regular, repeating elements
54804      * in it, each of which need a ToolTip which contains information specific
54805      * to that element. For example:</p><pre><code>
54806 var myGrid = Ext.create('Ext.grid.GridPanel', gridConfig);
54807 myGrid.on('render', function(grid) {
54808     var view = grid.getView();    // Capture the grid's view.
54809     grid.tip = Ext.create('Ext.tip.ToolTip', {
54810         target: view.el,          // The overall target element.
54811         delegate: view.itemSelector, // Each grid row causes its own seperate show and hide.
54812         trackMouse: true,         // Moving within the row should not hide the tip.
54813         renderTo: Ext.getBody(),  // Render immediately so that tip.body can be referenced prior to the first show.
54814         listeners: {              // Change content dynamically depending on which element triggered the show.
54815             beforeshow: function(tip) {
54816                 tip.update('Over Record ID ' + view.getRecord(tip.triggerElement).id);
54817             }
54818         }
54819     });
54820 });
54821      *</code></pre>
54822      */
54823
54824     // private
54825     targetCounter: 0,
54826     quickShowInterval: 250,
54827
54828     // private
54829     initComponent: function() {
54830         var me = this;
54831         me.callParent(arguments);
54832         me.lastActive = new Date();
54833         me.setTarget(me.target);
54834         me.origAnchor = me.anchor;
54835     },
54836
54837     // private
54838     onRender: function(ct, position) {
54839         var me = this;
54840         me.callParent(arguments);
54841         me.anchorCls = Ext.baseCSSPrefix + 'tip-anchor-' + me.getAnchorPosition();
54842         me.anchorEl = me.el.createChild({
54843             cls: Ext.baseCSSPrefix + 'tip-anchor ' + me.anchorCls
54844         });
54845     },
54846
54847     // private
54848     afterRender: function() {
54849         var me = this,
54850             zIndex;
54851
54852         me.callParent(arguments);
54853         zIndex = parseInt(me.el.getZIndex(), 10) || 0;
54854         me.anchorEl.setStyle('z-index', zIndex + 1).setVisibilityMode(Ext.core.Element.DISPLAY);
54855     },
54856
54857     /**
54858      * Binds this ToolTip to the specified element. The tooltip will be displayed when the mouse moves over the element.
54859      * @param {Mixed} t The Element, HtmlElement, or ID of an element to bind to
54860      */
54861     setTarget: function(target) {
54862         var me = this,
54863             t = Ext.get(target),
54864             tg;
54865
54866         if (me.target) {
54867             tg = Ext.get(me.target);
54868             me.mun(tg, 'mouseover', me.onTargetOver, me);
54869             me.mun(tg, 'mouseout', me.onTargetOut, me);
54870             me.mun(tg, 'mousemove', me.onMouseMove, me);
54871         }
54872         
54873         me.target = t;
54874         if (t) {
54875             
54876             me.mon(t, {
54877                 // TODO - investigate why IE6/7 seem to fire recursive resize in e.getXY
54878                 // breaking QuickTip#onTargetOver (EXTJSIV-1608)
54879                 freezeEvent: true,
54880
54881                 mouseover: me.onTargetOver,
54882                 mouseout: me.onTargetOut,
54883                 mousemove: me.onMouseMove,
54884                 scope: me
54885             });
54886         }
54887         if (me.anchor) {
54888             me.anchorTarget = me.target;
54889         }
54890     },
54891
54892     // private
54893     onMouseMove: function(e) {
54894         var me = this,
54895             t = me.delegate ? e.getTarget(me.delegate) : me.triggerElement = true,
54896             xy;
54897         if (t) {
54898             me.targetXY = e.getXY();
54899             if (t === me.triggerElement) {
54900                 if (!me.hidden && me.trackMouse) {
54901                     xy = me.getTargetXY();
54902                     if (me.constrainPosition) {
54903                         xy = me.el.adjustForConstraints(xy, me.el.dom.parentNode);
54904                     }
54905                     me.setPagePosition(xy);
54906                 }
54907             } else {
54908                 me.hide();
54909                 me.lastActive = new Date(0);
54910                 me.onTargetOver(e);
54911             }
54912         } else if ((!me.closable && me.isVisible()) && me.autoHide !== false) {
54913             me.hide();
54914         }
54915     },
54916
54917     // private
54918     getTargetXY: function() {
54919         var me = this,
54920             mouseOffset;
54921         if (me.delegate) {
54922             me.anchorTarget = me.triggerElement;
54923         }
54924         if (me.anchor) {
54925             me.targetCounter++;
54926                 var offsets = me.getOffsets(),
54927                     xy = (me.anchorToTarget && !me.trackMouse) ? me.el.getAlignToXY(me.anchorTarget, me.getAnchorAlign()) : me.targetXY,
54928                     dw = Ext.core.Element.getViewWidth() - 5,
54929                     dh = Ext.core.Element.getViewHeight() - 5,
54930                     de = document.documentElement,
54931                     bd = document.body,
54932                     scrollX = (de.scrollLeft || bd.scrollLeft || 0) + 5,
54933                     scrollY = (de.scrollTop || bd.scrollTop || 0) + 5,
54934                     axy = [xy[0] + offsets[0], xy[1] + offsets[1]],
54935                     sz = me.getSize(),
54936                     constrainPosition = me.constrainPosition;
54937
54938             me.anchorEl.removeCls(me.anchorCls);
54939
54940             if (me.targetCounter < 2 && constrainPosition) {
54941                 if (axy[0] < scrollX) {
54942                     if (me.anchorToTarget) {
54943                         me.defaultAlign = 'l-r';
54944                         if (me.mouseOffset) {
54945                             me.mouseOffset[0] *= -1;
54946                         }
54947                     }
54948                     me.anchor = 'left';
54949                     return me.getTargetXY();
54950                 }
54951                 if (axy[0] + sz.width > dw) {
54952                     if (me.anchorToTarget) {
54953                         me.defaultAlign = 'r-l';
54954                         if (me.mouseOffset) {
54955                             me.mouseOffset[0] *= -1;
54956                         }
54957                     }
54958                     me.anchor = 'right';
54959                     return me.getTargetXY();
54960                 }
54961                 if (axy[1] < scrollY) {
54962                     if (me.anchorToTarget) {
54963                         me.defaultAlign = 't-b';
54964                         if (me.mouseOffset) {
54965                             me.mouseOffset[1] *= -1;
54966                         }
54967                     }
54968                     me.anchor = 'top';
54969                     return me.getTargetXY();
54970                 }
54971                 if (axy[1] + sz.height > dh) {
54972                     if (me.anchorToTarget) {
54973                         me.defaultAlign = 'b-t';
54974                         if (me.mouseOffset) {
54975                             me.mouseOffset[1] *= -1;
54976                         }
54977                     }
54978                     me.anchor = 'bottom';
54979                     return me.getTargetXY();
54980                 }
54981             }
54982
54983             me.anchorCls = Ext.baseCSSPrefix + 'tip-anchor-' + me.getAnchorPosition();
54984             me.anchorEl.addCls(me.anchorCls);
54985             me.targetCounter = 0;
54986             return axy;
54987         } else {
54988             mouseOffset = me.getMouseOffset();
54989             return (me.targetXY) ? [me.targetXY[0] + mouseOffset[0], me.targetXY[1] + mouseOffset[1]] : mouseOffset;
54990         }
54991     },
54992
54993     getMouseOffset: function() {
54994         var me = this,
54995         offset = me.anchor ? [0, 0] : [15, 18];
54996         if (me.mouseOffset) {
54997             offset[0] += me.mouseOffset[0];
54998             offset[1] += me.mouseOffset[1];
54999         }
55000         return offset;
55001     },
55002
55003     // private
55004     getAnchorPosition: function() {
55005         var me = this,
55006             m;
55007         if (me.anchor) {
55008             me.tipAnchor = me.anchor.charAt(0);
55009         } else {
55010             m = me.defaultAlign.match(/^([a-z]+)-([a-z]+)(\?)?$/);
55011             if (!m) {
55012                 Ext.Error.raise('The AnchorTip.defaultAlign value "' + me.defaultAlign + '" is invalid.');
55013             }
55014             me.tipAnchor = m[1].charAt(0);
55015         }
55016
55017         switch (me.tipAnchor) {
55018         case 't':
55019             return 'top';
55020         case 'b':
55021             return 'bottom';
55022         case 'r':
55023             return 'right';
55024         }
55025         return 'left';
55026     },
55027
55028     // private
55029     getAnchorAlign: function() {
55030         switch (this.anchor) {
55031         case 'top':
55032             return 'tl-bl';
55033         case 'left':
55034             return 'tl-tr';
55035         case 'right':
55036             return 'tr-tl';
55037         default:
55038             return 'bl-tl';
55039         }
55040     },
55041
55042     // private
55043     getOffsets: function() {
55044         var me = this,
55045             mouseOffset,
55046             offsets,
55047             ap = me.getAnchorPosition().charAt(0);
55048         if (me.anchorToTarget && !me.trackMouse) {
55049             switch (ap) {
55050             case 't':
55051                 offsets = [0, 9];
55052                 break;
55053             case 'b':
55054                 offsets = [0, -13];
55055                 break;
55056             case 'r':
55057                 offsets = [ - 13, 0];
55058                 break;
55059             default:
55060                 offsets = [9, 0];
55061                 break;
55062             }
55063         } else {
55064             switch (ap) {
55065             case 't':
55066                 offsets = [ - 15 - me.anchorOffset, 30];
55067                 break;
55068             case 'b':
55069                 offsets = [ - 19 - me.anchorOffset, -13 - me.el.dom.offsetHeight];
55070                 break;
55071             case 'r':
55072                 offsets = [ - 15 - me.el.dom.offsetWidth, -13 - me.anchorOffset];
55073                 break;
55074             default:
55075                 offsets = [25, -13 - me.anchorOffset];
55076                 break;
55077             }
55078         }
55079         mouseOffset = me.getMouseOffset();
55080         offsets[0] += mouseOffset[0];
55081         offsets[1] += mouseOffset[1];
55082
55083         return offsets;
55084     },
55085
55086     // private
55087     onTargetOver: function(e) {
55088         var me = this,
55089             t;
55090
55091         if (me.disabled || e.within(me.target.dom, true)) {
55092             return;
55093         }
55094         t = e.getTarget(me.delegate);
55095         if (t) {
55096             me.triggerElement = t;
55097             me.clearTimer('hide');
55098             me.targetXY = e.getXY();
55099             me.delayShow();
55100         }
55101     },
55102
55103     // private
55104     delayShow: function() {
55105         var me = this;
55106         if (me.hidden && !me.showTimer) {
55107             if (Ext.Date.getElapsed(me.lastActive) < me.quickShowInterval) {
55108                 me.show();
55109             } else {
55110                 me.showTimer = Ext.defer(me.show, me.showDelay, me);
55111             }
55112         }
55113         else if (!me.hidden && me.autoHide !== false) {
55114             me.show();
55115         }
55116     },
55117
55118     // private
55119     onTargetOut: function(e) {
55120         var me = this;
55121         if (me.disabled || e.within(me.target.dom, true)) {
55122             return;
55123         }
55124         me.clearTimer('show');
55125         if (me.autoHide !== false) {
55126             me.delayHide();
55127         }
55128     },
55129
55130     // private
55131     delayHide: function() {
55132         var me = this;
55133         if (!me.hidden && !me.hideTimer) {
55134             me.hideTimer = Ext.defer(me.hide, me.hideDelay, me);
55135         }
55136     },
55137
55138     /**
55139      * Hides this tooltip if visible.
55140      */
55141     hide: function() {
55142         var me = this;
55143         me.clearTimer('dismiss');
55144         me.lastActive = new Date();
55145         if (me.anchorEl) {
55146             me.anchorEl.hide();
55147         }
55148         me.callParent(arguments);
55149         delete me.triggerElement;
55150     },
55151
55152     /**
55153      * Shows this tooltip at the current event target XY position.
55154      */
55155     show: function() {
55156         var me = this;
55157
55158         // Show this Component first, so that sizing can be calculated
55159         // pre-show it off screen so that the el will have dimensions
55160         this.callParent();
55161         if (this.hidden === false) {
55162             me.setPagePosition(-10000, -10000);
55163
55164             if (me.anchor) {
55165                 me.anchor = me.origAnchor;
55166             }
55167             me.showAt(me.getTargetXY());
55168
55169             if (me.anchor) {
55170                 me.syncAnchor();
55171                 me.anchorEl.show();
55172             } else {
55173                 me.anchorEl.hide();
55174             }
55175         }
55176     },
55177
55178     // inherit docs
55179     showAt: function(xy) {
55180         var me = this;
55181         me.lastActive = new Date();
55182         me.clearTimers();
55183
55184         // Only call if this is hidden. May have been called from show above.
55185         if (!me.isVisible()) {
55186             this.callParent(arguments);
55187         }
55188
55189         // Show may have been vetoed.
55190         if (me.isVisible()) {
55191             me.setPagePosition(xy[0], xy[1]);
55192             if (me.constrainPosition || me.constrain) {
55193                 me.doConstrain();
55194             }
55195             me.toFront(true);
55196         }
55197
55198         if (me.dismissDelay && me.autoHide !== false) {
55199             me.dismissTimer = Ext.defer(me.hide, me.dismissDelay, me);
55200         }
55201         if (me.anchor) {
55202             me.syncAnchor();
55203             if (!me.anchorEl.isVisible()) {
55204                 me.anchorEl.show();
55205             }
55206         } else {
55207             me.anchorEl.hide();
55208         }
55209     },
55210
55211     // private
55212     syncAnchor: function() {
55213         var me = this,
55214             anchorPos,
55215             targetPos,
55216             offset;
55217         switch (me.tipAnchor.charAt(0)) {
55218         case 't':
55219             anchorPos = 'b';
55220             targetPos = 'tl';
55221             offset = [20 + me.anchorOffset, 1];
55222             break;
55223         case 'r':
55224             anchorPos = 'l';
55225             targetPos = 'tr';
55226             offset = [ - 1, 12 + me.anchorOffset];
55227             break;
55228         case 'b':
55229             anchorPos = 't';
55230             targetPos = 'bl';
55231             offset = [20 + me.anchorOffset, -1];
55232             break;
55233         default:
55234             anchorPos = 'r';
55235             targetPos = 'tl';
55236             offset = [1, 12 + me.anchorOffset];
55237             break;
55238         }
55239         me.anchorEl.alignTo(me.el, anchorPos + '-' + targetPos, offset);
55240     },
55241
55242     // private
55243     setPagePosition: function(x, y) {
55244         var me = this;
55245         me.callParent(arguments);
55246         if (me.anchor) {
55247             me.syncAnchor();
55248         }
55249     },
55250
55251     // private
55252     clearTimer: function(name) {
55253         name = name + 'Timer';
55254         clearTimeout(this[name]);
55255         delete this[name];
55256     },
55257
55258     // private
55259     clearTimers: function() {
55260         var me = this;
55261         me.clearTimer('show');
55262         me.clearTimer('dismiss');
55263         me.clearTimer('hide');
55264     },
55265
55266     // private
55267     onShow: function() {
55268         var me = this;
55269         me.callParent();
55270         me.mon(Ext.getDoc(), 'mousedown', me.onDocMouseDown, me);
55271     },
55272
55273     // private
55274     onHide: function() {
55275         var me = this;
55276         me.callParent();
55277         me.mun(Ext.getDoc(), 'mousedown', me.onDocMouseDown, me);
55278     },
55279
55280     // private
55281     onDocMouseDown: function(e) {
55282         var me = this;
55283         if (me.autoHide !== true && !me.closable && !e.within(me.el.dom)) {
55284             me.disable();
55285             Ext.defer(me.doEnable, 100, me);
55286         }
55287     },
55288
55289     // private
55290     doEnable: function() {
55291         if (!this.isDestroyed) {
55292             this.enable();
55293         }
55294     },
55295
55296     // private
55297     onDisable: function() {
55298         this.callParent();
55299         this.clearTimers();
55300         this.hide();
55301     },
55302
55303     beforeDestroy: function() {
55304         var me = this;
55305         me.clearTimers();
55306         Ext.destroy(me.anchorEl);
55307         delete me.anchorEl;
55308         delete me.target;
55309         delete me.anchorTarget;
55310         delete me.triggerElement;
55311         me.callParent();
55312     },
55313
55314     // private
55315     onDestroy: function() {
55316         Ext.getDoc().un('mousedown', this.onDocMouseDown, this);
55317         this.callParent();
55318     }
55319 });
55320
55321 /**
55322  * @class Ext.tip.QuickTip
55323  * @extends Ext.tip.ToolTip
55324  * A specialized tooltip class for tooltips that can be specified in markup and automatically managed by the global
55325  * {@link Ext.tip.QuickTipManager} instance.  See the QuickTipManager class header for additional usage details and examples.
55326  * @constructor
55327  * Create a new Tip
55328  * @param {Object} config The configuration options
55329  * @xtype quicktip
55330  */
55331 Ext.define('Ext.tip.QuickTip', {
55332     extend: 'Ext.tip.ToolTip',
55333     alternateClassName: 'Ext.QuickTip',
55334     /**
55335      * @cfg {Mixed} target The target HTMLElement, Ext.core.Element or id to associate with this Quicktip (defaults to the document).
55336      */
55337     /**
55338      * @cfg {Boolean} interceptTitles True to automatically use the element's DOM title value if available (defaults to false).
55339      */
55340     interceptTitles : false,
55341
55342     // Force creation of header Component
55343     title: '&#160;',
55344
55345     // private
55346     tagConfig : {
55347         namespace : "data-",
55348         attribute : "qtip",
55349         width : "qwidth",
55350         target : "target",
55351         title : "qtitle",
55352         hide : "hide",
55353         cls : "qclass",
55354         align : "qalign",
55355         anchor : "anchor"
55356     },
55357
55358     // private
55359     initComponent : function(){
55360         var me = this;
55361         
55362         me.target = me.target || Ext.getDoc();
55363         me.targets = me.targets || {};
55364         me.callParent();
55365     },
55366
55367     /**
55368      * Configures a new quick tip instance and assigns it to a target element.  The following config values are
55369      * supported (for example usage, see the {@link Ext.tip.QuickTipManager} class header):
55370      * <div class="mdetail-params"><ul>
55371      * <li>autoHide</li>
55372      * <li>cls</li>
55373      * <li>dismissDelay (overrides the singleton value)</li>
55374      * <li>target (required)</li>
55375      * <li>text (required)</li>
55376      * <li>title</li>
55377      * <li>width</li></ul></div>
55378      * @param {Object} config The config object
55379      */
55380     register : function(config){
55381         var configs = Ext.isArray(config) ? config : arguments,
55382             i = 0,
55383             len = configs.length,
55384             target, j, targetLen;
55385             
55386         for (; i < len; i++) {
55387             config = configs[i];
55388             target = config.target;
55389             if (target) {
55390                 if (Ext.isArray(target)) {
55391                     for (j = 0, targetLen = target.length; j < targetLen; j++) {
55392                         this.targets[Ext.id(target[j])] = config;
55393                     }
55394                 } else{
55395                     this.targets[Ext.id(target)] = config;
55396                 }
55397             }
55398         }
55399     },
55400
55401     /**
55402      * Removes this quick tip from its element and destroys it.
55403      * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
55404      */
55405     unregister : function(el){
55406         delete this.targets[Ext.id(el)];
55407     },
55408     
55409     /**
55410      * Hides a visible tip or cancels an impending show for a particular element.
55411      * @param {String/HTMLElement/Element} el The element that is the target of the tip.
55412      */
55413     cancelShow: function(el){
55414         var me = this,
55415             activeTarget = me.activeTarget;
55416             
55417         el = Ext.get(el).dom;
55418         if (me.isVisible()) {
55419             if (activeTarget && activeTarget.el == el) {
55420                 me.hide();
55421             }
55422         } else if (activeTarget && activeTarget.el == el) {
55423             me.clearTimer('show');
55424         }
55425     },
55426     
55427     getTipCfg: function(e) {
55428         var t = e.getTarget(),
55429             ttp, 
55430             cfg;
55431         
55432         if(this.interceptTitles && t.title && Ext.isString(t.title)){
55433             ttp = t.title;
55434             t.qtip = ttp;
55435             t.removeAttribute("title");
55436             e.preventDefault();
55437         } 
55438         else {            
55439             cfg = this.tagConfig;
55440             t = e.getTarget('[' + cfg.namespace + cfg.attribute + ']');
55441             if (t) {
55442                 ttp = t.getAttribute(cfg.namespace + cfg.attribute);
55443             }
55444         }
55445         return ttp;
55446     },
55447
55448     // private
55449     onTargetOver : function(e){
55450         var me = this,
55451             target = e.getTarget(),
55452             elTarget,
55453             cfg,
55454             ns,
55455             ttp,
55456             autoHide;
55457         
55458         if (me.disabled) {
55459             return;
55460         }
55461
55462         // TODO - this causes "e" to be recycled in IE6/7 (EXTJSIV-1608) so ToolTip#setTarget
55463         // was changed to include freezeEvent. The issue seems to be a nested 'resize' event
55464         // that smashed Ext.EventObject.
55465         me.targetXY = e.getXY();
55466
55467         if(!target || target.nodeType !== 1 || target == document || target == document.body){
55468             return;
55469         }
55470         
55471         if (me.activeTarget && ((target == me.activeTarget.el) || Ext.fly(me.activeTarget.el).contains(target))) {
55472             me.clearTimer('hide');
55473             me.show();
55474             return;
55475         }
55476         
55477         if (target) {
55478             Ext.Object.each(me.targets, function(key, value) {
55479                 var targetEl = Ext.fly(value.target);
55480                 if (targetEl && (targetEl.dom === target || targetEl.contains(target))) {
55481                     elTarget = targetEl.dom;
55482                     return false;
55483                 }
55484             });
55485             if (elTarget) {
55486                 me.activeTarget = me.targets[elTarget.id];
55487                 me.activeTarget.el = target;
55488                 me.anchor = me.activeTarget.anchor;
55489                 if (me.anchor) {
55490                     me.anchorTarget = target;
55491                 }
55492                 me.delayShow();
55493                 return;
55494             }
55495         }
55496
55497         elTarget = Ext.get(target);
55498         cfg = me.tagConfig;
55499         ns = cfg.namespace; 
55500         ttp = me.getTipCfg(e);
55501         
55502         if (ttp) {
55503             autoHide = elTarget.getAttribute(ns + cfg.hide);
55504                  
55505             me.activeTarget = {
55506                 el: target,
55507                 text: ttp,
55508                 width: +elTarget.getAttribute(ns + cfg.width) || null,
55509                 autoHide: autoHide != "user" && autoHide !== 'false',
55510                 title: elTarget.getAttribute(ns + cfg.title),
55511                 cls: elTarget.getAttribute(ns + cfg.cls),
55512                 align: elTarget.getAttribute(ns + cfg.align)
55513                 
55514             };
55515             me.anchor = elTarget.getAttribute(ns + cfg.anchor);
55516             if (me.anchor) {
55517                 me.anchorTarget = target;
55518             }
55519             me.delayShow();
55520         }
55521     },
55522
55523     // private
55524     onTargetOut : function(e){
55525         var me = this;
55526         
55527         // If moving within the current target, and it does not have a new tip, ignore the mouseout
55528         if (me.activeTarget && e.within(me.activeTarget.el) && !me.getTipCfg(e)) {
55529             return;
55530         }
55531
55532         me.clearTimer('show');
55533         if (me.autoHide !== false) {
55534             me.delayHide();
55535         }
55536     },
55537
55538     // inherit docs
55539     showAt : function(xy){
55540         var me = this,
55541             target = me.activeTarget;
55542         
55543         if (target) {
55544             if (!me.rendered) {
55545                 me.render(Ext.getBody());
55546                 me.activeTarget = target;
55547             }
55548             if (target.title) {
55549                 me.setTitle(target.title || '');
55550                 me.header.show();
55551             } else {
55552                 me.header.hide();
55553             }
55554             me.body.update(target.text);
55555             me.autoHide = target.autoHide;
55556             me.dismissDelay = target.dismissDelay || me.dismissDelay;
55557             if (me.lastCls) {
55558                 me.el.removeCls(me.lastCls);
55559                 delete me.lastCls;
55560             }
55561             if (target.cls) {
55562                 me.el.addCls(target.cls);
55563                 me.lastCls = target.cls;
55564             }
55565
55566             me.setWidth(target.width);
55567             
55568             if (me.anchor) {
55569                 me.constrainPosition = false;
55570             } else if (target.align) { // TODO: this doesn't seem to work consistently
55571                 xy = me.el.getAlignToXY(target.el, target.align);
55572                 me.constrainPosition = false;
55573             }else{
55574                 me.constrainPosition = true;
55575             }
55576         }
55577         me.callParent([xy]);
55578     },
55579
55580     // inherit docs
55581     hide: function(){
55582         delete this.activeTarget;
55583         this.callParent();
55584     }
55585 });
55586
55587 /**
55588  * @class Ext.tip.QuickTipManager
55589  * <p>Provides attractive and customizable tooltips for any element. The QuickTips
55590  * singleton is used to configure and manage tooltips globally for multiple elements
55591  * in a generic manner.  To create individual tooltips with maximum customizability,
55592  * you should consider either {@link Ext.tip.Tip} or {@link Ext.tip.ToolTip}.</p>
55593  * <p>Quicktips can be configured via tag attributes directly in markup, or by
55594  * registering quick tips programmatically via the {@link #register} method.</p>
55595  * <p>The singleton's instance of {@link Ext.tip.QuickTip} is available via
55596  * {@link #getQuickTip}, and supports all the methods, and all the all the
55597  * configuration properties of Ext.tip.QuickTip. These settings will apply to all
55598  * tooltips shown by the singleton.</p>
55599  * <p>Below is the summary of the configuration properties which can be used.
55600  * For detailed descriptions see the config options for the {@link Ext.tip.QuickTip QuickTip} class</p>
55601  * <p><b>QuickTips singleton configs (all are optional)</b></p>
55602  * <div class="mdetail-params"><ul><li>dismissDelay</li>
55603  * <li>hideDelay</li>
55604  * <li>maxWidth</li>
55605  * <li>minWidth</li>
55606  * <li>showDelay</li>
55607  * <li>trackMouse</li></ul></div>
55608  * <p><b>Target element configs (optional unless otherwise noted)</b></p>
55609  * <div class="mdetail-params"><ul><li>autoHide</li>
55610  * <li>cls</li>
55611  * <li>dismissDelay (overrides singleton value)</li>
55612  * <li>target (required)</li>
55613  * <li>text (required)</li>
55614  * <li>title</li>
55615  * <li>width</li></ul></div>
55616  * <p>Here is an example showing how some of these config options could be used:</p>
55617  *
55618  * {@img Ext.tip.QuickTipManager/Ext.tip.QuickTipManager.png Ext.tip.QuickTipManager component}
55619  *
55620  * ## Code
55621  *    // Init the singleton.  Any tag-based quick tips will start working.
55622  *    Ext.tip.QuickTipManager.init();
55623  *    
55624  *    // Apply a set of config properties to the singleton
55625  *    Ext.apply(Ext.tip.QuickTipManager.getQuickTip(), {
55626  *        maxWidth: 200,
55627  *        minWidth: 100,
55628  *        showDelay: 50      // Show 50ms after entering target
55629  *    });
55630  *    
55631  *    // Create a small panel to add a quick tip to
55632  *    Ext.create('Ext.container.Container', {
55633  *        id: 'quickTipContainer',
55634  *        width: 200,
55635  *        height: 150,
55636  *        style: {
55637  *            backgroundColor:'#000000'
55638  *        },
55639  *        renderTo: Ext.getBody()
55640  *    });
55641  *
55642  *    
55643  *    // Manually register a quick tip for a specific element
55644  *    Ext.tip.QuickTipManager.register({
55645  *        target: 'quickTipContainer',
55646  *        title: 'My Tooltip',
55647  *        text: 'This tooltip was added in code',
55648  *        width: 100,
55649  *        dismissDelay: 10000 // Hide after 10 seconds hover
55650  *    });
55651 </code></pre>
55652  * <p>To register a quick tip in markup, you simply add one or more of the valid QuickTip attributes prefixed with
55653  * the <b>ext:</b> namespace.  The HTML element itself is automatically set as the quick tip target. Here is the summary
55654  * of supported attributes (optional unless otherwise noted):</p>
55655  * <ul><li><b>hide</b>: Specifying "user" is equivalent to setting autoHide = false.  Any other value will be the
55656  * same as autoHide = true.</li>
55657  * <li><b>qclass</b>: A CSS class to be applied to the quick tip (equivalent to the 'cls' target element config).</li>
55658  * <li><b>qtip (required)</b>: The quick tip text (equivalent to the 'text' target element config).</li>
55659  * <li><b>qtitle</b>: The quick tip title (equivalent to the 'title' target element config).</li>
55660  * <li><b>qwidth</b>: The quick tip width (equivalent to the 'width' target element config).</li></ul>
55661  * <p>Here is an example of configuring an HTML element to display a tooltip from markup:</p>
55662  * <pre><code>
55663 // Add a quick tip to an HTML button
55664 &lt;input type="button" value="OK" ext:qtitle="OK Button" ext:qwidth="100"
55665      data-qtip="This is a quick tip from markup!">&lt;/input>
55666 </code></pre>
55667  * @singleton
55668  */
55669 Ext.define('Ext.tip.QuickTipManager', function() {
55670     var tip,
55671         disabled = false;
55672
55673     return {
55674         requires: ['Ext.tip.QuickTip'],
55675         singleton: true,
55676         alternateClassName: 'Ext.QuickTips',
55677         /**
55678          * Initialize the global QuickTips instance and prepare any quick tips.
55679          * @param {Boolean} autoRender True to render the QuickTips container immediately to preload images. (Defaults to true) 
55680          */
55681         init : function(autoRender){
55682             if (!tip) {
55683                 if (!Ext.isReady) {
55684                     Ext.onReady(function(){
55685                         Ext.tip.QuickTipManager.init(autoRender);
55686                     });
55687                     return;
55688                 }
55689                 tip = Ext.create('Ext.tip.QuickTip', {
55690                     disabled: disabled,
55691                     renderTo: autoRender !== false ? document.body : undefined
55692                 });
55693             }
55694         },
55695
55696         /**
55697          * Destroy the QuickTips instance.
55698          */
55699         destroy: function() {
55700             if (tip) {
55701                 var undef;
55702                 tip.destroy();
55703                 tip = undef;
55704             }
55705         },
55706
55707         // Protected method called by the dd classes
55708         ddDisable : function(){
55709             // don't disable it if we don't need to
55710             if(tip && !disabled){
55711                 tip.disable();
55712             }
55713         },
55714
55715         // Protected method called by the dd classes
55716         ddEnable : function(){
55717             // only enable it if it hasn't been disabled
55718             if(tip && !disabled){
55719                 tip.enable();
55720             }
55721         },
55722
55723         /**
55724          * Enable quick tips globally.
55725          */
55726         enable : function(){
55727             if(tip){
55728                 tip.enable();
55729             }
55730             disabled = false;
55731         },
55732
55733         /**
55734          * Disable quick tips globally.
55735          */
55736         disable : function(){
55737             if(tip){
55738                 tip.disable();
55739             }
55740             disabled = true;
55741         },
55742
55743         /**
55744          * Returns true if quick tips are enabled, else false.
55745          * @return {Boolean}
55746          */
55747         isEnabled : function(){
55748             return tip !== undefined && !tip.disabled;
55749         },
55750
55751         /**
55752          * Gets the single {@link Ext.tip.QuickTip QuickTip} instance used to show tips from all registered elements.
55753          * @return {Ext.tip.QuickTip}
55754          */
55755         getQuickTip : function(){
55756             return tip;
55757         },
55758
55759         /**
55760          * Configures a new quick tip instance and assigns it to a target element.  See
55761          * {@link Ext.tip.QuickTip#register} for details.
55762          * @param {Object} config The config object
55763          */
55764         register : function(){
55765             tip.register.apply(tip, arguments);
55766         },
55767
55768         /**
55769          * Removes any registered quick tip from the target element and destroys it.
55770          * @param {String/HTMLElement/Element} el The element from which the quick tip is to be removed.
55771          */
55772         unregister : function(){
55773             tip.unregister.apply(tip, arguments);
55774         },
55775
55776         /**
55777          * Alias of {@link #register}.
55778          * @param {Object} config The config object
55779          */
55780         tips : function(){
55781             tip.register.apply(tip, arguments);
55782         }
55783     };
55784 }());
55785 /**
55786  * @class Ext.app.Application
55787  * @constructor
55788  * 
55789  * Represents an Ext JS 4 application, which is typically a single page app using a {@link Ext.container.Viewport Viewport}.
55790  * A typical Ext.app.Application might look like this:
55791  * 
55792  * Ext.application({
55793      name: 'MyApp',
55794      launch: function() {
55795          Ext.create('Ext.container.Viewport', {
55796              items: {
55797                  html: 'My App'
55798              }
55799          });
55800      }
55801  });
55802  * 
55803  * This does several things. First it creates a global variable called 'MyApp' - all of your Application's classes (such
55804  * as its Models, Views and Controllers) will reside under this single namespace, which drastically lowers the chances
55805  * of colliding global variables.
55806  * 
55807  * When the page is ready and all of your JavaScript has loaded, your Application's {@link #launch} function is called,
55808  * at which time you can run the code that starts your app. Usually this consists of creating a Viewport, as we do in
55809  * the example above.
55810  * 
55811  * <u>Telling Application about the rest of the app</u>
55812  * 
55813  * Because an Ext.app.Application represents an entire app, we should tell it about the other parts of the app - namely
55814  * the Models, Views and Controllers that are bundled with the application. Let's say we have a blog management app; we
55815  * might have Models and Controllers for Posts and Comments, and Views for listing, adding and editing Posts and Comments.
55816  * Here's how we'd tell our Application about all these things:
55817  * 
55818  * Ext.application({
55819      name: 'Blog',
55820      models: ['Post', 'Comment'],
55821      controllers: ['Posts', 'Comments'],
55822
55823      launch: function() {
55824          ...
55825      }
55826  });
55827  * 
55828  * Note that we didn't actually list the Views directly in the Application itself. This is because Views are managed by
55829  * Controllers, so it makes sense to keep those dependencies there. The Application will load each of the specified 
55830  * Controllers using the pathing conventions laid out in the <a href="../guide/application_architecture">application 
55831  * architecture guide</a> - in this case expecting the controllers to reside in app/controller/Posts.js and
55832  * app/controller/Comments.js. In turn, each Controller simply needs to list the Views it uses and they will be
55833  * automatically loaded. Here's how our Posts controller like be defined:
55834  * 
55835  * Ext.define('MyApp.controller.Posts', {
55836      extend: 'Ext.app.Controller',
55837      views: ['posts.List', 'posts.Edit'],
55838
55839      //the rest of the Controller here
55840  });
55841  * 
55842  * Because we told our Application about our Models and Controllers, and our Controllers about their Views, Ext JS will
55843  * automatically load all of our app files for us. This means we don't have to manually add script tags into our html
55844  * files whenever we add a new class, but more importantly it enables us to create a minimized build of our entire 
55845  * application using the Ext JS 4 SDK Tools.
55846  * 
55847  * For more information about writing Ext JS 4 applications, please see the <a href="../guide/application_architecture">
55848  * application architecture guide</a>.
55849  * 
55850  * @markdown
55851  * @docauthor Ed Spencer
55852  */
55853 Ext.define('Ext.app.Application', {
55854     extend: 'Ext.app.Controller',
55855
55856     requires: [
55857         'Ext.ModelManager',
55858         'Ext.data.Model',
55859         'Ext.data.StoreManager',
55860         'Ext.tip.QuickTipManager',
55861         'Ext.ComponentManager',
55862         'Ext.app.EventBus'
55863     ],
55864
55865     /**
55866      * @cfg {Object} name The name of your application. This will also be the namespace for your views, controllers
55867      * models and stores. Don't use spaces or special characters in the name.
55868      */
55869
55870     /**
55871      * @cfg {Object} scope The scope to execute the {@link #launch} function in. Defaults to the Application
55872      * instance.
55873      */
55874     scope: undefined,
55875
55876     /**
55877      * @cfg {Boolean} enableQuickTips True to automatically set up Ext.tip.QuickTip support (defaults to true)
55878      */
55879     enableQuickTips: true,
55880
55881     /**
55882      * @cfg {String} defaultUrl When the app is first loaded, this url will be redirected to. Defaults to undefined
55883      */
55884
55885     /**
55886      * @cfg {String} appFolder The path to the directory which contains all application's classes.
55887      * This path will be registered via {@link Ext.Loader#setPath} for the namespace specified in the {@link #name name} config.
55888      * Defaults to 'app'
55889      */
55890     appFolder: 'app',
55891
55892     /**
55893      * @cfg {Boolean} autoCreateViewport Automatically loads and instantiates AppName.view.Viewport before firing the launch function.
55894      */
55895     autoCreateViewport: true,
55896
55897     constructor: function(config) {
55898         config = config || {};
55899         Ext.apply(this, config);
55900
55901         var requires = config.requires || [];
55902
55903         Ext.Loader.setPath(this.name, this.appFolder);
55904
55905         if (this.paths) {
55906             Ext.Object.each(this.paths, function(key, value) {
55907                 Ext.Loader.setPath(key, value);
55908             });
55909         }
55910
55911         this.callParent(arguments);
55912
55913         this.eventbus = Ext.create('Ext.app.EventBus');
55914
55915         var controllers = this.controllers,
55916             ln = controllers.length,
55917             i, controller;
55918
55919         this.controllers = Ext.create('Ext.util.MixedCollection');
55920
55921         if (this.autoCreateViewport) {
55922             requires.push(this.getModuleClassName('Viewport', 'view'));
55923         }
55924
55925         for (i = 0; i < ln; i++) {
55926             requires.push(this.getModuleClassName(controllers[i], 'controller'));
55927         }
55928
55929         Ext.require(requires);
55930
55931         Ext.onReady(function() {
55932             for (i = 0; i < ln; i++) {
55933                 controller = this.getController(controllers[i]);
55934                 controller.init(this);
55935             }
55936
55937             this.onBeforeLaunch.call(this);
55938         }, this);
55939     },
55940
55941     control: function(selectors, listeners, controller) {
55942         this.eventbus.control(selectors, listeners, controller);
55943     },
55944
55945     /**
55946      * Called automatically when the page has completely loaded. This is an empty function that should be
55947      * overridden by each application that needs to take action on page load
55948      * @property launch
55949      * @type Function
55950      * @param {String} profile The detected {@link #profiles application profile}
55951      * @return {Boolean} By default, the Application will dispatch to the configured startup controller and
55952      * action immediately after running the launch function. Return false to prevent this behavior.
55953      */
55954     launch: Ext.emptyFn,
55955
55956     /**
55957      * @private
55958      */
55959     onBeforeLaunch: function() {
55960         if (this.enableQuickTips) {
55961             Ext.tip.QuickTipManager.init();
55962         }
55963
55964         if (this.autoCreateViewport) {
55965             this.getView('Viewport').create();
55966         }
55967
55968         this.launch.call(this.scope || this);
55969         this.launched = true;
55970         this.fireEvent('launch', this);
55971
55972         this.controllers.each(function(controller) {
55973             controller.onLaunch(this);
55974         }, this);
55975     },
55976
55977     getModuleClassName: function(name, type) {
55978         var namespace = Ext.Loader.getPrefix(name);
55979
55980         if (namespace.length > 0 && namespace !== name) {
55981             return name;
55982         }
55983
55984         return this.name + '.' + type + '.' + name;
55985     },
55986
55987     getController: function(name) {
55988         var controller = this.controllers.get(name);
55989
55990         if (!controller) {
55991             controller = Ext.create(this.getModuleClassName(name, 'controller'), {
55992                 application: this,
55993                 id: name
55994             });
55995
55996             this.controllers.add(controller);
55997         }
55998
55999         return controller;
56000     },
56001
56002     getStore: function(name) {
56003         var store = Ext.StoreManager.get(name);
56004
56005         if (!store) {
56006             store = Ext.create(this.getModuleClassName(name, 'store'), {
56007                 storeId: name
56008             });
56009         }
56010
56011         return store;
56012     },
56013
56014     getModel: function(model) {
56015         model = this.getModuleClassName(model, 'model');
56016
56017         return Ext.ModelManager.getModel(model);
56018     },
56019
56020     getView: function(view) {
56021         view = this.getModuleClassName(view, 'view');
56022
56023         return Ext.ClassManager.get(view);
56024     }
56025 });
56026
56027 /**
56028  * @class Ext.chart.Callout
56029  * @ignore
56030  */
56031 Ext.define('Ext.chart.Callout', {
56032
56033     /* Begin Definitions */
56034
56035     /* End Definitions */
56036
56037     constructor: function(config) {
56038         if (config.callouts) {
56039             config.callouts.styles = Ext.applyIf(config.callouts.styles || {}, {
56040                 color: "#000",
56041                 font: "11px Helvetica, sans-serif"
56042             });
56043             this.callouts = Ext.apply(this.callouts || {}, config.callouts);
56044             this.calloutsArray = [];
56045         }
56046     },
56047
56048     renderCallouts: function() {
56049         if (!this.callouts) {
56050             return;
56051         }
56052
56053         var me = this,
56054             items = me.items,
56055             animate = me.chart.animate,
56056             config = me.callouts,
56057             styles = config.styles,
56058             group = me.calloutsArray,
56059             store = me.chart.store,
56060             len = store.getCount(),
56061             ratio = items.length / len,
56062             previouslyPlacedCallouts = [],
56063             i,
56064             count,
56065             j,
56066             p;
56067             
56068         for (i = 0, count = 0; i < len; i++) {
56069             for (j = 0; j < ratio; j++) {
56070                 var item = items[count],
56071                     label = group[count],
56072                     storeItem = store.getAt(i),
56073                     display;
56074                 
56075                 display = config.filter(storeItem);
56076                 
56077                 if (!display && !label) {
56078                     count++;
56079                     continue;               
56080                 }
56081                 
56082                 if (!label) {
56083                     group[count] = label = me.onCreateCallout(storeItem, item, i, display, j, count);
56084                 }
56085                 for (p in label) {
56086                     if (label[p] && label[p].setAttributes) {
56087                         label[p].setAttributes(styles, true);
56088                     }
56089                 }
56090                 if (!display) {
56091                     for (p in label) {
56092                         if (label[p]) {
56093                             if (label[p].setAttributes) {
56094                                 label[p].setAttributes({
56095                                     hidden: true
56096                                 }, true);
56097                             } else if(label[p].setVisible) {
56098                                 label[p].setVisible(false);
56099                             }
56100                         }
56101                     }
56102                 }
56103                 config.renderer(label, storeItem);
56104                 me.onPlaceCallout(label, storeItem, item, i, display, animate,
56105                                   j, count, previouslyPlacedCallouts);
56106                 previouslyPlacedCallouts.push(label);
56107                 count++;
56108             }
56109         }
56110         this.hideCallouts(count);
56111     },
56112
56113     onCreateCallout: function(storeItem, item, i, display) {
56114         var me = this,
56115             group = me.calloutsGroup,
56116             config = me.callouts,
56117             styles = config.styles,
56118             width = styles.width,
56119             height = styles.height,
56120             chart = me.chart,
56121             surface = chart.surface,
56122             calloutObj = {
56123                 //label: false,
56124                 //box: false,
56125                 lines: false
56126             };
56127
56128         calloutObj.lines = surface.add(Ext.apply({},
56129         {
56130             type: 'path',
56131             path: 'M0,0',
56132             stroke: me.getLegendColor() || '#555'
56133         },
56134         styles));
56135
56136         if (config.items) {
56137             calloutObj.panel = Ext.create('widget.panel', {
56138                 style: "position: absolute;",    
56139                 width: width,
56140                 height: height,
56141                 items: config.items,
56142                 renderTo: chart.el
56143             });
56144         }
56145
56146         return calloutObj;
56147     },
56148
56149     hideCallouts: function(index) {
56150         var calloutsArray = this.calloutsArray,
56151             len = calloutsArray.length,
56152             co,
56153             p;
56154         while (len-->index) {
56155             co = calloutsArray[len];
56156             for (p in co) {
56157                 if (co[p]) {
56158                     co[p].hide(true);
56159                 }
56160             }
56161         }
56162     }
56163 });
56164
56165 /**
56166  * @class Ext.draw.CompositeSprite
56167  * @extends Ext.util.MixedCollection
56168  *
56169  * A composite Sprite handles a group of sprites with common methods to a sprite
56170  * such as `hide`, `show`, `setAttributes`. These methods are applied to the set of sprites
56171  * added to the group.
56172  *
56173  * CompositeSprite extends {@link Ext.util.MixedCollection} so you can use the same methods
56174  * in `MixedCollection` to iterate through sprites, add and remove elements, etc.
56175  *
56176  * In order to create a CompositeSprite, one has to provide a handle to the surface where it is
56177  * rendered:
56178  *
56179  *     var group = Ext.create('Ext.draw.CompositeSprite', {
56180  *         surface: drawComponent.surface
56181  *     });
56182  *                  
56183  * Then just by using `MixedCollection` methods it's possible to add {@link Ext.draw.Sprite}s:
56184  *  
56185  *     group.add(sprite1);
56186  *     group.add(sprite2);
56187  *     group.add(sprite3);
56188  *                  
56189  * And then apply common Sprite methods to them:
56190  *  
56191  *     group.setAttributes({
56192  *         fill: '#f00'
56193  *     }, true);
56194  */
56195 Ext.define('Ext.draw.CompositeSprite', {
56196
56197     /* Begin Definitions */
56198
56199     extend: 'Ext.util.MixedCollection',
56200     mixins: {
56201         animate: 'Ext.util.Animate'
56202     },
56203
56204     /* End Definitions */
56205     isCompositeSprite: true,
56206     constructor: function(config) {
56207         var me = this;
56208         
56209         config = config || {};
56210         Ext.apply(me, config);
56211
56212         me.addEvents(
56213             'mousedown',
56214             'mouseup',
56215             'mouseover',
56216             'mouseout',
56217             'click'
56218         );
56219         me.id = Ext.id(null, 'ext-sprite-group-');
56220         me.callParent();
56221     },
56222
56223     // @private
56224     onClick: function(e) {
56225         this.fireEvent('click', e);
56226     },
56227
56228     // @private
56229     onMouseUp: function(e) {
56230         this.fireEvent('mouseup', e);
56231     },
56232
56233     // @private
56234     onMouseDown: function(e) {
56235         this.fireEvent('mousedown', e);
56236     },
56237
56238     // @private
56239     onMouseOver: function(e) {
56240         this.fireEvent('mouseover', e);
56241     },
56242
56243     // @private
56244     onMouseOut: function(e) {
56245         this.fireEvent('mouseout', e);
56246     },
56247
56248     attachEvents: function(o) {
56249         var me = this;
56250         
56251         o.on({
56252             scope: me,
56253             mousedown: me.onMouseDown,
56254             mouseup: me.onMouseUp,
56255             mouseover: me.onMouseOver,
56256             mouseout: me.onMouseOut,
56257             click: me.onClick
56258         });
56259     },
56260
56261     /** Add a Sprite to the Group */
56262     add: function(key, o) {
56263         var result = this.callParent(arguments);
56264         this.attachEvents(result);
56265         return result;
56266     },
56267
56268     insert: function(index, key, o) {
56269         return this.callParent(arguments);
56270     },
56271
56272     /** Remove a Sprite from the Group */
56273     remove: function(o) {
56274         var me = this;
56275         
56276         o.un({
56277             scope: me,
56278             mousedown: me.onMouseDown,
56279             mouseup: me.onMouseUp,
56280             mouseover: me.onMouseOver,
56281             mouseout: me.onMouseOut,
56282             click: me.onClick
56283         });
56284         me.callParent(arguments);
56285     },
56286     
56287     /**
56288      * Returns the group bounding box.
56289      * Behaves like {@link Ext.draw.Sprite} getBBox method.
56290     */
56291     getBBox: function() {
56292         var i = 0,
56293             sprite,
56294             bb,
56295             items = this.items,
56296             len = this.length,
56297             infinity = Infinity,
56298             minX = infinity,
56299             maxHeight = -infinity,
56300             minY = infinity,
56301             maxWidth = -infinity,
56302             maxWidthBBox, maxHeightBBox;
56303         
56304         for (; i < len; i++) {
56305             sprite = items[i];
56306             if (sprite.el) {
56307                 bb = sprite.getBBox();
56308                 minX = Math.min(minX, bb.x);
56309                 minY = Math.min(minY, bb.y);
56310                 maxHeight = Math.max(maxHeight, bb.height + bb.y);
56311                 maxWidth = Math.max(maxWidth, bb.width + bb.x);
56312             }
56313         }
56314         
56315         return {
56316             x: minX,
56317             y: minY,
56318             height: maxHeight - minY,
56319             width: maxWidth - minX
56320         };
56321     },
56322
56323     /**
56324      *  Iterates through all sprites calling
56325      *  `setAttributes` on each one. For more information
56326      *  {@link Ext.draw.Sprite} provides a description of the
56327      *  attributes that can be set with this method.
56328      */
56329     setAttributes: function(attrs, redraw) {
56330         var i = 0,
56331             items = this.items,
56332             len = this.length;
56333             
56334         for (; i < len; i++) {
56335             items[i].setAttributes(attrs, redraw);
56336         }
56337         return this;
56338     },
56339
56340     /**
56341      * Hides all sprites. If the first parameter of the method is true
56342      * then a redraw will be forced for each sprite.
56343      */
56344     hide: function(attrs) {
56345         var i = 0,
56346             items = this.items,
56347             len = this.length;
56348             
56349         for (; i < len; i++) {
56350             items[i].hide();
56351         }
56352         return this;
56353     },
56354
56355     /**
56356      * Shows all sprites. If the first parameter of the method is true
56357      * then a redraw will be forced for each sprite.
56358      */
56359     show: function(attrs) {
56360         var i = 0,
56361             items = this.items,
56362             len = this.length;
56363             
56364         for (; i < len; i++) {
56365             items[i].show();
56366         }
56367         return this;
56368     },
56369
56370     redraw: function() {
56371         var me = this,
56372             i = 0,
56373             items = me.items,
56374             surface = me.getSurface(),
56375             len = me.length;
56376         
56377         if (surface) {
56378             for (; i < len; i++) {
56379                 surface.renderItem(items[i]);
56380             }
56381         }
56382         return me;
56383     },
56384
56385     setStyle: function(obj) {
56386         var i = 0,
56387             items = this.items,
56388             len = this.length,
56389             item, el;
56390             
56391         for (; i < len; i++) {
56392             item = items[i];
56393             el = item.el;
56394             if (el) {
56395                 el.setStyle(obj);
56396             }
56397         }
56398     },
56399
56400     addCls: function(obj) {
56401         var i = 0,
56402             items = this.items,
56403             surface = this.getSurface(),
56404             len = this.length;
56405         
56406         if (surface) {
56407             for (; i < len; i++) {
56408                 surface.addCls(items[i], obj);
56409             }
56410         }
56411     },
56412
56413     removeCls: function(obj) {
56414         var i = 0,
56415             items = this.items,
56416             surface = this.getSurface(),
56417             len = this.length;
56418         
56419         if (surface) {
56420             for (; i < len; i++) {
56421                 surface.removeCls(items[i], obj);
56422             }
56423         }
56424     },
56425     
56426     /**
56427      * Grab the surface from the items
56428      * @private
56429      * @return {Ext.draw.Surface} The surface, null if not found
56430      */
56431     getSurface: function(){
56432         var first = this.first();
56433         if (first) {
56434             return first.surface;
56435         }
56436         return null;
56437     },
56438     
56439     /**
56440      * Destroys the SpriteGroup
56441      */
56442     destroy: function(){
56443         var me = this,
56444             surface = me.getSurface(),
56445             item;
56446             
56447         if (surface) {
56448             while (me.getCount() > 0) {
56449                 item = me.first();
56450                 me.remove(item);
56451                 surface.remove(item);
56452             }
56453         }
56454         me.clearListeners();
56455     }
56456 });
56457
56458 /**
56459  * @class Ext.layout.component.Draw
56460  * @extends Ext.layout.component.Component
56461  * @private
56462  *
56463  */
56464
56465 Ext.define('Ext.layout.component.Draw', {
56466
56467     /* Begin Definitions */
56468
56469     alias: 'layout.draw',
56470
56471     extend: 'Ext.layout.component.Auto',
56472
56473     /* End Definitions */
56474
56475     type: 'draw',
56476
56477     onLayout : function(width, height) {
56478         this.owner.surface.setSize(width, height);
56479         this.callParent(arguments);
56480     }
56481 });
56482 /**
56483  * @class Ext.chart.theme.Theme
56484  * @ignore
56485  */
56486 Ext.define('Ext.chart.theme.Theme', {
56487
56488     /* Begin Definitions */
56489
56490     requires: ['Ext.draw.Color'],
56491
56492     /* End Definitions */
56493
56494     theme: 'Base',
56495     themeAttrs: false,
56496     
56497     initTheme: function(theme) {
56498         var me = this,
56499             themes = Ext.chart.theme,
56500             key, gradients;
56501         if (theme) {
56502             theme = theme.split(':');
56503             for (key in themes) {
56504                 if (key == theme[0]) {
56505                     gradients = theme[1] == 'gradients';
56506                     me.themeAttrs = new themes[key]({
56507                         useGradients: gradients
56508                     });
56509                     if (gradients) {
56510                         me.gradients = me.themeAttrs.gradients;
56511                     }
56512                     if (me.themeAttrs.background) {
56513                         me.background = me.themeAttrs.background;
56514                     }
56515                     return;
56516                 }
56517             }
56518             Ext.Error.raise('No theme found named "' + theme + '"');
56519         }
56520     }
56521 }, 
56522 // This callback is executed right after when the class is created. This scope refers to the newly created class itself
56523 function() {
56524    /* Theme constructor: takes either a complex object with styles like:
56525   
56526    {
56527         axis: {
56528             fill: '#000',
56529             'stroke-width': 1
56530         },
56531         axisLabelTop: {
56532             fill: '#000',
56533             font: '11px Arial'
56534         },
56535         axisLabelLeft: {
56536             fill: '#000',
56537             font: '11px Arial'
56538         },
56539         axisLabelRight: {
56540             fill: '#000',
56541             font: '11px Arial'
56542         },
56543         axisLabelBottom: {
56544             fill: '#000',
56545             font: '11px Arial'
56546         },
56547         axisTitleTop: {
56548             fill: '#000',
56549             font: '11px Arial'
56550         },
56551         axisTitleLeft: {
56552             fill: '#000',
56553             font: '11px Arial'
56554         },
56555         axisTitleRight: {
56556             fill: '#000',
56557             font: '11px Arial'
56558         },
56559         axisTitleBottom: {
56560             fill: '#000',
56561             font: '11px Arial'
56562         },
56563         series: {
56564             'stroke-width': 1
56565         },
56566         seriesLabel: {
56567             font: '12px Arial',
56568             fill: '#333'
56569         },
56570         marker: {
56571             stroke: '#555',
56572             fill: '#000',
56573             radius: 3,
56574             size: 3
56575         },
56576         seriesThemes: [{
56577             fill: '#C6DBEF'
56578         }, {
56579             fill: '#9ECAE1'
56580         }, {
56581             fill: '#6BAED6'
56582         }, {
56583             fill: '#4292C6'
56584         }, {
56585             fill: '#2171B5'
56586         }, {
56587             fill: '#084594'
56588         }],
56589         markerThemes: [{
56590             fill: '#084594',
56591             type: 'circle' 
56592         }, {
56593             fill: '#2171B5',
56594             type: 'cross'
56595         }, {
56596             fill: '#4292C6',
56597             type: 'plus'
56598         }]
56599     }
56600   
56601   ...or also takes just an array of colors and creates the complex object:
56602   
56603   {
56604       colors: ['#aaa', '#bcd', '#eee']
56605   }
56606   
56607   ...or takes just a base color and makes a theme from it
56608   
56609   {
56610       baseColor: '#bce'
56611   }
56612   
56613   To create a new theme you may add it to the Themes object:
56614   
56615   Ext.chart.theme.MyNewTheme = Ext.extend(Object, {
56616       constructor: function(config) {
56617           Ext.chart.theme.call(this, config, {
56618               baseColor: '#mybasecolor'
56619           });
56620       }
56621   });
56622   
56623   //Proposal:
56624   Ext.chart.theme.MyNewTheme = Ext.chart.createTheme('#basecolor');
56625   
56626   ...and then to use it provide the name of the theme (as a lower case string) in the chart config.
56627   
56628   {
56629       theme: 'mynewtheme'
56630   }
56631  */
56632
56633 (function() {
56634     Ext.chart.theme = function(config, base) {
56635         config = config || {};
56636         var i = 0, l, colors, color,
56637             seriesThemes, markerThemes,
56638             seriesTheme, markerTheme, 
56639             key, gradients = [],
56640             midColor, midL;
56641         
56642         if (config.baseColor) {
56643             midColor = Ext.draw.Color.fromString(config.baseColor);
56644             midL = midColor.getHSL()[2];
56645             if (midL < 0.15) {
56646                 midColor = midColor.getLighter(0.3);
56647             } else if (midL < 0.3) {
56648                 midColor = midColor.getLighter(0.15);
56649             } else if (midL > 0.85) {
56650                 midColor = midColor.getDarker(0.3);
56651             } else if (midL > 0.7) {
56652                 midColor = midColor.getDarker(0.15);
56653             }
56654             config.colors = [ midColor.getDarker(0.3).toString(),
56655                               midColor.getDarker(0.15).toString(),
56656                               midColor.toString(),
56657                               midColor.getLighter(0.15).toString(),
56658                               midColor.getLighter(0.3).toString()];
56659
56660             delete config.baseColor;
56661         }
56662         if (config.colors) {
56663             colors = config.colors.slice();
56664             markerThemes = base.markerThemes;
56665             seriesThemes = base.seriesThemes;
56666             l = colors.length;
56667             base.colors = colors;
56668             for (; i < l; i++) {
56669                 color = colors[i];
56670                 markerTheme = markerThemes[i] || {};
56671                 seriesTheme = seriesThemes[i] || {};
56672                 markerTheme.fill = seriesTheme.fill = markerTheme.stroke = seriesTheme.stroke = color;
56673                 markerThemes[i] = markerTheme;
56674                 seriesThemes[i] = seriesTheme;
56675             }
56676             base.markerThemes = markerThemes.slice(0, l);
56677             base.seriesThemes = seriesThemes.slice(0, l);
56678         //the user is configuring something in particular (either markers, series or pie slices)
56679         }
56680         for (key in base) {
56681             if (key in config) {
56682                 if (Ext.isObject(config[key]) && Ext.isObject(base[key])) {
56683                     Ext.apply(base[key], config[key]);
56684                 } else {
56685                     base[key] = config[key];
56686                 }
56687             }
56688         }
56689         if (config.useGradients) {
56690             colors = base.colors || (function () {
56691                 var ans = [];
56692                 for (i = 0, seriesThemes = base.seriesThemes, l = seriesThemes.length; i < l; i++) {
56693                     ans.push(seriesThemes[i].fill || seriesThemes[i].stroke);
56694                 }
56695                 return ans;
56696             })();
56697             for (i = 0, l = colors.length; i < l; i++) {
56698                 midColor = Ext.draw.Color.fromString(colors[i]);
56699                 if (midColor) {
56700                     color = midColor.getDarker(0.1).toString();
56701                     midColor = midColor.toString();
56702                     key = 'theme-' + midColor.substr(1) + '-' + color.substr(1);
56703                     gradients.push({
56704                         id: key,
56705                         angle: 45,
56706                         stops: {
56707                             0: {
56708                                 color: midColor.toString()
56709                             },
56710                             100: {
56711                                 color: color.toString()
56712                             }
56713                         }
56714                     });
56715                     colors[i] = 'url(#' + key + ')'; 
56716                 }
56717             }
56718             base.gradients = gradients;
56719             base.colors = colors;
56720         }
56721         /*
56722         base.axis = Ext.apply(base.axis || {}, config.axis || {});
56723         base.axisLabel = Ext.apply(base.axisLabel || {}, config.axisLabel || {});
56724         base.axisTitle = Ext.apply(base.axisTitle || {}, config.axisTitle || {});
56725         */
56726         Ext.apply(this, base);
56727     };
56728 })();
56729 });
56730
56731 /**
56732  * @class Ext.chart.Mask
56733  *
56734  * Defines a mask for a chart's series.
56735  * The 'chart' member must be set prior to rendering.
56736  *
56737  * A Mask can be used to select a certain region in a chart.
56738  * When enabled, the `select` event will be triggered when a
56739  * region is selected by the mask, allowing the user to perform
56740  * other tasks like zooming on that region, etc.
56741  *
56742  * In order to use the mask one has to set the Chart `mask` option to
56743  * `true`, `vertical` or `horizontal`. Then a possible configuration for the
56744  * listener could be:
56745  *
56746         items: {
56747             xtype: 'chart',
56748             animate: true,
56749             store: store1,
56750             mask: 'horizontal',
56751             listeners: {
56752                 select: {
56753                     fn: function(me, selection) {
56754                         me.setZoom(selection);
56755                         me.mask.hide();
56756                     }
56757                 }
56758             },
56759
56760  * In this example we zoom the chart to that particular region. You can also get
56761  * a handle to a mask instance from the chart object. The `chart.mask` element is a
56762  * `Ext.Panel`.
56763  * 
56764  * @constructor
56765  */
56766 Ext.define('Ext.chart.Mask', {
56767     constructor: function(config) {
56768         var me = this;
56769
56770         me.addEvents('select');
56771
56772         if (config) {
56773             Ext.apply(me, config);
56774         }
56775         if (me.mask) {
56776             me.on('afterrender', function() {
56777                 //create a mask layer component
56778                 var comp = Ext.create('Ext.chart.MaskLayer', {
56779                     renderTo: me.el
56780                 });
56781                 comp.el.on({
56782                     'mousemove': function(e) {
56783                         me.onMouseMove(e);
56784                     },
56785                     'mouseup': function(e) {
56786                         me.resized(e);
56787                     }
56788                 });
56789                 //create a resize handler for the component
56790                 var resizeHandler = Ext.create('Ext.resizer.Resizer', {
56791                     el: comp.el,
56792                     handles: 'all',
56793                     pinned: true
56794                 });
56795                 resizeHandler.on({
56796                     'resize': function(e) {
56797                         me.resized(e);    
56798                     }    
56799                 });
56800                 comp.initDraggable();
56801                 me.maskType = me.mask;
56802                 me.mask = comp;
56803                 me.maskSprite = me.surface.add({
56804                     type: 'path',
56805                     path: ['M', 0, 0],
56806                     zIndex: 1001,
56807                     opacity: 0.7,
56808                     hidden: true,
56809                     stroke: '#444'
56810                 });
56811             }, me, { single: true });
56812         }
56813     },
56814     
56815     resized: function(e) {
56816         var me = this,
56817             bbox = me.bbox || me.chartBBox,
56818             x = bbox.x,
56819             y = bbox.y,
56820             width = bbox.width,
56821             height = bbox.height,
56822             box = me.mask.getBox(true),
56823             max = Math.max,
56824             min = Math.min,
56825             staticX = box.x - x,
56826             staticY = box.y - y;
56827         
56828         staticX = max(staticX, x);
56829         staticY = max(staticY, y);
56830         staticX = min(staticX, width);
56831         staticY = min(staticY, height);
56832         box.x = staticX;
56833         box.y = staticY;
56834         me.fireEvent('select', me, box);
56835     },
56836
56837     onMouseUp: function(e) {
56838         var me = this,
56839             bbox = me.bbox || me.chartBBox,
56840             sel = me.maskSelection;
56841         me.maskMouseDown = false;
56842         me.mouseDown = false;
56843         if (me.mouseMoved) {
56844             me.onMouseMove(e);
56845             me.mouseMoved = false;
56846             me.fireEvent('select', me, {
56847                 x: sel.x - bbox.x,
56848                 y: sel.y - bbox.y,
56849                 width: sel.width,
56850                 height: sel.height
56851             });
56852         }
56853     },
56854
56855     onMouseDown: function(e) {
56856         var me = this;
56857         me.mouseDown = true;
56858         me.mouseMoved = false;
56859         me.maskMouseDown = {
56860             x: e.getPageX() - me.el.getX(),
56861             y: e.getPageY() - me.el.getY()
56862         };
56863     },
56864
56865     onMouseMove: function(e) {
56866         var me = this,
56867             mask = me.maskType,
56868             bbox = me.bbox || me.chartBBox,
56869             x = bbox.x,
56870             y = bbox.y,
56871             math = Math,
56872             floor = math.floor,
56873             abs = math.abs,
56874             min = math.min,
56875             max = math.max,
56876             height = floor(y + bbox.height),
56877             width = floor(x + bbox.width),
56878             posX = e.getPageX(),
56879             posY = e.getPageY(),
56880             staticX = posX - me.el.getX(),
56881             staticY = posY - me.el.getY(),
56882             maskMouseDown = me.maskMouseDown,
56883             path;
56884         
56885         me.mouseMoved = me.mouseDown;
56886         staticX = max(staticX, x);
56887         staticY = max(staticY, y);
56888         staticX = min(staticX, width);
56889         staticY = min(staticY, height);
56890         if (maskMouseDown && me.mouseDown) {
56891             if (mask == 'horizontal') {
56892                 staticY = y;
56893                 maskMouseDown.y = height;
56894                 posY = me.el.getY() + bbox.height + me.insetPadding;
56895             }
56896             else if (mask == 'vertical') {
56897                 staticX = x;
56898                 maskMouseDown.x = width;
56899             }
56900             width = maskMouseDown.x - staticX;
56901             height = maskMouseDown.y - staticY;
56902             path = ['M', staticX, staticY, 'l', width, 0, 0, height, -width, 0, 'z'];
56903             me.maskSelection = {
56904                 x: width > 0 ? staticX : staticX + width,
56905                 y: height > 0 ? staticY : staticY + height,
56906                 width: abs(width),
56907                 height: abs(height)
56908             };
56909             me.mask.updateBox({
56910                 x: posX - abs(width),
56911                 y: posY - abs(height),
56912                 width: abs(width),
56913                 height: abs(height)
56914             });
56915             me.mask.show();
56916             me.maskSprite.setAttributes({
56917                 hidden: true    
56918             }, true);
56919         }
56920         else {
56921             if (mask == 'horizontal') {
56922                 path = ['M', staticX, y, 'L', staticX, height];
56923             }
56924             else if (mask == 'vertical') {
56925                 path = ['M', x, staticY, 'L', width, staticY];
56926             }
56927             else {
56928                 path = ['M', staticX, y, 'L', staticX, height, 'M', x, staticY, 'L', width, staticY];
56929             }
56930             me.maskSprite.setAttributes({
56931                 path: path,
56932                 fill: me.maskMouseDown ? me.maskSprite.stroke : false,
56933                 'stroke-width': mask === true ? 1 : 3,
56934                 hidden: false
56935             }, true);
56936         }
56937     },
56938
56939     onMouseLeave: function(e) {
56940         var me = this;
56941         me.mouseMoved = false;
56942         me.mouseDown = false;
56943         me.maskMouseDown = false;
56944         me.mask.hide();
56945         me.maskSprite.hide(true);
56946     }
56947 });
56948     
56949 /**
56950  * @class Ext.chart.Navigation
56951  *
56952  * Handles panning and zooming capabilities.
56953  * 
56954  * @ignore
56955  */
56956 Ext.define('Ext.chart.Navigation', {
56957
56958     constructor: function() {
56959         this.originalStore = this.store;
56960     },
56961     
56962     //filters the store to the specified interval(s)
56963     setZoom: function(zoomConfig) {
56964         var me = this,
56965             store = me.substore || me.store,
56966             bbox = me.chartBBox,
56967             len = store.getCount(),
56968             from = (zoomConfig.x / bbox.width * len) >> 0,
56969             to = Math.ceil(((zoomConfig.x + zoomConfig.width) / bbox.width * len)),
56970             recFieldsLen, recFields = [], curField, json = [], obj;
56971         
56972         store.each(function(rec, i) {
56973             if (i < from || i > to) {
56974                 return;
56975             }
56976             obj = {};
56977             //get all record field names in a simple array
56978             if (!recFields.length) {
56979                 rec.fields.each(function(f) {
56980                     recFields.push(f.name);
56981                 });
56982                 recFieldsLen = recFields.length;
56983             }
56984             //append record values to an aggregation record
56985             for (i = 0; i < recFieldsLen; i++) {
56986                 curField = recFields[i];
56987                 obj[curField] = rec.get(curField);
56988             }
56989             json.push(obj);
56990         });
56991         me.store = me.substore = Ext.create('Ext.data.JsonStore', {
56992             fields: recFields,
56993             data: json
56994         });
56995         me.redraw(true);
56996     },
56997
56998     restoreZoom: function() {
56999         this.store = this.substore = this.originalStore;
57000         this.redraw(true);
57001     }
57002     
57003 });
57004 /**
57005  * @class Ext.chart.Shape
57006  * @ignore
57007  */
57008 Ext.define('Ext.chart.Shape', {
57009
57010     /* Begin Definitions */
57011
57012     singleton: true,
57013
57014     /* End Definitions */
57015
57016     circle: function (surface, opts) {
57017         return surface.add(Ext.apply({
57018             type: 'circle',
57019             x: opts.x,
57020             y: opts.y,
57021             stroke: null,
57022             radius: opts.radius
57023         }, opts));
57024     },
57025     line: function (surface, opts) {
57026         return surface.add(Ext.apply({
57027             type: 'rect',
57028             x: opts.x - opts.radius,
57029             y: opts.y - opts.radius,
57030             height: 2 * opts.radius,
57031             width: 2 * opts.radius / 5
57032         }, opts));
57033     },
57034     square: function (surface, opts) {
57035         return surface.add(Ext.applyIf({
57036             type: 'rect',
57037             x: opts.x - opts.radius,
57038             y: opts.y - opts.radius,
57039             height: 2 * opts.radius,
57040             width: 2 * opts.radius,
57041             radius: null
57042         }, opts));
57043     },
57044     triangle: function (surface, opts) {
57045         opts.radius *= 1.75;
57046         return surface.add(Ext.apply({
57047             type: 'path',
57048             stroke: null,
57049             path: "M".concat(opts.x, ",", opts.y, "m0-", opts.radius * 0.58, "l", opts.radius * 0.5, ",", opts.radius * 0.87, "-", opts.radius, ",0z")
57050         }, opts));
57051     },
57052     diamond: function (surface, opts) {
57053         var r = opts.radius;
57054         r *= 1.5;
57055         return surface.add(Ext.apply({
57056             type: 'path',
57057             stroke: null,
57058             path: ["M", opts.x, opts.y - r, "l", r, r, -r, r, -r, -r, r, -r, "z"]
57059         }, opts));
57060     },
57061     cross: function (surface, opts) {
57062         var r = opts.radius;
57063         r = r / 1.7;
57064         return surface.add(Ext.apply({
57065             type: 'path',
57066             stroke: null,
57067             path: "M".concat(opts.x - r, ",", opts.y, "l", [-r, -r, r, -r, r, r, r, -r, r, r, -r, r, r, r, -r, r, -r, -r, -r, r, -r, -r, "z"])
57068         }, opts));
57069     },
57070     plus: function (surface, opts) {
57071         var r = opts.radius / 1.3;
57072         return surface.add(Ext.apply({
57073             type: 'path',
57074             stroke: null,
57075             path: "M".concat(opts.x - r / 2, ",", opts.y - r / 2, "l", [0, -r, r, 0, 0, r, r, 0, 0, r, -r, 0, 0, r, -r, 0, 0, -r, -r, 0, 0, -r, "z"])
57076         }, opts));
57077     },
57078     arrow: function (surface, opts) {
57079         var r = opts.radius;
57080         return surface.add(Ext.apply({
57081             type: 'path',
57082             path: "M".concat(opts.x - r * 0.7, ",", opts.y - r * 0.4, "l", [r * 0.6, 0, 0, -r * 0.4, r, r * 0.8, -r, r * 0.8, 0, -r * 0.4, -r * 0.6, 0], "z")
57083         }, opts));
57084     },
57085     drop: function (surface, x, y, text, size, angle) {
57086         size = size || 30;
57087         angle = angle || 0;
57088         surface.add({
57089             type: 'path',
57090             path: ['M', x, y, 'l', size, 0, 'A', size * 0.4, size * 0.4, 0, 1, 0, x + size * 0.7, y - size * 0.7, 'z'],
57091             fill: '#000',
57092             stroke: 'none',
57093             rotate: {
57094                 degrees: 22.5 - angle,
57095                 x: x,
57096                 y: y
57097             }
57098         });
57099         angle = (angle + 90) * Math.PI / 180;
57100         surface.add({
57101             type: 'text',
57102             x: x + size * Math.sin(angle) - 10, // Shift here, Not sure why.
57103             y: y + size * Math.cos(angle) + 5,
57104             text:  text,
57105             'font-size': size * 12 / 40,
57106             stroke: 'none',
57107             fill: '#fff'
57108         });
57109     }
57110 });
57111 /**
57112  * @class Ext.draw.Surface
57113  * @extends Object
57114  *
57115  * A Surface is an interface to render methods inside a draw {@link Ext.draw.Component}.
57116  * A Surface contains methods to render sprites, get bounding boxes of sprites, add
57117  * sprites to the canvas, initialize other graphic components, etc. One of the most used
57118  * methods for this class is the `add` method, to add Sprites to the surface.
57119  *
57120  * Most of the Surface methods are abstract and they have a concrete implementation
57121  * in VML or SVG engines.
57122  *
57123  * A Surface instance can be accessed as a property of a draw component. For example:
57124  *
57125  *     drawComponent.surface.add({
57126  *         type: 'circle',
57127  *         fill: '#ffc',
57128  *         radius: 100,
57129  *         x: 100,
57130  *         y: 100
57131  *     });
57132  *
57133  * The configuration object passed in the `add` method is the same as described in the {@link Ext.draw.Sprite}
57134  * class documentation.
57135  *
57136  * ### Listeners
57137  *
57138  * You can also add event listeners to the surface using the `Observable` listener syntax. Supported events are:
57139  *
57140  * - mousedown
57141  * - mouseup
57142  * - mouseover
57143  * - mouseout
57144  * - mousemove
57145  * - mouseenter
57146  * - mouseleave
57147  * - click
57148  *
57149  * For example:
57150  *
57151         drawComponent.surface.on({
57152            'mousemove': function() {
57153                 console.log('moving the mouse over the surface');   
57154             }
57155         });
57156  */
57157 Ext.define('Ext.draw.Surface', {
57158
57159     /* Begin Definitions */
57160
57161     mixins: {
57162         observable: 'Ext.util.Observable'
57163     },
57164
57165     requires: ['Ext.draw.CompositeSprite'],
57166     uses: ['Ext.draw.engine.Svg', 'Ext.draw.engine.Vml'],
57167
57168     separatorRe: /[, ]+/,
57169
57170     statics: {
57171         /**
57172          * Create and return a new concrete Surface instance appropriate for the current environment.
57173          * @param {Object} config Initial configuration for the Surface instance
57174          * @param {Array} enginePriority Optional order of implementations to use; the first one that is
57175          *                available in the current environment will be used. Defaults to
57176          *                <code>['Svg', 'Vml']</code>.
57177          */
57178         create: function(config, enginePriority) {
57179             enginePriority = enginePriority || ['Svg', 'Vml'];
57180
57181             var i = 0,
57182                 len = enginePriority.length,
57183                 surfaceClass;
57184
57185             for (; i < len; i++) {
57186                 if (Ext.supports[enginePriority[i]]) {
57187                     return Ext.create('Ext.draw.engine.' + enginePriority[i], config);
57188                 }
57189             }
57190             return false;
57191         }
57192     },
57193
57194     /* End Definitions */
57195
57196     // @private
57197     availableAttrs: {
57198         blur: 0,
57199         "clip-rect": "0 0 1e9 1e9",
57200         cursor: "default",
57201         cx: 0,
57202         cy: 0,
57203         'dominant-baseline': 'auto',
57204         fill: "none",
57205         "fill-opacity": 1,
57206         font: '10px "Arial"',
57207         "font-family": '"Arial"',
57208         "font-size": "10",
57209         "font-style": "normal",
57210         "font-weight": 400,
57211         gradient: "",
57212         height: 0,
57213         hidden: false,
57214         href: "http://sencha.com/",
57215         opacity: 1,
57216         path: "M0,0",
57217         radius: 0,
57218         rx: 0,
57219         ry: 0,
57220         scale: "1 1",
57221         src: "",
57222         stroke: "#000",
57223         "stroke-dasharray": "",
57224         "stroke-linecap": "butt",
57225         "stroke-linejoin": "butt",
57226         "stroke-miterlimit": 0,
57227         "stroke-opacity": 1,
57228         "stroke-width": 1,
57229         target: "_blank",
57230         text: "",
57231         "text-anchor": "middle",
57232         title: "Ext Draw",
57233         width: 0,
57234         x: 0,
57235         y: 0,
57236         zIndex: 0
57237     },
57238
57239  /**
57240   * @cfg {Number} height
57241   * The height of this component in pixels (defaults to auto).
57242   * <b>Note</b> to express this dimension as a percentage or offset see {@link Ext.Component#anchor}.
57243   */
57244  /**
57245   * @cfg {Number} width
57246   * The width of this component in pixels (defaults to auto).
57247   * <b>Note</b> to express this dimension as a percentage or offset see {@link Ext.Component#anchor}.
57248   */
57249     container: undefined,
57250     height: 352,
57251     width: 512,
57252     x: 0,
57253     y: 0,
57254
57255     constructor: function(config) {
57256         var me = this;
57257         config = config || {};
57258         Ext.apply(me, config);
57259
57260         me.domRef = Ext.getDoc().dom;
57261         
57262         me.customAttributes = {};
57263
57264         me.addEvents(
57265             'mousedown',
57266             'mouseup',
57267             'mouseover',
57268             'mouseout',
57269             'mousemove',
57270             'mouseenter',
57271             'mouseleave',
57272             'click'
57273         );
57274
57275         me.mixins.observable.constructor.call(me);
57276
57277         me.getId();
57278         me.initGradients();
57279         me.initItems();
57280         if (me.renderTo) {
57281             me.render(me.renderTo);
57282             delete me.renderTo;
57283         }
57284         me.initBackground(config.background);
57285     },
57286
57287     // @private called to initialize components in the surface
57288     // this is dependent on the underlying implementation.
57289     initSurface: Ext.emptyFn,
57290
57291     // @private called to setup the surface to render an item
57292     //this is dependent on the underlying implementation.
57293     renderItem: Ext.emptyFn,
57294
57295     // @private
57296     renderItems: Ext.emptyFn,
57297
57298     // @private
57299     setViewBox: Ext.emptyFn,
57300
57301     /**
57302      * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
57303      *
57304      * For example:
57305      *
57306      *          drawComponent.surface.addCls(sprite, 'x-visible');
57307      *      
57308      * @param {Object} sprite The sprite to add the class to.
57309      * @param {String/Array} className The CSS class to add, or an array of classes
57310      */
57311     addCls: Ext.emptyFn,
57312
57313     /**
57314      * Removes one or more CSS classes from the element.
57315      *
57316      * For example:
57317      *
57318      *      drawComponent.surface.removeCls(sprite, 'x-visible');
57319      *      
57320      * @param {Object} sprite The sprite to remove the class from.
57321      * @param {String/Array} className The CSS class to remove, or an array of classes
57322      */
57323     removeCls: Ext.emptyFn,
57324
57325     /**
57326      * Sets CSS style attributes to an element.
57327      *
57328      * For example:
57329      *
57330      *      drawComponent.surface.setStyle(sprite, {
57331      *          'cursor': 'pointer'
57332      *      });
57333      *      
57334      * @param {Object} sprite The sprite to add, or an array of classes to
57335      * @param {Object} styles An Object with CSS styles.
57336      */
57337     setStyle: Ext.emptyFn,
57338
57339     // @private
57340     initGradients: function() {
57341         var gradients = this.gradients;
57342         if (gradients) {
57343             Ext.each(gradients, this.addGradient, this);
57344         }
57345     },
57346
57347     // @private
57348     initItems: function() {
57349         var items = this.items;
57350         this.items = Ext.create('Ext.draw.CompositeSprite');
57351         this.groups = Ext.create('Ext.draw.CompositeSprite');
57352         if (items) {
57353             this.add(items);
57354         }
57355     },
57356     
57357     // @private
57358     initBackground: function(config) {
57359         var gradientId, 
57360             gradient,
57361             backgroundSprite,
57362             width = this.width,
57363             height = this.height;
57364         if (config) {
57365             if (config.gradient) {
57366                 gradient = config.gradient;
57367                 gradientId = gradient.id;
57368                 this.addGradient(gradient);
57369                 this.background = this.add({
57370                     type: 'rect',
57371                     x: 0,
57372                     y: 0,
57373                     width: width,
57374                     height: height,
57375                     fill: 'url(#' + gradientId + ')'
57376                 });
57377             } else if (config.fill) {
57378                 this.background = this.add({
57379                     type: 'rect',
57380                     x: 0,
57381                     y: 0,
57382                     width: width,
57383                     height: height,
57384                     fill: config.fill
57385                 });
57386             } else if (config.image) {
57387                 this.background = this.add({
57388                     type: 'image',
57389                     x: 0,
57390                     y: 0,
57391                     width: width,
57392                     height: height,
57393                     src: config.image
57394                 });
57395             }
57396         }
57397     },
57398     
57399     /**
57400      * Sets the size of the surface. Accomodates the background (if any) to fit the new size too.
57401      *
57402      * For example:
57403      *
57404      *      drawComponent.surface.setSize(500, 500);
57405      *
57406      * This method is generally called when also setting the size of the draw Component.
57407      * 
57408      * @param {Number} w The new width of the canvas.
57409      * @param {Number} h The new height of the canvas.
57410      */
57411     setSize: function(w, h) {
57412         if (this.background) {
57413             this.background.setAttributes({
57414                 width: w,
57415                 height: h,
57416                 hidden: false
57417             }, true);
57418         }
57419     },
57420
57421     // @private
57422     scrubAttrs: function(sprite) {
57423         var i,
57424             attrs = {},
57425             exclude = {},
57426             sattr = sprite.attr;
57427         for (i in sattr) {    
57428             // Narrow down attributes to the main set
57429             if (this.translateAttrs.hasOwnProperty(i)) {
57430                 // Translated attr
57431                 attrs[this.translateAttrs[i]] = sattr[i];
57432                 exclude[this.translateAttrs[i]] = true;
57433             }
57434             else if (this.availableAttrs.hasOwnProperty(i) && !exclude[i]) {
57435                 // Passtrhough attr
57436                 attrs[i] = sattr[i];
57437             }
57438         }
57439         return attrs;
57440     },
57441
57442     // @private
57443     onClick: function(e) {
57444         this.processEvent('click', e);
57445     },
57446
57447     // @private
57448     onMouseUp: function(e) {
57449         this.processEvent('mouseup', e);
57450     },
57451
57452     // @private
57453     onMouseDown: function(e) {
57454         this.processEvent('mousedown', e);
57455     },
57456
57457     // @private
57458     onMouseOver: function(e) {
57459         this.processEvent('mouseover', e);
57460     },
57461
57462     // @private
57463     onMouseOut: function(e) {
57464         this.processEvent('mouseout', e);
57465     },
57466
57467     // @private
57468     onMouseMove: function(e) {
57469         this.fireEvent('mousemove', e);
57470     },
57471
57472     // @private
57473     onMouseEnter: Ext.emptyFn,
57474
57475     // @private
57476     onMouseLeave: Ext.emptyFn,
57477
57478     /**
57479      * Add a gradient definition to the Surface. Note that in some surface engines, adding
57480      * a gradient via this method will not take effect if the surface has already been rendered.
57481      * Therefore, it is preferred to pass the gradients as an item to the surface config, rather
57482      * than calling this method, especially if the surface is rendered immediately (e.g. due to
57483      * 'renderTo' in its config). For more information on how to create gradients in the Chart
57484      * configuration object please refer to {@link Ext.chart.Chart}.
57485      *
57486      * The gradient object to be passed into this method is composed by:
57487      * 
57488      * 
57489      *  - **id** - string - The unique name of the gradient.
57490      *  - **angle** - number, optional - The angle of the gradient in degrees.
57491      *  - **stops** - object - An object with numbers as keys (from 0 to 100) and style objects as values.
57492      * 
57493      *
57494      For example:
57495                 drawComponent.surface.addGradient({
57496                     id: 'gradientId',
57497                     angle: 45,
57498                     stops: {
57499                         0: {
57500                             color: '#555'
57501                         },
57502                         100: {
57503                             color: '#ddd'
57504                         }
57505                     }
57506                 });
57507      */
57508     addGradient: Ext.emptyFn,
57509
57510     /**
57511      * Add a Sprite to the surface. See {@link Ext.draw.Sprite} for the configuration object to be passed into this method.
57512      *
57513      * For example:
57514      *
57515      *     drawComponent.surface.add({
57516      *         type: 'circle',
57517      *         fill: '#ffc',
57518      *         radius: 100,
57519      *         x: 100,
57520      *         y: 100
57521      *     });
57522      *
57523     */
57524     add: function() {
57525         var args = Array.prototype.slice.call(arguments),
57526             sprite,
57527             index;
57528
57529         var hasMultipleArgs = args.length > 1;
57530         if (hasMultipleArgs || Ext.isArray(args[0])) {
57531             var items = hasMultipleArgs ? args : args[0],
57532                 results = [],
57533                 i, ln, item;
57534
57535             for (i = 0, ln = items.length; i < ln; i++) {
57536                 item = items[i];
57537                 item = this.add(item);
57538                 results.push(item);
57539             }
57540
57541             return results;
57542         }
57543         sprite = this.prepareItems(args[0], true)[0];
57544         this.normalizeSpriteCollection(sprite);
57545         this.onAdd(sprite);
57546         return sprite;
57547     },
57548
57549     /**
57550      * @private
57551      * Insert or move a given sprite into the correct position in the items
57552      * MixedCollection, according to its zIndex. Will be inserted at the end of
57553      * an existing series of sprites with the same or lower zIndex. If the sprite
57554      * is already positioned within an appropriate zIndex group, it will not be moved.
57555      * This ordering can be used by subclasses to assist in rendering the sprites in
57556      * the correct order for proper z-index stacking.
57557      * @param {Ext.draw.Sprite} sprite
57558      * @return {Number} the sprite's new index in the list
57559      */
57560     normalizeSpriteCollection: function(sprite) {
57561         var items = this.items,
57562             zIndex = sprite.attr.zIndex,
57563             idx = items.indexOf(sprite);
57564
57565         if (idx < 0 || (idx > 0 && items.getAt(idx - 1).attr.zIndex > zIndex) ||
57566                 (idx < items.length - 1 && items.getAt(idx + 1).attr.zIndex < zIndex)) {
57567             items.removeAt(idx);
57568             idx = items.findIndexBy(function(otherSprite) {
57569                 return otherSprite.attr.zIndex > zIndex;
57570             });
57571             if (idx < 0) {
57572                 idx = items.length;
57573             }
57574             items.insert(idx, sprite);
57575         }
57576         return idx;
57577     },
57578
57579     onAdd: function(sprite) {
57580         var group = sprite.group,
57581             draggable = sprite.draggable,
57582             groups, ln, i;
57583         if (group) {
57584             groups = [].concat(group);
57585             ln = groups.length;
57586             for (i = 0; i < ln; i++) {
57587                 group = groups[i];
57588                 this.getGroup(group).add(sprite);
57589             }
57590             delete sprite.group;
57591         }
57592         if (draggable) {
57593             sprite.initDraggable();
57594         }
57595     },
57596
57597     /**
57598      * Remove a given sprite from the surface, optionally destroying the sprite in the process.
57599      * You can also call the sprite own `remove` method.
57600      *
57601      * For example:
57602      *
57603      *      drawComponent.surface.remove(sprite);
57604      *      //or...
57605      *      sprite.remove();
57606      *      
57607      * @param {Ext.draw.Sprite} sprite
57608      * @param {Boolean} destroySprite
57609      * @return {Number} the sprite's new index in the list
57610      */
57611     remove: function(sprite, destroySprite) {
57612         if (sprite) {
57613             this.items.remove(sprite);
57614             this.groups.each(function(item) {
57615                 item.remove(sprite);
57616             });
57617             sprite.onRemove();
57618             if (destroySprite === true) {
57619                 sprite.destroy();
57620             }
57621         }
57622     },
57623
57624     /**
57625      * Remove all sprites from the surface, optionally destroying the sprites in the process.
57626      *
57627      * For example:
57628      *
57629      *      drawComponent.surface.removeAll();
57630      *      
57631      * @param {Boolean} destroySprites Whether to destroy all sprites when removing them.
57632      * @return {Number} The sprite's new index in the list.
57633      */
57634     removeAll: function(destroySprites) {
57635         var items = this.items.items,
57636             ln = items.length,
57637             i;
57638         for (i = ln - 1; i > -1; i--) {
57639             this.remove(items[i], destroySprites);
57640         }
57641     },
57642
57643     onRemove: Ext.emptyFn,
57644
57645     onDestroy: Ext.emptyFn,
57646
57647     // @private
57648     applyTransformations: function(sprite) {
57649             sprite.bbox.transform = 0;
57650             this.transform(sprite);
57651
57652         var me = this,
57653             dirty = false,
57654             attr = sprite.attr;
57655
57656         if (attr.translation.x != null || attr.translation.y != null) {
57657             me.translate(sprite);
57658             dirty = true;
57659         }
57660         if (attr.scaling.x != null || attr.scaling.y != null) {
57661             me.scale(sprite);
57662             dirty = true;
57663         }
57664         if (attr.rotation.degrees != null) {
57665             me.rotate(sprite);
57666             dirty = true;
57667         }
57668         if (dirty) {
57669             sprite.bbox.transform = 0;
57670             this.transform(sprite);
57671             sprite.transformations = [];
57672         }
57673     },
57674
57675     // @private
57676     rotate: function (sprite) {
57677         var bbox,
57678             deg = sprite.attr.rotation.degrees,
57679             centerX = sprite.attr.rotation.x,
57680             centerY = sprite.attr.rotation.y;
57681         if (!Ext.isNumber(centerX) || !Ext.isNumber(centerY)) {
57682             bbox = this.getBBox(sprite);
57683             centerX = !Ext.isNumber(centerX) ? bbox.x + bbox.width / 2 : centerX;
57684             centerY = !Ext.isNumber(centerY) ? bbox.y + bbox.height / 2 : centerY;
57685         }
57686         sprite.transformations.push({
57687             type: "rotate",
57688             degrees: deg,
57689             x: centerX,
57690             y: centerY
57691         });
57692     },
57693
57694     // @private
57695     translate: function(sprite) {
57696         var x = sprite.attr.translation.x || 0,
57697             y = sprite.attr.translation.y || 0;
57698         sprite.transformations.push({
57699             type: "translate",
57700             x: x,
57701             y: y
57702         });
57703     },
57704
57705     // @private
57706     scale: function(sprite) {
57707         var bbox,
57708             x = sprite.attr.scaling.x || 1,
57709             y = sprite.attr.scaling.y || 1,
57710             centerX = sprite.attr.scaling.centerX,
57711             centerY = sprite.attr.scaling.centerY;
57712
57713         if (!Ext.isNumber(centerX) || !Ext.isNumber(centerY)) {
57714             bbox = this.getBBox(sprite);
57715             centerX = !Ext.isNumber(centerX) ? bbox.x + bbox.width / 2 : centerX;
57716             centerY = !Ext.isNumber(centerY) ? bbox.y + bbox.height / 2 : centerY;
57717         }
57718         sprite.transformations.push({
57719             type: "scale",
57720             x: x,
57721             y: y,
57722             centerX: centerX,
57723             centerY: centerY
57724         });
57725     },
57726
57727     // @private
57728     rectPath: function (x, y, w, h, r) {
57729         if (r) {
57730             return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]];
57731         }
57732         return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]];
57733     },
57734
57735     // @private
57736     ellipsePath: function (x, y, rx, ry) {
57737         if (ry == null) {
57738             ry = rx;
57739         }
57740         return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]];
57741     },
57742
57743     // @private
57744     getPathpath: function (el) {
57745         return el.attr.path;
57746     },
57747
57748     // @private
57749     getPathcircle: function (el) {
57750         var a = el.attr;
57751         return this.ellipsePath(a.x, a.y, a.radius, a.radius);
57752     },
57753
57754     // @private
57755     getPathellipse: function (el) {
57756         var a = el.attr;
57757         return this.ellipsePath(a.x, a.y, a.radiusX, a.radiusY);
57758     },
57759
57760     // @private
57761     getPathrect: function (el) {
57762         var a = el.attr;
57763         return this.rectPath(a.x, a.y, a.width, a.height, a.r);
57764     },
57765
57766     // @private
57767     getPathimage: function (el) {
57768         var a = el.attr;
57769         return this.rectPath(a.x || 0, a.y || 0, a.width, a.height);
57770     },
57771
57772     // @private
57773     getPathtext: function (el) {
57774         var bbox = this.getBBoxText(el);
57775         return this.rectPath(bbox.x, bbox.y, bbox.width, bbox.height);
57776     },
57777
57778     createGroup: function(id) {
57779         var group = this.groups.get(id);
57780         if (!group) {
57781             group = Ext.create('Ext.draw.CompositeSprite', {
57782                 surface: this
57783             });
57784             group.id = id || Ext.id(null, 'ext-surface-group-');
57785             this.groups.add(group);
57786         }
57787         return group;
57788     },
57789
57790     /**
57791      * Returns a new group or an existent group associated with the current surface.
57792      * The group returned is a {@link Ext.draw.CompositeSprite} group.
57793      *
57794      * For example:
57795      *
57796      *      var spriteGroup = drawComponent.surface.getGroup('someGroupId');
57797      *      
57798      * @param {String} id The unique identifier of the group.
57799      * @return {Object} The {@link Ext.draw.CompositeSprite}.
57800      */
57801     getGroup: function(id) {
57802         if (typeof id == "string") {
57803             var group = this.groups.get(id);
57804             if (!group) {
57805                 group = this.createGroup(id);
57806             }
57807         } else {
57808             group = id;
57809         }
57810         return group;
57811     },
57812
57813     // @private
57814     prepareItems: function(items, applyDefaults) {
57815         items = [].concat(items);
57816         // Make sure defaults are applied and item is initialized
57817         var item, i, ln;
57818         for (i = 0, ln = items.length; i < ln; i++) {
57819             item = items[i];
57820             if (!(item instanceof Ext.draw.Sprite)) {
57821                 // Temporary, just take in configs...
57822                 item.surface = this;
57823                 items[i] = this.createItem(item);
57824             } else {
57825                 item.surface = this;
57826             }
57827         }
57828         return items;
57829     },
57830     
57831     /**
57832      * Changes the text in the sprite element. The sprite must be a `text` sprite.
57833      * This method can also be called from {@link Ext.draw.Sprite}.
57834      *
57835      * For example:
57836      *
57837      *      var spriteGroup = drawComponent.surface.setText(sprite, 'my new text');
57838      *      
57839      * @param {Object} sprite The Sprite to change the text.
57840      * @param {String} text The new text to be set.
57841      */
57842     setText: Ext.emptyFn,
57843     
57844     //@private Creates an item and appends it to the surface. Called
57845     //as an internal method when calling `add`.
57846     createItem: Ext.emptyFn,
57847
57848     /**
57849      * Retrieves the id of this component.
57850      * Will autogenerate an id if one has not already been set.
57851      */
57852     getId: function() {
57853         return this.id || (this.id = Ext.id(null, 'ext-surface-'));
57854     },
57855
57856     /**
57857      * Destroys the surface. This is done by removing all components from it and
57858      * also removing its reference to a DOM element.
57859      *
57860      * For example:
57861      *
57862      *      drawComponent.surface.destroy();
57863      */
57864     destroy: function() {
57865         delete this.domRef;
57866         this.removeAll();
57867     }
57868 });
57869 /**
57870  * @class Ext.draw.Component
57871  * @extends Ext.Component
57872  *
57873  * The Draw Component is a surface in which sprites can be rendered. The Draw Component
57874  * manages and holds a `Surface` instance: an interface that has
57875  * an SVG or VML implementation depending on the browser capabilities and where
57876  * Sprites can be appended.
57877  * {@img Ext.draw.Component/Ext.draw.Component.png Ext.draw.Component component}
57878  * One way to create a draw component is:
57879  * 
57880  *     var drawComponent = Ext.create('Ext.draw.Component', {
57881  *         viewBox: false,
57882  *         items: [{
57883  *             type: 'circle',
57884  *             fill: '#79BB3F',
57885  *             radius: 100,
57886  *             x: 100,
57887  *             y: 100
57888  *         }]
57889  *     });
57890  *   
57891  *     Ext.create('Ext.Window', {
57892  *         width: 215,
57893  *         height: 235,
57894  *         layout: 'fit',
57895  *         items: [drawComponent]
57896  *     }).show();
57897  * 
57898  * In this case we created a draw component and added a sprite to it.
57899  * The *type* of the sprite is *circle* so if you run this code you'll see a yellow-ish
57900  * circle in a Window. When setting `viewBox` to `false` we are responsible for setting the object's position and
57901  * dimensions accordingly. 
57902  * 
57903  * You can also add sprites by using the surface's add method:
57904  *    
57905  *     drawComponent.surface.add({
57906  *         type: 'circle',
57907  *         fill: '#79BB3F',
57908  *         radius: 100,
57909  *         x: 100,
57910  *         y: 100
57911  *     });
57912  *  
57913  * For more information on Sprites, the core elements added to a draw component's surface,
57914  * refer to the Ext.draw.Sprite documentation.
57915  */
57916 Ext.define('Ext.draw.Component', {
57917
57918     /* Begin Definitions */
57919
57920     alias: 'widget.draw',
57921
57922     extend: 'Ext.Component',
57923
57924     requires: [
57925         'Ext.draw.Surface',
57926         'Ext.layout.component.Draw'
57927     ],
57928
57929     /* End Definitions */
57930
57931     /**
57932      * @cfg {Array} enginePriority
57933      * Defines the priority order for which Surface implementation to use. The first
57934      * one supported by the current environment will be used.
57935      */
57936     enginePriority: ['Svg', 'Vml'],
57937
57938     baseCls: Ext.baseCSSPrefix + 'surface',
57939
57940     componentLayout: 'draw',
57941
57942     /**
57943      * @cfg {Boolean} viewBox
57944      * Turn on view box support which will scale and position items in the draw component to fit to the component while
57945      * maintaining aspect ratio. Note that this scaling can override other sizing settings on yor items. Defaults to true.
57946      */
57947     viewBox: true,
57948
57949     /**
57950      * @cfg {Boolean} autoSize
57951      * Turn on autoSize support which will set the bounding div's size to the natural size of the contents. Defaults to false.
57952      */
57953     autoSize: false,
57954     
57955     /**
57956      * @cfg {Array} gradients (optional) Define a set of gradients that can be used as `fill` property in sprites.
57957      * The gradients array is an array of objects with the following properties:
57958      *
57959      * <ul>
57960      * <li><strong>id</strong> - string - The unique name of the gradient.</li>
57961      * <li><strong>angle</strong> - number, optional - The angle of the gradient in degrees.</li>
57962      * <li><strong>stops</strong> - object - An object with numbers as keys (from 0 to 100) and style objects
57963      * as values</li>
57964      * </ul>
57965      * 
57966      
57967      For example:
57968      
57969      <pre><code>
57970         gradients: [{
57971             id: 'gradientId',
57972             angle: 45,
57973             stops: {
57974                 0: {
57975                     color: '#555'
57976                 },
57977                 100: {
57978                     color: '#ddd'
57979                 }
57980             }
57981         },  {
57982             id: 'gradientId2',
57983             angle: 0,
57984             stops: {
57985                 0: {
57986                     color: '#590'
57987                 },
57988                 20: {
57989                     color: '#599'
57990                 },
57991                 100: {
57992                     color: '#ddd'
57993                 }
57994             }
57995         }]
57996      </code></pre>
57997      
57998      Then the sprites can use `gradientId` and `gradientId2` by setting the fill attributes to those ids, for example:
57999      
58000      <pre><code>
58001         sprite.setAttributes({
58002             fill: 'url(#gradientId)'
58003         }, true);
58004      </code></pre>
58005      
58006      */
58007
58008     initComponent: function() {
58009         this.callParent(arguments);
58010
58011         this.addEvents(
58012             'mousedown',
58013             'mouseup',
58014             'mousemove',
58015             'mouseenter',
58016             'mouseleave',
58017             'click'
58018         );
58019     },
58020
58021     /**
58022      * @private
58023      *
58024      * Create the Surface on initial render
58025      */
58026     onRender: function() {
58027         var me = this,
58028             viewBox = me.viewBox,
58029             autoSize = me.autoSize,
58030             bbox, items, width, height, x, y;
58031         me.callParent(arguments);
58032
58033         me.createSurface();
58034
58035         items = me.surface.items;
58036
58037         if (viewBox || autoSize) {
58038             bbox = items.getBBox();
58039             width = bbox.width;
58040             height = bbox.height;
58041             x = bbox.x;
58042             y = bbox.y;
58043             if (me.viewBox) {
58044                 me.surface.setViewBox(x, y, width, height);
58045             }
58046             else {
58047                 // AutoSized
58048                 me.autoSizeSurface();
58049             }
58050         }
58051     },
58052
58053     //@private
58054     autoSizeSurface: function() {
58055         var me = this,
58056             items = me.surface.items,
58057             bbox = items.getBBox(),
58058             width = bbox.width,
58059             height = bbox.height;
58060         items.setAttributes({
58061             translate: {
58062                 x: -bbox.x,
58063                 //Opera has a slight offset in the y axis.
58064                 y: -bbox.y + (+Ext.isOpera)
58065             }
58066         }, true);
58067         if (me.rendered) {
58068             me.setSize(width, height);
58069         }
58070         else {
58071             me.surface.setSize(width, height);
58072         }
58073         me.el.setSize(width, height);
58074     },
58075
58076     /**
58077      * Create the Surface instance. Resolves the correct Surface implementation to
58078      * instantiate based on the 'enginePriority' config. Once the Surface instance is
58079      * created you can use the handle to that instance to add sprites. For example:
58080      *
58081      <pre><code>
58082         drawComponent.surface.add(sprite);
58083      </code></pre>
58084      */
58085     createSurface: function() {
58086         var surface = Ext.draw.Surface.create(Ext.apply({}, {
58087                 width: this.width,
58088                 height: this.height,
58089                 renderTo: this.el
58090             }, this.initialConfig));
58091         this.surface = surface;
58092
58093         function refire(eventName) {
58094             return function(e) {
58095                 this.fireEvent(eventName, e);
58096             };
58097         }
58098
58099         surface.on({
58100             scope: this,
58101             mouseup: refire('mouseup'),
58102             mousedown: refire('mousedown'),
58103             mousemove: refire('mousemove'),
58104             mouseenter: refire('mouseenter'),
58105             mouseleave: refire('mouseleave'),
58106             click: refire('click')
58107         });
58108     },
58109
58110
58111     /**
58112      * @private
58113      * 
58114      * Clean up the Surface instance on component destruction
58115      */
58116     onDestroy: function() {
58117         var surface = this.surface;
58118         if (surface) {
58119             surface.destroy();
58120         }
58121         this.callParent(arguments);
58122     }
58123
58124 });
58125
58126 /**
58127  * @class Ext.chart.LegendItem
58128  * @extends Ext.draw.CompositeSprite
58129  * A single item of a legend (marker plus label)
58130  * @constructor
58131  */
58132 Ext.define('Ext.chart.LegendItem', {
58133
58134     /* Begin Definitions */
58135
58136     extend: 'Ext.draw.CompositeSprite',
58137
58138     requires: ['Ext.chart.Shape'],
58139
58140     /* End Definitions */
58141
58142     // Position of the item, relative to the upper-left corner of the legend box
58143     x: 0,
58144     y: 0,
58145     zIndex: 500,
58146
58147     constructor: function(config) {
58148         this.callParent(arguments);
58149         this.createLegend(config);
58150     },
58151
58152     /**
58153      * Creates all the individual sprites for this legend item
58154      */
58155     createLegend: function(config) {
58156         var me = this,
58157             index = config.yFieldIndex,
58158             series = me.series,
58159             seriesType = series.type,
58160             idx = me.yFieldIndex,
58161             legend = me.legend,
58162             surface = me.surface,
58163             refX = legend.x + me.x,
58164             refY = legend.y + me.y,
58165             bbox, z = me.zIndex,
58166             markerConfig, label, mask,
58167             radius, toggle = false,
58168             seriesStyle = Ext.apply(series.seriesStyle, series.style);
58169
58170         function getSeriesProp(name) {
58171             var val = series[name];
58172             return (Ext.isArray(val) ? val[idx] : val);
58173         }
58174         
58175         label = me.add('label', surface.add({
58176             type: 'text',
58177             x: 20,
58178             y: 0,
58179             zIndex: z || 0,
58180             font: legend.labelFont,
58181             text: getSeriesProp('title') || getSeriesProp('yField')
58182         }));
58183
58184         // Line series - display as short line with optional marker in the middle
58185         if (seriesType === 'line' || seriesType === 'scatter') {
58186             if(seriesType === 'line') {
58187                 me.add('line', surface.add({
58188                     type: 'path',
58189                     path: 'M0.5,0.5L16.5,0.5',
58190                     zIndex: z,
58191                     "stroke-width": series.lineWidth,
58192                     "stroke-linejoin": "round",
58193                     "stroke-dasharray": series.dash,
58194                     stroke: seriesStyle.stroke || '#000',
58195                     style: {
58196                         cursor: 'pointer'
58197                     }
58198                 }));
58199             }
58200             if (series.showMarkers || seriesType === 'scatter') {
58201                 markerConfig = Ext.apply(series.markerStyle, series.markerConfig || {});
58202                 me.add('marker', Ext.chart.Shape[markerConfig.type](surface, {
58203                     fill: markerConfig.fill,
58204                     x: 8.5,
58205                     y: 0.5,
58206                     zIndex: z,
58207                     radius: markerConfig.radius || markerConfig.size,
58208                     style: {
58209                         cursor: 'pointer'
58210                     }
58211                 }));
58212             }
58213         }
58214         // All other series types - display as filled box
58215         else {
58216             me.add('box', surface.add({
58217                 type: 'rect',
58218                 zIndex: z,
58219                 x: 0,
58220                 y: 0,
58221                 width: 12,
58222                 height: 12,
58223                 fill: series.getLegendColor(index),
58224                 style: {
58225                     cursor: 'pointer'
58226                 }
58227             }));
58228         }
58229         
58230         me.setAttributes({
58231             hidden: false
58232         }, true);
58233         
58234         bbox = me.getBBox();
58235         
58236         mask = me.add('mask', surface.add({
58237             type: 'rect',
58238             x: bbox.x,
58239             y: bbox.y,
58240             width: bbox.width || 20,
58241             height: bbox.height || 20,
58242             zIndex: (z || 0) + 1000,
58243             fill: '#f00',
58244             opacity: 0,
58245             style: {
58246                 'cursor': 'pointer'
58247             }
58248         }));
58249
58250         //add toggle listener
58251         me.on('mouseover', function() {
58252             label.setStyle({
58253                 'font-weight': 'bold'
58254             });
58255             mask.setStyle({
58256                 'cursor': 'pointer'
58257             });
58258             series._index = index;
58259             series.highlightItem();
58260         }, me);
58261
58262         me.on('mouseout', function() {
58263             label.setStyle({
58264                 'font-weight': 'normal'
58265             });
58266             series._index = index;
58267             series.unHighlightItem();
58268         }, me);
58269         
58270         if (!series.visibleInLegend(index)) {
58271             toggle = true;
58272             label.setAttributes({
58273                opacity: 0.5
58274             }, true);
58275         }
58276
58277         me.on('mousedown', function() {
58278             if (!toggle) {
58279                 series.hideAll();
58280                 label.setAttributes({
58281                     opacity: 0.5
58282                 }, true);
58283             } else {
58284                 series.showAll();
58285                 label.setAttributes({
58286                     opacity: 1
58287                 }, true);
58288             }
58289             toggle = !toggle;
58290         }, me);
58291         me.updatePosition({x:0, y:0}); //Relative to 0,0 at first so that the bbox is calculated correctly
58292     },
58293
58294     /**
58295      * Update the positions of all this item's sprites to match the root position
58296      * of the legend box.
58297      * @param {Object} relativeTo (optional) If specified, this object's 'x' and 'y' values will be used
58298      *                 as the reference point for the relative positioning. Defaults to the Legend.
58299      */
58300     updatePosition: function(relativeTo) {
58301         var me = this,
58302             items = me.items,
58303             ln = items.length,
58304             i = 0,
58305             item;
58306         if (!relativeTo) {
58307             relativeTo = me.legend;
58308         }
58309         for (; i < ln; i++) {
58310             item = items[i];
58311             switch (item.type) {
58312                 case 'text':
58313                     item.setAttributes({
58314                         x: 20 + relativeTo.x + me.x,
58315                         y: relativeTo.y + me.y
58316                     }, true);
58317                     break;
58318                 case 'rect':
58319                     item.setAttributes({
58320                         translate: {
58321                             x: relativeTo.x + me.x,
58322                             y: relativeTo.y + me.y - 6
58323                         }
58324                     }, true);
58325                     break;
58326                 default:
58327                     item.setAttributes({
58328                         translate: {
58329                             x: relativeTo.x + me.x,
58330                             y: relativeTo.y + me.y
58331                         }
58332                     }, true);
58333             }
58334         }
58335     }
58336 });
58337 /**
58338  * @class Ext.chart.Legend
58339  *
58340  * Defines a legend for a chart's series.
58341  * The 'chart' member must be set prior to rendering.
58342  * The legend class displays a list of legend items each of them related with a
58343  * series being rendered. In order to render the legend item of the proper series
58344  * the series configuration object must have `showInSeries` set to true.
58345  *
58346  * The legend configuration object accepts a `position` as parameter.
58347  * The `position` parameter can be `left`, `right`
58348  * `top` or `bottom`. For example:
58349  *
58350  *     legend: {
58351  *         position: 'right'
58352  *     },
58353  * 
58354  * Full example:
58355     <pre><code>
58356     var store = Ext.create('Ext.data.JsonStore', {
58357         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
58358         data: [
58359             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
58360             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
58361             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
58362             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
58363             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}                                                
58364         ]
58365     });
58366     
58367     Ext.create('Ext.chart.Chart', {
58368         renderTo: Ext.getBody(),
58369         width: 500,
58370         height: 300,
58371         animate: true,
58372         store: store,
58373         shadow: true,
58374         theme: 'Category1',
58375         legend: {
58376             position: 'top'
58377         },
58378          axes: [{
58379                 type: 'Numeric',
58380                 grid: true,
58381                 position: 'left',
58382                 fields: ['data1', 'data2', 'data3', 'data4', 'data5'],
58383                 title: 'Sample Values',
58384                 grid: {
58385                     odd: {
58386                         opacity: 1,
58387                         fill: '#ddd',
58388                         stroke: '#bbb',
58389                         'stroke-width': 1
58390                     }
58391                 },
58392                 minimum: 0,
58393                 adjustMinimumByMajorUnit: 0
58394             }, {
58395                 type: 'Category',
58396                 position: 'bottom',
58397                 fields: ['name'],
58398                 title: 'Sample Metrics',
58399                 grid: true,
58400                 label: {
58401                     rotate: {
58402                         degrees: 315
58403                     }
58404                 }
58405         }],
58406         series: [{
58407             type: 'area',
58408             highlight: false,
58409             axis: 'left',
58410             xField: 'name',
58411             yField: ['data1', 'data2', 'data3', 'data4', 'data5'],
58412             style: {
58413                 opacity: 0.93
58414             }
58415         }]
58416     });    
58417     </code></pre>    
58418  *
58419  * @constructor
58420  */
58421 Ext.define('Ext.chart.Legend', {
58422
58423     /* Begin Definitions */
58424
58425     requires: ['Ext.chart.LegendItem'],
58426
58427     /* End Definitions */
58428
58429     /**
58430      * @cfg {Boolean} visible
58431      * Whether or not the legend should be displayed.
58432      */
58433     visible: true,
58434
58435     /**
58436      * @cfg {String} position
58437      * The position of the legend in relation to the chart. One of: "top",
58438      * "bottom", "left", "right", or "float". If set to "float", then the legend
58439      * box will be positioned at the point denoted by the x and y parameters.
58440      */
58441     position: 'bottom',
58442
58443     /**
58444      * @cfg {Number} x
58445      * X-position of the legend box. Used directly if position is set to "float", otherwise 
58446      * it will be calculated dynamically.
58447      */
58448     x: 0,
58449
58450     /**
58451      * @cfg {Number} y
58452      * Y-position of the legend box. Used directly if position is set to "float", otherwise
58453      * it will be calculated dynamically.
58454      */
58455     y: 0,
58456
58457     /**
58458      * @cfg {String} labelFont
58459      * Font to be used for the legend labels, eg '12px Helvetica'
58460      */
58461     labelFont: '12px Helvetica, sans-serif',
58462
58463     /**
58464      * @cfg {String} boxStroke
58465      * Style of the stroke for the legend box
58466      */
58467     boxStroke: '#000',
58468
58469     /**
58470      * @cfg {String} boxStrokeWidth
58471      * Width of the stroke for the legend box
58472      */
58473     boxStrokeWidth: 1,
58474
58475     /**
58476      * @cfg {String} boxFill
58477      * Fill style for the legend box
58478      */
58479     boxFill: '#FFF',
58480
58481     /**
58482      * @cfg {Number} itemSpacing
58483      * Amount of space between legend items
58484      */
58485     itemSpacing: 10,
58486
58487     /**
58488      * @cfg {Number} padding
58489      * Amount of padding between the legend box's border and its items
58490      */
58491     padding: 5,
58492
58493     // @private
58494     width: 0,
58495     // @private
58496     height: 0,
58497
58498     /**
58499      * @cfg {Number} boxZIndex
58500      * Sets the z-index for the legend. Defaults to 100.
58501      */
58502     boxZIndex: 100,
58503
58504     constructor: function(config) {
58505         var me = this;
58506         if (config) {
58507             Ext.apply(me, config);
58508         }
58509         me.items = [];
58510         /**
58511          * Whether the legend box is oriented vertically, i.e. if it is on the left or right side or floating.
58512          * @type {Boolean}
58513          */
58514         me.isVertical = ("left|right|float".indexOf(me.position) !== -1);
58515         
58516         // cache these here since they may get modified later on
58517         me.origX = me.x;
58518         me.origY = me.y;
58519     },
58520
58521     /**
58522      * @private Create all the sprites for the legend
58523      */
58524     create: function() {
58525         var me = this;
58526         me.createItems();
58527         if (!me.created && me.isDisplayed()) {
58528             me.createBox();
58529             me.created = true;
58530
58531             // Listen for changes to series titles to trigger regeneration of the legend
58532             me.chart.series.each(function(series) {
58533                 series.on('titlechange', function() {
58534                     me.create();
58535                     me.updatePosition();
58536                 });
58537             });
58538         }
58539     },
58540
58541     /**
58542      * @private Determine whether the legend should be displayed. Looks at the legend's 'visible' config,
58543      * and also the 'showInLegend' config for each of the series.
58544      */
58545     isDisplayed: function() {
58546         return this.visible && this.chart.series.findIndex('showInLegend', true) !== -1;
58547     },
58548
58549     /**
58550      * @private Create the series markers and labels
58551      */
58552     createItems: function() {
58553         var me = this,
58554             chart = me.chart,
58555             surface = chart.surface,
58556             items = me.items,
58557             padding = me.padding,
58558             itemSpacing = me.itemSpacing,
58559             spacingOffset = 2,
58560             maxWidth = 0,
58561             maxHeight = 0,
58562             totalWidth = 0,
58563             totalHeight = 0,
58564             vertical = me.isVertical,
58565             math = Math,
58566             mfloor = math.floor,
58567             mmax = math.max,
58568             index = 0, 
58569             i = 0, 
58570             len = items ? items.length : 0,
58571             x, y, spacing, item, bbox, height, width;
58572
58573         //remove all legend items
58574         if (len) {
58575             for (; i < len; i++) {
58576                 items[i].destroy();
58577             }
58578         }
58579         //empty array
58580         items.length = [];
58581         // Create all the item labels, collecting their dimensions and positioning each one
58582         // properly in relation to the previous item
58583         chart.series.each(function(series, i) {
58584             if (series.showInLegend) {
58585                 Ext.each([].concat(series.yField), function(field, j) {
58586                     item = Ext.create('Ext.chart.LegendItem', {
58587                         legend: this,
58588                         series: series,
58589                         surface: chart.surface,
58590                         yFieldIndex: j
58591                     });
58592                     bbox = item.getBBox();
58593
58594                     //always measure from x=0, since not all markers go all the way to the left
58595                     width = bbox.width; 
58596                     height = bbox.height;
58597
58598                     if (i + j === 0) {
58599                         spacing = vertical ? padding + height / 2 : padding;
58600                     }
58601                     else {
58602                         spacing = itemSpacing / (vertical ? 2 : 1);
58603                     }
58604                     // Set the item's position relative to the legend box
58605                     item.x = mfloor(vertical ? padding : totalWidth + spacing);
58606                     item.y = mfloor(vertical ? totalHeight + spacing : padding + height / 2);
58607
58608                     // Collect cumulative dimensions
58609                     totalWidth += width + spacing;
58610                     totalHeight += height + spacing;
58611                     maxWidth = mmax(maxWidth, width);
58612                     maxHeight = mmax(maxHeight, height);
58613
58614                     items.push(item);
58615                 }, this);
58616             }
58617         }, me);
58618
58619         // Store the collected dimensions for later
58620         me.width = mfloor((vertical ? maxWidth : totalWidth) + padding * 2);
58621         if (vertical && items.length === 1) {
58622             spacingOffset = 1;
58623         }
58624         me.height = mfloor((vertical ? totalHeight - spacingOffset * spacing : maxHeight) + (padding * 2));
58625         me.itemHeight = maxHeight;
58626     },
58627
58628     /**
58629      * @private Get the bounds for the legend's outer box
58630      */
58631     getBBox: function() {
58632         var me = this;
58633         return {
58634             x: Math.round(me.x) - me.boxStrokeWidth / 2,
58635             y: Math.round(me.y) - me.boxStrokeWidth / 2,
58636             width: me.width,
58637             height: me.height
58638         };
58639     },
58640
58641     /**
58642      * @private Create the box around the legend items
58643      */
58644     createBox: function() {
58645         var me = this,
58646             box = me.boxSprite = me.chart.surface.add(Ext.apply({
58647                 type: 'rect',
58648                 stroke: me.boxStroke,
58649                 "stroke-width": me.boxStrokeWidth,
58650                 fill: me.boxFill,
58651                 zIndex: me.boxZIndex
58652             }, me.getBBox()));
58653         box.redraw();
58654     },
58655
58656     /**
58657      * @private Update the position of all the legend's sprites to match its current x/y values
58658      */
58659     updatePosition: function() {
58660         var me = this,
58661             x, y,
58662             legendWidth = me.width,
58663             legendHeight = me.height,
58664             padding = me.padding,
58665             chart = me.chart,
58666             chartBBox = chart.chartBBox,
58667             insets = chart.insetPadding,
58668             chartWidth = chartBBox.width - (insets * 2),
58669             chartHeight = chartBBox.height - (insets * 2),
58670             chartX = chartBBox.x + insets,
58671             chartY = chartBBox.y + insets,
58672             surface = chart.surface,
58673             mfloor = Math.floor;
58674         
58675         if (me.isDisplayed()) {
58676             // Find the position based on the dimensions
58677             switch(me.position) {
58678                 case "left":
58679                     x = insets;
58680                     y = mfloor(chartY + chartHeight / 2 - legendHeight / 2);
58681                     break;
58682                 case "right":
58683                     x = mfloor(surface.width - legendWidth) - insets;
58684                     y = mfloor(chartY + chartHeight / 2 - legendHeight / 2);
58685                     break;
58686                 case "top":
58687                     x = mfloor(chartX + chartWidth / 2 - legendWidth / 2);
58688                     y = insets;
58689                     break;
58690                 case "bottom":
58691                     x = mfloor(chartX + chartWidth / 2 - legendWidth / 2);
58692                     y = mfloor(surface.height - legendHeight) - insets;
58693                     break;
58694                 default:
58695                     x = mfloor(me.origX) + insets;
58696                     y = mfloor(me.origY) + insets;
58697             }
58698             me.x = x;
58699             me.y = y;
58700
58701             // Update the position of each item
58702             Ext.each(me.items, function(item) {
58703                 item.updatePosition();
58704             });
58705             // Update the position of the outer box
58706             me.boxSprite.setAttributes(me.getBBox(), true);
58707         }
58708     }
58709 });
58710 /**
58711  * @class Ext.chart.Chart
58712  * @extends Ext.draw.Component
58713  *
58714  * The Ext.chart package provides the capability to visualize data.
58715  * Each chart binds directly to an Ext.data.Store enabling automatic updates of the chart.
58716  * A chart configuration object has some overall styling options as well as an array of axes
58717  * and series. A chart instance example could look like:
58718  *
58719   <pre><code>
58720     Ext.create('Ext.chart.Chart', {
58721         renderTo: Ext.getBody(),
58722         width: 800,
58723         height: 600,
58724         animate: true,
58725         store: store1,
58726         shadow: true,
58727         theme: 'Category1',
58728         legend: {
58729             position: 'right'
58730         },
58731         axes: [ ...some axes options... ],
58732         series: [ ...some series options... ]
58733     });
58734   </code></pre>
58735  *
58736  * In this example we set the `width` and `height` of the chart, we decide whether our series are
58737  * animated or not and we select a store to be bound to the chart. We also turn on shadows for all series,
58738  * select a color theme `Category1` for coloring the series, set the legend to the right part of the chart and
58739  * then tell the chart to render itself in the body element of the document. For more information about the axes and
58740  * series configurations please check the documentation of each series (Line, Bar, Pie, etc).
58741  *
58742  * @xtype chart
58743  */
58744
58745 Ext.define('Ext.chart.Chart', {
58746
58747     /* Begin Definitions */
58748
58749     alias: 'widget.chart',
58750
58751     extend: 'Ext.draw.Component',
58752     
58753     mixins: {
58754         themeManager: 'Ext.chart.theme.Theme',
58755         mask: 'Ext.chart.Mask',
58756         navigation: 'Ext.chart.Navigation'
58757     },
58758
58759     requires: [
58760         'Ext.util.MixedCollection',
58761         'Ext.data.StoreManager',
58762         'Ext.chart.Legend',
58763         'Ext.util.DelayedTask'
58764     ],
58765
58766     /* End Definitions */
58767
58768     // @private
58769     viewBox: false,
58770
58771     /**
58772      * @cfg {String} theme (optional) The name of the theme to be used. A theme defines the colors and
58773      * other visual displays of tick marks on axis, text, title text, line colors, marker colors and styles, etc.
58774      * Possible theme values are 'Base', 'Green', 'Sky', 'Red', 'Purple', 'Blue', 'Yellow' and also six category themes
58775      * 'Category1' to 'Category6'. Default value is 'Base'.
58776      */
58777
58778     /**
58779      * @cfg {Boolean/Object} animate (optional) true for the default animation (easing: 'ease' and duration: 500)
58780      * or a standard animation config object to be used for default chart animations. Defaults to false.
58781      */
58782     animate: false,
58783
58784     /**
58785      * @cfg {Boolean/Object} legend (optional) true for the default legend display or a legend config object. Defaults to false.
58786      */
58787     legend: false,
58788
58789     /**
58790      * @cfg {integer} insetPadding (optional) Set the amount of inset padding in pixels for the chart. Defaults to 10.
58791      */
58792     insetPadding: 10,
58793
58794     /**
58795      * @cfg {Array} enginePriority
58796      * Defines the priority order for which Surface implementation to use. The first
58797      * one supported by the current environment will be used.
58798      */
58799     enginePriority: ['Svg', 'Vml'],
58800
58801     /**
58802      * @cfg {Object|Boolean} background (optional) Set the chart background. This can be a gradient object, image, or color.
58803      * Defaults to false for no background.
58804      *
58805      * For example, if `background` were to be a color we could set the object as
58806      *
58807      <pre><code>
58808         background: {
58809             //color string
58810             fill: '#ccc'
58811         }
58812      </code></pre>
58813
58814      You can specify an image by using:
58815
58816      <pre><code>
58817         background: {
58818             image: 'http://path.to.image/'
58819         }
58820      </code></pre>
58821
58822      Also you can specify a gradient by using the gradient object syntax:
58823
58824      <pre><code>
58825         background: {
58826             gradient: {
58827                 id: 'gradientId',
58828                 angle: 45,
58829                 stops: {
58830                     0: {
58831                         color: '#555'
58832                     }
58833                     100: {
58834                         color: '#ddd'
58835                     }
58836                 }
58837             }
58838         }
58839      </code></pre>
58840      */
58841     background: false,
58842
58843     /**
58844      * @cfg {Array} gradients (optional) Define a set of gradients that can be used as `fill` property in sprites.
58845      * The gradients array is an array of objects with the following properties:
58846      *
58847      * <ul>
58848      * <li><strong>id</strong> - string - The unique name of the gradient.</li>
58849      * <li><strong>angle</strong> - number, optional - The angle of the gradient in degrees.</li>
58850      * <li><strong>stops</strong> - object - An object with numbers as keys (from 0 to 100) and style objects
58851      * as values</li>
58852      * </ul>
58853      *
58854
58855      For example:
58856
58857      <pre><code>
58858         gradients: [{
58859             id: 'gradientId',
58860             angle: 45,
58861             stops: {
58862                 0: {
58863                     color: '#555'
58864                 },
58865                 100: {
58866                     color: '#ddd'
58867                 }
58868             }
58869         },  {
58870             id: 'gradientId2',
58871             angle: 0,
58872             stops: {
58873                 0: {
58874                     color: '#590'
58875                 },
58876                 20: {
58877                     color: '#599'
58878                 },
58879                 100: {
58880                     color: '#ddd'
58881                 }
58882             }
58883         }]
58884      </code></pre>
58885
58886      Then the sprites can use `gradientId` and `gradientId2` by setting the fill attributes to those ids, for example:
58887
58888      <pre><code>
58889         sprite.setAttributes({
58890             fill: 'url(#gradientId)'
58891         }, true);
58892      </code></pre>
58893
58894      */
58895
58896
58897     constructor: function(config) {
58898         var me = this,
58899             defaultAnim;
58900         me.initTheme(config.theme || me.theme);
58901         if (me.gradients) {
58902             Ext.apply(config, { gradients: me.gradients });
58903         }
58904         if (me.background) {
58905             Ext.apply(config, { background: me.background });
58906         }
58907         if (config.animate) {
58908             defaultAnim = {
58909                 easing: 'ease',
58910                 duration: 500
58911             };
58912             if (Ext.isObject(config.animate)) {
58913                 config.animate = Ext.applyIf(config.animate, defaultAnim);
58914             }
58915             else {
58916                 config.animate = defaultAnim;
58917             }
58918         }
58919         me.mixins.mask.constructor.call(me, config);
58920         me.mixins.navigation.constructor.call(me, config);
58921         me.callParent([config]);
58922     },
58923
58924     initComponent: function() {
58925         var me = this,
58926             axes,
58927             series;
58928         me.callParent();
58929         me.addEvents(
58930             'itemmousedown',
58931             'itemmouseup',
58932             'itemmouseover',
58933             'itemmouseout',
58934             'itemclick',
58935             'itemdoubleclick',
58936             'itemdragstart',
58937             'itemdrag',
58938             'itemdragend',
58939             /**
58940                  * @event beforerefresh
58941                  * Fires before a refresh to the chart data is called.  If the beforerefresh handler returns
58942                  * <tt>false</tt> the {@link #refresh} action will be cancelled.
58943                  * @param {Chart} this
58944                  */
58945             'beforerefresh',
58946             /**
58947                  * @event refresh
58948                  * Fires after the chart data has been refreshed.
58949                  * @param {Chart} this
58950                  */
58951             'refresh'
58952         );
58953         Ext.applyIf(me, {
58954             zoom: {
58955                 width: 1,
58956                 height: 1,
58957                 x: 0,
58958                 y: 0
58959             }
58960         });
58961         me.maxGutter = [0, 0];
58962         me.store = Ext.data.StoreManager.lookup(me.store);
58963         axes = me.axes;
58964         me.axes = Ext.create('Ext.util.MixedCollection', false, function(a) { return a.position; });
58965         if (axes) {
58966             me.axes.addAll(axes);
58967         }
58968         series = me.series;
58969         me.series = Ext.create('Ext.util.MixedCollection', false, function(a) { return a.seriesId || (a.seriesId = Ext.id(null, 'ext-chart-series-')); });
58970         if (series) {
58971             me.series.addAll(series);
58972         }
58973         if (me.legend !== false) {
58974             me.legend = Ext.create('Ext.chart.Legend', Ext.applyIf({chart:me}, me.legend));
58975         }
58976
58977         me.on({
58978             mousemove: me.onMouseMove,
58979             mouseleave: me.onMouseLeave,
58980             mousedown: me.onMouseDown,
58981             mouseup: me.onMouseUp,
58982             scope: me
58983         });
58984     },
58985
58986     // @private overrides the component method to set the correct dimensions to the chart.
58987     afterComponentLayout: function(width, height) {
58988         var me = this;
58989         if (Ext.isNumber(width) && Ext.isNumber(height)) {
58990             me.curWidth = width;
58991             me.curHeight = height;
58992             me.redraw(true);
58993         }
58994         this.callParent(arguments);
58995     },
58996
58997     /**
58998      * Redraw the chart. If animations are set this will animate the chart too.
58999      * @cfg {boolean} resize Optional flag which changes the default origin points of the chart for animations.
59000      */
59001     redraw: function(resize) {
59002         var me = this,
59003             chartBBox = me.chartBBox = {
59004                 x: 0,
59005                 y: 0,
59006                 height: me.curHeight,
59007                 width: me.curWidth
59008             },
59009             legend = me.legend;
59010         me.surface.setSize(chartBBox.width, chartBBox.height);
59011         // Instantiate Series and Axes
59012         me.series.each(me.initializeSeries, me);
59013         me.axes.each(me.initializeAxis, me);
59014         //process all views (aggregated data etc) on stores
59015         //before rendering.
59016         me.axes.each(function(axis) {
59017             axis.processView();
59018         });
59019         me.axes.each(function(axis) {
59020             axis.drawAxis(true);
59021         });
59022
59023         // Create legend if not already created
59024         if (legend !== false) {
59025             legend.create();
59026         }
59027
59028         // Place axes properly, including influence from each other
59029         me.alignAxes();
59030
59031         // Reposition legend based on new axis alignment
59032         if (me.legend !== false) {
59033             legend.updatePosition();
59034         }
59035
59036         // Find the max gutter
59037         me.getMaxGutter();
59038
59039         // Draw axes and series
59040         me.resizing = !!resize;
59041
59042         me.axes.each(me.drawAxis, me);
59043         me.series.each(me.drawCharts, me);
59044         me.resizing = false;
59045     },
59046
59047     // @private set the store after rendering the chart.
59048     afterRender: function() {
59049         var ref,
59050             me = this;
59051         this.callParent();
59052
59053         if (me.categoryNames) {
59054             me.setCategoryNames(me.categoryNames);
59055         }
59056
59057         if (me.tipRenderer) {
59058             ref = me.getFunctionRef(me.tipRenderer);
59059             me.setTipRenderer(ref.fn, ref.scope);
59060         }
59061         me.bindStore(me.store, true);
59062         me.refresh();
59063     },
59064
59065     // @private get x and y position of the mouse cursor.
59066     getEventXY: function(e) {
59067         var me = this,
59068             box = this.surface.getRegion(),
59069             pageXY = e.getXY(),
59070             x = pageXY[0] - box.left,
59071             y = pageXY[1] - box.top;
59072         return [x, y];
59073     },
59074
59075     // @private wrap the mouse down position to delegate the event to the series.
59076     onClick: function(e) {
59077         var me = this,
59078             position = me.getEventXY(e),
59079             item;
59080
59081         // Ask each series if it has an item corresponding to (not necessarily exactly
59082         // on top of) the current mouse coords. Fire itemclick event.
59083         me.series.each(function(series) {
59084             if (Ext.draw.Draw.withinBox(position[0], position[1], series.bbox)) {
59085                 if (series.getItemForPoint) {
59086                     item = series.getItemForPoint(position[0], position[1]);
59087                     if (item) {
59088                         series.fireEvent('itemclick', item);
59089                     }
59090                 }
59091             }
59092         }, me);
59093     },
59094
59095     // @private wrap the mouse down position to delegate the event to the series.
59096     onMouseDown: function(e) {
59097         var me = this,
59098             position = me.getEventXY(e),
59099             item;
59100
59101         if (me.mask) {
59102             me.mixins.mask.onMouseDown.call(me, e);
59103         }
59104         // Ask each series if it has an item corresponding to (not necessarily exactly
59105         // on top of) the current mouse coords. Fire mousedown event.
59106         me.series.each(function(series) {
59107             if (Ext.draw.Draw.withinBox(position[0], position[1], series.bbox)) {
59108                 if (series.getItemForPoint) {
59109                     item = series.getItemForPoint(position[0], position[1]);
59110                     if (item) {
59111                         series.fireEvent('itemmousedown', item);
59112                     }
59113                 }
59114             }
59115         }, me);
59116     },
59117
59118     // @private wrap the mouse up event to delegate it to the series.
59119     onMouseUp: function(e) {
59120         var me = this,
59121             position = me.getEventXY(e),
59122             item;
59123
59124         if (me.mask) {
59125             me.mixins.mask.onMouseUp.call(me, e);
59126         }
59127         // Ask each series if it has an item corresponding to (not necessarily exactly
59128         // on top of) the current mouse coords. Fire mousedown event.
59129         me.series.each(function(series) {
59130             if (Ext.draw.Draw.withinBox(position[0], position[1], series.bbox)) {
59131                 if (series.getItemForPoint) {
59132                     item = series.getItemForPoint(position[0], position[1]);
59133                     if (item) {
59134                         series.fireEvent('itemmouseup', item);
59135                     }
59136                 }
59137             }
59138         }, me);
59139     },
59140
59141     // @private wrap the mouse move event so it can be delegated to the series.
59142     onMouseMove: function(e) {
59143         var me = this,
59144             position = me.getEventXY(e),
59145             item, last, storeItem, storeField;
59146
59147         if (me.mask) {
59148             me.mixins.mask.onMouseMove.call(me, e);
59149         }
59150         // Ask each series if it has an item corresponding to (not necessarily exactly
59151         // on top of) the current mouse coords. Fire itemmouseover/out events.
59152         me.series.each(function(series) {
59153             if (Ext.draw.Draw.withinBox(position[0], position[1], series.bbox)) {
59154                 if (series.getItemForPoint) {
59155                     item = series.getItemForPoint(position[0], position[1]);
59156                     last = series._lastItemForPoint;
59157                     storeItem = series._lastStoreItem;
59158                     storeField = series._lastStoreField;
59159
59160
59161                     if (item !== last || item && (item.storeItem != storeItem || item.storeField != storeField)) {
59162                         if (last) {
59163                             series.fireEvent('itemmouseout', last);
59164                             delete series._lastItemForPoint;
59165                             delete series._lastStoreField;
59166                             delete series._lastStoreItem;
59167                         }
59168                         if (item) {
59169                             series.fireEvent('itemmouseover', item);
59170                             series._lastItemForPoint = item;
59171                             series._lastStoreItem = item.storeItem;
59172                             series._lastStoreField = item.storeField;
59173                         }
59174                     }
59175                 }
59176             } else {
59177                 last = series._lastItemForPoint;
59178                 if (last) {
59179                     series.fireEvent('itemmouseout', last);
59180                     delete series._lastItemForPoint;
59181                     delete series._lastStoreField;
59182                     delete series._lastStoreItem;
59183                 }
59184             }
59185         }, me);
59186     },
59187
59188     // @private handle mouse leave event.
59189     onMouseLeave: function(e) {
59190         var me = this;
59191         if (me.mask) {
59192             me.mixins.mask.onMouseLeave.call(me, e);
59193         }
59194         me.series.each(function(series) {
59195             delete series._lastItemForPoint;
59196         });
59197     },
59198
59199     // @private buffered refresh for when we update the store
59200     delayRefresh: function() {
59201         var me = this;
59202         if (!me.refreshTask) {
59203             me.refreshTask = Ext.create('Ext.util.DelayedTask', me.refresh, me);
59204         }
59205         me.refreshTask.delay(me.refreshBuffer);
59206     },
59207
59208     // @private
59209     refresh: function() {
59210         var me = this;
59211         if (me.rendered && me.curWidth != undefined && me.curHeight != undefined) {
59212             if (me.fireEvent('beforerefresh', me) !== false) {
59213                 me.redraw();
59214                 me.fireEvent('refresh', me);
59215             }
59216         }
59217     },
59218
59219     /**
59220      * Changes the data store bound to this chart and refreshes it.
59221      * @param {Store} store The store to bind to this chart
59222      */
59223     bindStore: function(store, initial) {
59224         var me = this;
59225         if (!initial && me.store) {
59226             if (store !== me.store && me.store.autoDestroy) {
59227                 me.store.destroy();
59228             }
59229             else {
59230                 me.store.un('datachanged', me.refresh, me);
59231                 me.store.un('add', me.delayRefresh, me);
59232                 me.store.un('remove', me.delayRefresh, me);
59233                 me.store.un('update', me.delayRefresh, me);
59234                 me.store.un('clear', me.refresh, me);
59235             }
59236         }
59237         if (store) {
59238             store = Ext.data.StoreManager.lookup(store);
59239             store.on({
59240                 scope: me,
59241                 datachanged: me.refresh,
59242                 add: me.delayRefresh,
59243                 remove: me.delayRefresh,
59244                 update: me.delayRefresh,
59245                 clear: me.refresh
59246             });
59247         }
59248         me.store = store;
59249         if (store && !initial) {
59250             me.refresh();
59251         }
59252     },
59253
59254     // @private Create Axis
59255     initializeAxis: function(axis) {
59256         var me = this,
59257             chartBBox = me.chartBBox,
59258             w = chartBBox.width,
59259             h = chartBBox.height,
59260             x = chartBBox.x,
59261             y = chartBBox.y,
59262             themeAttrs = me.themeAttrs,
59263             config = {
59264                 chart: me
59265             };
59266         if (themeAttrs) {
59267             config.axisStyle = Ext.apply({}, themeAttrs.axis);
59268             config.axisLabelLeftStyle = Ext.apply({}, themeAttrs.axisLabelLeft);
59269             config.axisLabelRightStyle = Ext.apply({}, themeAttrs.axisLabelRight);
59270             config.axisLabelTopStyle = Ext.apply({}, themeAttrs.axisLabelTop);
59271             config.axisLabelBottomStyle = Ext.apply({}, themeAttrs.axisLabelBottom);
59272             config.axisTitleLeftStyle = Ext.apply({}, themeAttrs.axisTitleLeft);
59273             config.axisTitleRightStyle = Ext.apply({}, themeAttrs.axisTitleRight);
59274             config.axisTitleTopStyle = Ext.apply({}, themeAttrs.axisTitleTop);
59275             config.axisTitleBottomStyle = Ext.apply({}, themeAttrs.axisTitleBottom);
59276         }
59277         switch (axis.position) {
59278             case 'top':
59279                 Ext.apply(config, {
59280                     length: w,
59281                     width: h,
59282                     x: x,
59283                     y: y
59284                 });
59285             break;
59286             case 'bottom':
59287                 Ext.apply(config, {
59288                     length: w,
59289                     width: h,
59290                     x: x,
59291                     y: h
59292                 });
59293             break;
59294             case 'left':
59295                 Ext.apply(config, {
59296                     length: h,
59297                     width: w,
59298                     x: x,
59299                     y: h
59300                 });
59301             break;
59302             case 'right':
59303                 Ext.apply(config, {
59304                     length: h,
59305                     width: w,
59306                     x: w,
59307                     y: h
59308                 });
59309             break;
59310         }
59311         if (!axis.chart) {
59312             Ext.apply(config, axis);
59313             axis = me.axes.replace(Ext.createByAlias('axis.' + axis.type.toLowerCase(), config));
59314         }
59315         else {
59316             Ext.apply(axis, config);
59317         }
59318     },
59319
59320
59321     /**
59322      * @private Adjust the dimensions and positions of each axis and the chart body area after accounting
59323      * for the space taken up on each side by the axes and legend.
59324      */
59325     alignAxes: function() {
59326         var me = this,
59327             axes = me.axes,
59328             legend = me.legend,
59329             edges = ['top', 'right', 'bottom', 'left'],
59330             chartBBox,
59331             insetPadding = me.insetPadding,
59332             insets = {
59333                 top: insetPadding,
59334                 right: insetPadding,
59335                 bottom: insetPadding,
59336                 left: insetPadding
59337             };
59338
59339         function getAxis(edge) {
59340             var i = axes.findIndex('position', edge);
59341             return (i < 0) ? null : axes.getAt(i);
59342         }
59343
59344         // Find the space needed by axes and legend as a positive inset from each edge
59345         Ext.each(edges, function(edge) {
59346             var isVertical = (edge === 'left' || edge === 'right'),
59347                 axis = getAxis(edge),
59348                 bbox;
59349
59350             // Add legend size if it's on this edge
59351             if (legend !== false) {
59352                 if (legend.position === edge) {
59353                     bbox = legend.getBBox();
59354                     insets[edge] += (isVertical ? bbox.width : bbox.height) + insets[edge];
59355                 }
59356             }
59357
59358             // Add axis size if there's one on this edge only if it has been
59359             //drawn before.
59360             if (axis && axis.bbox) {
59361                 bbox = axis.bbox;
59362                 insets[edge] += (isVertical ? bbox.width : bbox.height);
59363             }
59364         });
59365         // Build the chart bbox based on the collected inset values
59366         chartBBox = {
59367             x: insets.left,
59368             y: insets.top,
59369             width: me.curWidth - insets.left - insets.right,
59370             height: me.curHeight - insets.top - insets.bottom
59371         };
59372         me.chartBBox = chartBBox;
59373
59374         // Go back through each axis and set its length and position based on the
59375         // corresponding edge of the chartBBox
59376         axes.each(function(axis) {
59377             var pos = axis.position,
59378                 isVertical = (pos === 'left' || pos === 'right');
59379
59380             axis.x = (pos === 'right' ? chartBBox.x + chartBBox.width : chartBBox.x);
59381             axis.y = (pos === 'top' ? chartBBox.y : chartBBox.y + chartBBox.height);
59382             axis.width = (isVertical ? chartBBox.width : chartBBox.height);
59383             axis.length = (isVertical ? chartBBox.height : chartBBox.width);
59384         });
59385     },
59386
59387     // @private initialize the series.
59388     initializeSeries: function(series, idx) {
59389         var me = this,
59390             themeAttrs = me.themeAttrs,
59391             seriesObj, markerObj, seriesThemes, st,
59392             markerThemes, colorArrayStyle = [],
59393             i = 0, l,
59394             config = {
59395                 chart: me,
59396                 seriesId: series.seriesId
59397             };
59398         if (themeAttrs) {
59399             seriesThemes = themeAttrs.seriesThemes;
59400             markerThemes = themeAttrs.markerThemes;
59401             seriesObj = Ext.apply({}, themeAttrs.series);
59402             markerObj = Ext.apply({}, themeAttrs.marker);
59403             config.seriesStyle = Ext.apply(seriesObj, seriesThemes[idx % seriesThemes.length]);
59404             config.seriesLabelStyle = Ext.apply({}, themeAttrs.seriesLabel);
59405             config.markerStyle = Ext.apply(markerObj, markerThemes[idx % markerThemes.length]);
59406             if (themeAttrs.colors) {
59407                 config.colorArrayStyle = themeAttrs.colors;
59408             } else {
59409                 colorArrayStyle = [];
59410                 for (l = seriesThemes.length; i < l; i++) {
59411                     st = seriesThemes[i];
59412                     if (st.fill || st.stroke) {
59413                         colorArrayStyle.push(st.fill || st.stroke);
59414                     }
59415                 }
59416                 if (colorArrayStyle.length) {
59417                     config.colorArrayStyle = colorArrayStyle;
59418                 }
59419             }
59420             config.seriesIdx = idx;
59421         }
59422         if (series instanceof Ext.chart.series.Series) {
59423             Ext.apply(series, config);
59424         } else {
59425             Ext.applyIf(config, series);
59426             series = me.series.replace(Ext.createByAlias('series.' + series.type.toLowerCase(), config));
59427         }
59428         if (series.initialize) {
59429             series.initialize();
59430         }
59431     },
59432
59433     // @private
59434     getMaxGutter: function() {
59435         var me = this,
59436             maxGutter = [0, 0];
59437         me.series.each(function(s) {
59438             var gutter = s.getGutters && s.getGutters() || [0, 0];
59439             maxGutter[0] = Math.max(maxGutter[0], gutter[0]);
59440             maxGutter[1] = Math.max(maxGutter[1], gutter[1]);
59441         });
59442         me.maxGutter = maxGutter;
59443     },
59444
59445     // @private draw axis.
59446     drawAxis: function(axis) {
59447         axis.drawAxis();
59448     },
59449
59450     // @private draw series.
59451     drawCharts: function(series) {
59452         series.triggerafterrender = false;
59453         series.drawSeries();
59454         if (!this.animate) {
59455             series.fireEvent('afterrender');
59456         }
59457     },
59458
59459     // @private remove gently.
59460     destroy: function() {
59461         this.surface.destroy();
59462         this.bindStore(null);
59463         this.callParent(arguments);
59464     }
59465 });
59466
59467 /**
59468  * @class Ext.chart.Highlight
59469  * @ignore
59470  */
59471 Ext.define('Ext.chart.Highlight', {
59472
59473     /* Begin Definitions */
59474
59475     requires: ['Ext.fx.Anim'],
59476
59477     /* End Definitions */
59478
59479     /**
59480      * Highlight the given series item.
59481      * @param {Boolean|Object} Default's false. Can also be an object width style properties (i.e fill, stroke, radius) 
59482      * or just use default styles per series by setting highlight = true.
59483      */
59484     highlight: false,
59485
59486     highlightCfg : null,
59487
59488     constructor: function(config) {
59489         if (config.highlight) {
59490             if (config.highlight !== true) { //is an object
59491                 this.highlightCfg = Ext.apply({}, config.highlight);
59492             }
59493             else {
59494                 this.highlightCfg = {
59495                     fill: '#fdd',
59496                     radius: 20,
59497                     lineWidth: 5,
59498                     stroke: '#f55'
59499                 };
59500             }
59501         }
59502     },
59503
59504     /**
59505      * Highlight the given series item.
59506      * @param {Object} item Info about the item; same format as returned by #getItemForPoint.
59507      */
59508     highlightItem: function(item) {
59509         if (!item) {
59510             return;
59511         }
59512         
59513         var me = this,
59514             sprite = item.sprite,
59515             opts = me.highlightCfg,
59516             surface = me.chart.surface,
59517             animate = me.chart.animate,
59518             p,
59519             from,
59520             to,
59521             pi;
59522
59523         if (!me.highlight || !sprite || sprite._highlighted) {
59524             return;
59525         }
59526         if (sprite._anim) {
59527             sprite._anim.paused = true;
59528         }
59529         sprite._highlighted = true;
59530         if (!sprite._defaults) {
59531             sprite._defaults = Ext.apply(sprite._defaults || {},
59532             sprite.attr);
59533             from = {};
59534             to = {};
59535             for (p in opts) {
59536                 if (! (p in sprite._defaults)) {
59537                     sprite._defaults[p] = surface.availableAttrs[p];
59538                 }
59539                 from[p] = sprite._defaults[p];
59540                 to[p] = opts[p];
59541                 if (Ext.isObject(opts[p])) {
59542                     from[p] = {};
59543                     to[p] = {};
59544                     Ext.apply(sprite._defaults[p], sprite.attr[p]);
59545                     Ext.apply(from[p], sprite._defaults[p]);
59546                     for (pi in sprite._defaults[p]) {
59547                         if (! (pi in opts[p])) {
59548                             to[p][pi] = from[p][pi];
59549                         } else {
59550                             to[p][pi] = opts[p][pi];
59551                         }
59552                     }
59553                     for (pi in opts[p]) {
59554                         if (! (pi in to[p])) {
59555                             to[p][pi] = opts[p][pi];
59556                         }
59557                     }
59558                 }
59559             }
59560             sprite._from = from;
59561             sprite._to = to;
59562         }
59563         if (animate) {
59564             sprite._anim = Ext.create('Ext.fx.Anim', {
59565                 target: sprite,
59566                 from: sprite._from,
59567                 to: sprite._to,
59568                 duration: 150
59569             });
59570         } else {
59571             sprite.setAttributes(sprite._to, true);
59572         }
59573     },
59574
59575     /**
59576      * Un-highlight any existing highlights
59577      */
59578     unHighlightItem: function() {
59579         if (!this.highlight || !this.items) {
59580             return;
59581         }
59582
59583         var me = this,
59584             items = me.items,
59585             len = items.length,
59586             opts = me.highlightCfg,
59587             animate = me.chart.animate,
59588             i = 0,
59589             obj,
59590             p,
59591             sprite;
59592
59593         for (; i < len; i++) {
59594             if (!items[i]) {
59595                 continue;
59596             }
59597             sprite = items[i].sprite;
59598             if (sprite && sprite._highlighted) {
59599                 if (sprite._anim) {
59600                     sprite._anim.paused = true;
59601                 }
59602                 obj = {};
59603                 for (p in opts) {
59604                     if (Ext.isObject(sprite._defaults[p])) {
59605                         obj[p] = {};
59606                         Ext.apply(obj[p], sprite._defaults[p]);
59607                     }
59608                     else {
59609                         obj[p] = sprite._defaults[p];
59610                     }
59611                 }
59612                 if (animate) {
59613                     sprite._anim = Ext.create('Ext.fx.Anim', {
59614                         target: sprite,
59615                         to: obj,
59616                         duration: 150
59617                     });
59618                 }
59619                 else {
59620                     sprite.setAttributes(obj, true);
59621                 }
59622                 delete sprite._highlighted;
59623                 //delete sprite._defaults;
59624             }
59625         }
59626     },
59627
59628     cleanHighlights: function() {
59629         if (!this.highlight) {
59630             return;
59631         }
59632
59633         var group = this.group,
59634             markerGroup = this.markerGroup,
59635             i = 0,
59636             l;
59637         for (l = group.getCount(); i < l; i++) {
59638             delete group.getAt(i)._defaults;
59639         }
59640         if (markerGroup) {
59641             for (l = markerGroup.getCount(); i < l; i++) {
59642                 delete markerGroup.getAt(i)._defaults;
59643             }
59644         }
59645     }
59646 });
59647 /**
59648  * @class Ext.chart.Label
59649  *
59650  * Labels is a mixin whose methods are appended onto the Series class. Labels is an interface with methods implemented
59651  * in each of the Series (Pie, Bar, etc) for label creation and label placement.
59652  *
59653  * The methods implemented by the Series are:
59654  *  
59655  * - **`onCreateLabel(storeItem, item, i, display)`** Called each time a new label is created.
59656  *   The arguments of the method are:
59657  *   - *`storeItem`* The element of the store that is related to the label sprite.
59658  *   - *`item`* The item related to the label sprite. An item is an object containing the position of the shape
59659  *     used to describe the visualization and also pointing to the actual shape (circle, rectangle, path, etc).
59660  *   - *`i`* The index of the element created (i.e the first created label, second created label, etc)
59661  *   - *`display`* The display type. May be <b>false</b> if the label is hidden
59662  *
59663  *  - **`onPlaceLabel(label, storeItem, item, i, display, animate)`** Called for updating the position of the label.
59664  *    The arguments of the method are:
59665  *    - *`label`* The sprite label.</li>
59666  *    - *`storeItem`* The element of the store that is related to the label sprite</li>
59667  *    - *`item`* The item related to the label sprite. An item is an object containing the position of the shape
59668  *      used to describe the visualization and also pointing to the actual shape (circle, rectangle, path, etc).
59669  *    - *`i`* The index of the element to be updated (i.e. whether it is the first, second, third from the labelGroup)
59670  *    - *`display`* The display type. May be <b>false</b> if the label is hidden.
59671  *    - *`animate`* A boolean value to set or unset animations for the labels.
59672  */
59673 Ext.define('Ext.chart.Label', {
59674
59675     /* Begin Definitions */
59676
59677     requires: ['Ext.draw.Color'],
59678     
59679     /* End Definitions */
59680
59681     /**
59682      * @cfg {String} display
59683      * Specifies the presence and position of labels for each pie slice. Either "rotate", "middle", "insideStart",
59684      * "insideEnd", "outside", "over", "under", or "none" to prevent label rendering.
59685      * Default value: 'none'.
59686      */
59687
59688     /**
59689      * @cfg {String} color
59690      * The color of the label text.
59691      * Default value: '#000' (black).
59692      */
59693
59694     /**
59695      * @cfg {String} field
59696      * The name of the field to be displayed in the label.
59697      * Default value: 'name'.
59698      */
59699
59700     /**
59701      * @cfg {Number} minMargin
59702      * Specifies the minimum distance from a label to the origin of the visualization.
59703      * This parameter is useful when using PieSeries width variable pie slice lengths.
59704      * Default value: 50.
59705      */
59706
59707     /**
59708      * @cfg {String} font
59709      * The font used for the labels.
59710      * Defautl value: "11px Helvetica, sans-serif".
59711      */
59712
59713     /**
59714      * @cfg {String} orientation
59715      * Either "horizontal" or "vertical".
59716      * Dafault value: "horizontal".
59717      */
59718
59719     /**
59720      * @cfg {Function} renderer
59721      * Optional function for formatting the label into a displayable value.
59722      * Default value: function(v) { return v; }
59723      * @param v
59724      */
59725
59726     //@private a regex to parse url type colors.
59727     colorStringRe: /url\s*\(\s*#([^\/)]+)\s*\)/,
59728     
59729     //@private the mixin constructor. Used internally by Series.
59730     constructor: function(config) {
59731         var me = this;
59732         me.label = Ext.applyIf(me.label || {},
59733         {
59734             display: "none",
59735             color: "#000",
59736             field: "name",
59737             minMargin: 50,
59738             font: "11px Helvetica, sans-serif",
59739             orientation: "horizontal",
59740             renderer: function(v) {
59741                 return v;
59742             }
59743         });
59744
59745         if (me.label.display !== 'none') {
59746             me.labelsGroup = me.chart.surface.getGroup(me.seriesId + '-labels');
59747         }
59748     },
59749
59750     //@private a method to render all labels in the labelGroup
59751     renderLabels: function() {
59752         var me = this,
59753             chart = me.chart,
59754             gradients = chart.gradients,
59755             gradient,
59756             items = me.items,
59757             animate = chart.animate,
59758             config = me.label,
59759             display = config.display,
59760             color = config.color,
59761             field = [].concat(config.field),
59762             group = me.labelsGroup,
59763             store = me.chart.store,
59764             len = store.getCount(),
59765             ratio = items.length / len,
59766             i, count, j, 
59767             k, gradientsCount = (gradients || 0) && gradients.length,
59768             colorStopTotal, colorStopIndex, colorStop,
59769             item, label, storeItem,
59770             sprite, spriteColor, spriteBrightness, labelColor,
59771             Color = Ext.draw.Color,
59772             colorString;
59773
59774         if (display == 'none') {
59775             return;
59776         }
59777
59778         for (i = 0, count = 0; i < len; i++) {
59779             for (j = 0; j < ratio; j++) {
59780                 item = items[count];
59781                 label = group.getAt(count);
59782                 storeItem = store.getAt(i);
59783
59784                 if (!item && label) {
59785                     label.hide(true);
59786                 }
59787
59788                 if (item && field[j]) {
59789                     if (!label) {
59790                         label = me.onCreateLabel(storeItem, item, i, display, j, count);
59791                     }
59792                     me.onPlaceLabel(label, storeItem, item, i, display, animate, j, count);
59793
59794                     //set contrast
59795                     if (config.contrast && item.sprite) {
59796                         sprite = item.sprite;
59797                         colorString = sprite._to && sprite._to.fill || sprite.attr.fill;
59798                         spriteColor = Color.fromString(colorString);
59799                         //color wasn't parsed property maybe because it's a gradient id
59800                         if (colorString && !spriteColor) {
59801                             colorString = colorString.match(me.colorStringRe)[1];
59802                             for (k = 0; k < gradientsCount; k++) {
59803                                 gradient = gradients[k];
59804                                 if (gradient.id == colorString) {
59805                                     //avg color stops
59806                                     colorStop = 0; colorStopTotal = 0;
59807                                     for (colorStopIndex in gradient.stops) {
59808                                         colorStop++;
59809                                         colorStopTotal += Color.fromString(gradient.stops[colorStopIndex].color).getGrayscale();
59810                                     }
59811                                     spriteBrightness = (colorStopTotal / colorStop) / 255;
59812                                     break;
59813                                 }
59814                             }
59815                         }
59816                         else {
59817                             spriteBrightness = spriteColor.getGrayscale() / 255;
59818                         }
59819                         labelColor = Color.fromString(label.attr.color || label.attr.fill).getHSL();
59820                         
59821                         labelColor[2] = spriteBrightness > 0.5? 0.2 : 0.8;
59822                         label.setAttributes({
59823                             fill: String(Color.fromHSL.apply({}, labelColor))
59824                         }, true);
59825                     }
59826                 }
59827                 count++;
59828             }
59829         }
59830         me.hideLabels(count);
59831     },
59832
59833     //@private a method to hide labels.
59834     hideLabels: function(index) {
59835         var labelsGroup = this.labelsGroup, len;
59836         if (labelsGroup) {
59837             len = labelsGroup.getCount();
59838             while (len-->index) {
59839                 labelsGroup.getAt(len).hide(true);
59840             }
59841         }
59842     }
59843 });
59844 Ext.define('Ext.chart.MaskLayer', {
59845     extend: 'Ext.Component',
59846     
59847     constructor: function(config) {
59848         config = Ext.apply(config || {}, {
59849             style: 'position:absolute;background-color:#888;cursor:move;opacity:0.6;border:1px solid #222;'
59850         });
59851         this.callParent([config]);    
59852     },
59853     
59854     initComponent: function() {
59855         var me = this;
59856         me.callParent(arguments);
59857         me.addEvents(
59858             'mousedown',
59859             'mouseup',
59860             'mousemove',
59861             'mouseenter',
59862             'mouseleave'
59863         );
59864     },
59865
59866     initDraggable: function() {
59867         this.callParent(arguments);
59868         this.dd.onStart = function (e) {
59869             var me = this,
59870                 comp = me.comp;
59871     
59872             // Cache the start [X, Y] array
59873             this.startPosition = comp.getPosition(true);
59874     
59875             // If client Component has a ghost method to show a lightweight version of itself
59876             // then use that as a drag proxy unless configured to liveDrag.
59877             if (comp.ghost && !comp.liveDrag) {
59878                  me.proxy = comp.ghost();
59879                  me.dragTarget = me.proxy.header.el;
59880             }
59881     
59882             // Set the constrainTo Region before we start dragging.
59883             if (me.constrain || me.constrainDelegate) {
59884                 me.constrainTo = me.calculateConstrainRegion();
59885             }
59886         };
59887     }
59888 });
59889 /**
59890  * @class Ext.chart.TipSurface
59891  * @ignore
59892  */
59893 Ext.define('Ext.chart.TipSurface', {
59894
59895     /* Begin Definitions */
59896
59897     extend: 'Ext.draw.Component',
59898
59899     /* End Definitions */
59900
59901     spriteArray: false,
59902     renderFirst: true,
59903
59904     constructor: function(config) {
59905         this.callParent([config]);
59906         if (config.sprites) {
59907             this.spriteArray = [].concat(config.sprites);
59908             delete config.sprites;
59909         }
59910     },
59911
59912     onRender: function() {
59913         var me = this,
59914             i = 0,
59915             l = 0,
59916             sp,
59917             sprites;
59918             this.callParent(arguments);
59919         sprites = me.spriteArray;
59920         if (me.renderFirst && sprites) {
59921             me.renderFirst = false;
59922             for (l = sprites.length; i < l; i++) {
59923                 sp = me.surface.add(sprites[i]);
59924                 sp.setAttributes({
59925                     hidden: false
59926                 },
59927                 true);
59928             }
59929         }
59930     }
59931 });
59932
59933 /**
59934  * @class Ext.chart.Tip
59935  * @ignore
59936  */
59937 Ext.define('Ext.chart.Tip', {
59938
59939     /* Begin Definitions */
59940
59941     requires: ['Ext.tip.ToolTip', 'Ext.chart.TipSurface'],
59942
59943     /* End Definitions */
59944
59945     constructor: function(config) {
59946         var me = this,
59947             surface,
59948             sprites,
59949             tipSurface;
59950         if (config.tips) {
59951             me.tipTimeout = null;
59952             me.tipConfig = Ext.apply({}, config.tips, {
59953                 renderer: Ext.emptyFn,
59954                 constrainPosition: false
59955             });
59956             me.tooltip = Ext.create('Ext.tip.ToolTip', me.tipConfig);
59957             Ext.getBody().on('mousemove', me.tooltip.onMouseMove, me.tooltip);
59958             if (me.tipConfig.surface) {
59959                 //initialize a surface
59960                 surface = me.tipConfig.surface;
59961                 sprites = surface.sprites;
59962                 tipSurface = Ext.create('Ext.chart.TipSurface', {
59963                     id: 'tipSurfaceComponent',
59964                     sprites: sprites
59965                 });
59966                 if (surface.width && surface.height) {
59967                     tipSurface.setSize(surface.width, surface.height);
59968                 }
59969                 me.tooltip.add(tipSurface);
59970                 me.spriteTip = tipSurface;
59971             }
59972         }
59973     },
59974
59975     showTip: function(item) {
59976         var me = this;
59977         if (!me.tooltip) {
59978             return;
59979         }
59980         clearTimeout(me.tipTimeout);
59981         var tooltip = me.tooltip,
59982             spriteTip = me.spriteTip,
59983             tipConfig = me.tipConfig,
59984             trackMouse = tooltip.trackMouse,
59985             sprite, surface, surfaceExt, pos, x, y;
59986         if (!trackMouse) {
59987             tooltip.trackMouse = true;
59988             sprite = item.sprite;
59989             surface = sprite.surface;
59990             surfaceExt = Ext.get(surface.getId());
59991             if (surfaceExt) {
59992                 pos = surfaceExt.getXY();
59993                 x = pos[0] + (sprite.attr.x || 0) + (sprite.attr.translation && sprite.attr.translation.x || 0);
59994                 y = pos[1] + (sprite.attr.y || 0) + (sprite.attr.translation && sprite.attr.translation.y || 0);
59995                 tooltip.targetXY = [x, y];
59996             }
59997         }
59998         if (spriteTip) {
59999             tipConfig.renderer.call(tooltip, item.storeItem, item, spriteTip.surface);
60000         } else {
60001             tipConfig.renderer.call(tooltip, item.storeItem, item);
60002         }
60003         tooltip.show();
60004         tooltip.trackMouse = trackMouse;
60005     },
60006
60007     hideTip: function(item) {
60008         var tooltip = this.tooltip;
60009         if (!tooltip) {
60010             return;
60011         }
60012         clearTimeout(this.tipTimeout);
60013         this.tipTimeout = setTimeout(function() {
60014             tooltip.hide();
60015         }, 0);
60016     }
60017 });
60018 /**
60019  * @class Ext.chart.axis.Abstract
60020  * @ignore
60021  */
60022 Ext.define('Ext.chart.axis.Abstract', {
60023
60024     /* Begin Definitions */
60025
60026     requires: ['Ext.chart.Chart'],
60027
60028     /* End Definitions */
60029
60030     constructor: function(config) {
60031         config = config || {};
60032
60033         var me = this,
60034             pos = config.position || 'left';
60035
60036         pos = pos.charAt(0).toUpperCase() + pos.substring(1);
60037         //axisLabel(Top|Bottom|Right|Left)Style
60038         config.label = Ext.apply(config['axisLabel' + pos + 'Style'] || {}, config.label || {});
60039         config.axisTitleStyle = Ext.apply(config['axisTitle' + pos + 'Style'] || {}, config.labelTitle || {});
60040         Ext.apply(me, config);
60041         me.fields = [].concat(me.fields);
60042         this.callParent();
60043         me.labels = [];
60044         me.getId();
60045         me.labelGroup = me.chart.surface.getGroup(me.axisId + "-labels");
60046     },
60047
60048     alignment: null,
60049     grid: false,
60050     steps: 10,
60051     x: 0,
60052     y: 0,
60053     minValue: 0,
60054     maxValue: 0,
60055
60056     getId: function() {
60057         return this.axisId || (this.axisId = Ext.id(null, 'ext-axis-'));
60058     },
60059
60060     /*
60061       Called to process a view i.e to make aggregation and filtering over
60062       a store creating a substore to be used to render the axis. Since many axes
60063       may do different things on the data and we want the final result of all these
60064       operations to be rendered we need to call processView on all axes before drawing
60065       them.
60066     */
60067     processView: Ext.emptyFn,
60068
60069     drawAxis: Ext.emptyFn,
60070     addDisplayAndLabels: Ext.emptyFn
60071 });
60072
60073 /**
60074  * @class Ext.chart.axis.Axis
60075  * @extends Ext.chart.axis.Abstract
60076  * 
60077  * Defines axis for charts. The axis position, type, style can be configured.
60078  * The axes are defined in an axes array of configuration objects where the type, 
60079  * field, grid and other configuration options can be set. To know more about how 
60080  * to create a Chart please check the Chart class documentation. Here's an example for the axes part:
60081  * An example of axis for a series (in this case for an area chart that has multiple layers of yFields) could be:
60082  * 
60083   <pre><code>
60084     axes: [{
60085         type: 'Numeric',
60086         grid: true,
60087         position: 'left',
60088         fields: ['data1', 'data2', 'data3'],
60089         title: 'Number of Hits',
60090         grid: {
60091             odd: {
60092                 opacity: 1,
60093                 fill: '#ddd',
60094                 stroke: '#bbb',
60095                 'stroke-width': 1
60096             }
60097         },
60098         minimum: 0
60099     }, {
60100         type: 'Category',
60101         position: 'bottom',
60102         fields: ['name'],
60103         title: 'Month of the Year',
60104         grid: true,
60105         label: {
60106             rotate: {
60107                 degrees: 315
60108             }
60109         }
60110     }]
60111    </code></pre>
60112  * 
60113  * In this case we use a `Numeric` axis for displaying the values of the Area series and a `Category` axis for displaying the names of
60114  * the store elements. The numeric axis is placed on the left of the screen, while the category axis is placed at the bottom of the chart. 
60115  * Both the category and numeric axes have `grid` set, which means that horizontal and vertical lines will cover the chart background. In the 
60116  * category axis the labels will be rotated so they can fit the space better.
60117  */
60118 Ext.define('Ext.chart.axis.Axis', {
60119
60120     /* Begin Definitions */
60121
60122     extend: 'Ext.chart.axis.Abstract',
60123
60124     alternateClassName: 'Ext.chart.Axis',
60125
60126     requires: ['Ext.draw.Draw'],
60127
60128     /* End Definitions */
60129
60130     /**
60131      * @cfg {Number} majorTickSteps 
60132      * If `minimum` and `maximum` are specified it forces the number of major ticks to the specified value.
60133      */
60134
60135     /**
60136      * @cfg {Number} minorTickSteps 
60137      * The number of small ticks between two major ticks. Default is zero.
60138      */
60139
60140     /**
60141      * @cfg {Number} dashSize 
60142      * The size of the dash marker. Default's 3.
60143      */
60144     dashSize: 3,
60145     
60146     /**
60147      * @cfg {String} position
60148      * Where to set the axis. Available options are `left`, `bottom`, `right`, `top`. Default's `bottom`.
60149      */
60150     position: 'bottom',
60151     
60152     // @private
60153     skipFirst: false,
60154     
60155     /**
60156      * @cfg {Number} length
60157      * Offset axis position. Default's 0.
60158      */
60159     length: 0,
60160     
60161     /**
60162      * @cfg {Number} width
60163      * Offset axis width. Default's 0.
60164      */
60165     width: 0,
60166     
60167     majorTickSteps: false,
60168
60169     // @private
60170     applyData: Ext.emptyFn,
60171
60172     // @private creates a structure with start, end and step points.
60173     calcEnds: function() {
60174         var me = this,
60175             math = Math,
60176             mmax = math.max,
60177             mmin = math.min,
60178             store = me.chart.substore || me.chart.store,
60179             series = me.chart.series.items,
60180             fields = me.fields,
60181             ln = fields.length,
60182             min = isNaN(me.minimum) ? Infinity : me.minimum,
60183             max = isNaN(me.maximum) ? -Infinity : me.maximum,
60184             prevMin = me.prevMin,
60185             prevMax = me.prevMax,
60186             aggregate = false,
60187             total = 0,
60188             excludes = [],
60189             outfrom, outto,
60190             i, l, values, rec, out;
60191
60192         //if one series is stacked I have to aggregate the values
60193         //for the scale.
60194         for (i = 0, l = series.length; !aggregate && i < l; i++) {
60195             aggregate = aggregate || series[i].stacked;
60196             excludes = series[i].__excludes || excludes;
60197         }
60198         store.each(function(record) {
60199             if (aggregate) {
60200                 if (!isFinite(min)) {
60201                     min = 0;
60202                 }
60203                 for (values = [0, 0], i = 0; i < ln; i++) {
60204                     if (excludes[i]) {
60205                         continue;
60206                     }
60207                     rec = record.get(fields[i]);
60208                     values[+(rec > 0)] += math.abs(rec);
60209                 }
60210                 max = mmax(max, -values[0], values[1]);
60211                 min = mmin(min, -values[0], values[1]);
60212             }
60213             else {
60214                 for (i = 0; i < ln; i++) {
60215                     if (excludes[i]) {
60216                         continue;
60217                     }
60218                     value = record.get(fields[i]);
60219                     max = mmax(max, value);
60220                     min = mmin(min, value);
60221                 }
60222             }
60223         });
60224         if (!isFinite(max)) {
60225             max = me.prevMax || 0;
60226         }
60227         if (!isFinite(min)) {
60228             min = me.prevMin || 0;
60229         }
60230         //normalize min max for snapEnds.
60231         if (min != max && (max != (max >> 0))) {
60232             max = (max >> 0) + 1;
60233         }
60234         out = Ext.draw.Draw.snapEnds(min, max, me.majorTickSteps !== false ?  (me.majorTickSteps +1) : me.steps);
60235         outfrom = out.from;
60236         outto = out.to;
60237         if (!isNaN(me.maximum)) {
60238             //TODO(nico) users are responsible for their own minimum/maximum values set.
60239             //Clipping should be added to remove lines in the chart which are below the axis.
60240             out.to = me.maximum;
60241         }
60242         if (!isNaN(me.minimum)) {
60243             //TODO(nico) users are responsible for their own minimum/maximum values set.
60244             //Clipping should be added to remove lines in the chart which are below the axis.
60245             out.from = me.minimum;
60246         }
60247         
60248         //Adjust after adjusting minimum and maximum
60249         out.step = (out.to - out.from) / (outto - outfrom) * out.step;
60250         
60251         if (me.adjustMaximumByMajorUnit) {
60252             out.to += out.step;
60253         }
60254         if (me.adjustMinimumByMajorUnit) {
60255             out.from -= out.step;
60256         }
60257         me.prevMin = min == max? 0 : min;
60258         me.prevMax = max;
60259         return out;
60260     },
60261
60262     /**
60263      * Renders the axis into the screen and updates it's position.
60264      */
60265     drawAxis: function (init) {
60266         var me = this,
60267             i, j,
60268             x = me.x,
60269             y = me.y,
60270             gutterX = me.chart.maxGutter[0],
60271             gutterY = me.chart.maxGutter[1],
60272             dashSize = me.dashSize,
60273             subDashesX = me.minorTickSteps || 0,
60274             subDashesY = me.minorTickSteps || 0,
60275             length = me.length,
60276             position = me.position,
60277             inflections = [],
60278             calcLabels = false,
60279             stepCalcs = me.applyData(),
60280             step = stepCalcs.step,
60281             steps = stepCalcs.steps,
60282             from = stepCalcs.from,
60283             to = stepCalcs.to,
60284             trueLength,
60285             currentX,
60286             currentY,
60287             path,
60288             prev,
60289             dashesX,
60290             dashesY,
60291             delta;
60292         
60293         //If no steps are specified
60294         //then don't draw the axis. This generally happens
60295         //when an empty store.
60296         if (me.hidden || isNaN(step) || (from == to)) {
60297             return;
60298         }
60299
60300         me.from = stepCalcs.from;
60301         me.to = stepCalcs.to;
60302         if (position == 'left' || position == 'right') {
60303             currentX = Math.floor(x) + 0.5;
60304             path = ["M", currentX, y, "l", 0, -length];
60305             trueLength = length - (gutterY * 2);
60306         }
60307         else {
60308             currentY = Math.floor(y) + 0.5;
60309             path = ["M", x, currentY, "l", length, 0];
60310             trueLength = length - (gutterX * 2);
60311         }
60312         
60313         delta = trueLength / (steps || 1);
60314         dashesX = Math.max(subDashesX +1, 0);
60315         dashesY = Math.max(subDashesY +1, 0);
60316         if (me.type == 'Numeric') {
60317             calcLabels = true;
60318             me.labels = [stepCalcs.from];
60319         }
60320         if (position == 'right' || position == 'left') {
60321             currentY = y - gutterY;
60322             currentX = x - ((position == 'left') * dashSize * 2);
60323             while (currentY >= y - gutterY - trueLength) {
60324                 path.push("M", currentX, Math.floor(currentY) + 0.5, "l", dashSize * 2 + 1, 0);
60325                 if (currentY != y - gutterY) {
60326                     for (i = 1; i < dashesY; i++) {
60327                         path.push("M", currentX + dashSize, Math.floor(currentY + delta * i / dashesY) + 0.5, "l", dashSize + 1, 0);
60328                     }
60329                 }
60330                 inflections.push([ Math.floor(x), Math.floor(currentY) ]);
60331                 currentY -= delta;
60332                 if (calcLabels) {
60333                     me.labels.push(me.labels[me.labels.length -1] + step);
60334                 }
60335                 if (delta === 0) {
60336                     break;
60337                 }
60338             }
60339             if (Math.round(currentY + delta - (y - gutterY - trueLength))) {
60340                 path.push("M", currentX, Math.floor(y - length + gutterY) + 0.5, "l", dashSize * 2 + 1, 0);
60341                 for (i = 1; i < dashesY; i++) {
60342                     path.push("M", currentX + dashSize, Math.floor(y - length + gutterY + delta * i / dashesY) + 0.5, "l", dashSize + 1, 0);
60343                 }
60344                 inflections.push([ Math.floor(x), Math.floor(currentY) ]);
60345                 if (calcLabels) {
60346                     me.labels.push(me.labels[me.labels.length -1] + step);
60347                 }
60348             }
60349         } else {
60350             currentX = x + gutterX;
60351             currentY = y - ((position == 'top') * dashSize * 2);
60352             while (currentX <= x + gutterX + trueLength) {
60353                 path.push("M", Math.floor(currentX) + 0.5, currentY, "l", 0, dashSize * 2 + 1);
60354                 if (currentX != x + gutterX) {
60355                     for (i = 1; i < dashesX; i++) {
60356                         path.push("M", Math.floor(currentX - delta * i / dashesX) + 0.5, currentY, "l", 0, dashSize + 1);
60357                     }
60358                 }
60359                 inflections.push([ Math.floor(currentX), Math.floor(y) ]);
60360                 currentX += delta;
60361                 if (calcLabels) {
60362                     me.labels.push(me.labels[me.labels.length -1] + step);
60363                 }
60364                 if (delta === 0) {
60365                     break;
60366                 }
60367             }
60368             if (Math.round(currentX - delta - (x + gutterX + trueLength))) {
60369                 path.push("M", Math.floor(x + length - gutterX) + 0.5, currentY, "l", 0, dashSize * 2 + 1);
60370                 for (i = 1; i < dashesX; i++) {
60371                     path.push("M", Math.floor(x + length - gutterX - delta * i / dashesX) + 0.5, currentY, "l", 0, dashSize + 1);
60372                 }
60373                 inflections.push([ Math.floor(currentX), Math.floor(y) ]);
60374                 if (calcLabels) {
60375                     me.labels.push(me.labels[me.labels.length -1] + step);
60376                 }
60377             }
60378         }
60379         if (!me.axis) {
60380             me.axis = me.chart.surface.add(Ext.apply({
60381                 type: 'path',
60382                 path: path
60383             }, me.axisStyle));
60384         }
60385         me.axis.setAttributes({
60386             path: path
60387         }, true);
60388         me.inflections = inflections;
60389         if (!init && me.grid) {
60390             me.drawGrid();
60391         }
60392         me.axisBBox = me.axis.getBBox();
60393         me.drawLabel();
60394     },
60395
60396     /**
60397      * Renders an horizontal and/or vertical grid into the Surface.
60398      */
60399     drawGrid: function() {
60400         var me = this,
60401             surface = me.chart.surface, 
60402             grid = me.grid,
60403             odd = grid.odd,
60404             even = grid.even,
60405             inflections = me.inflections,
60406             ln = inflections.length - ((odd || even)? 0 : 1),
60407             position = me.position,
60408             gutter = me.chart.maxGutter,
60409             width = me.width - 2,
60410             vert = false,
60411             point, prevPoint,
60412             i = 1,
60413             path = [], styles, lineWidth, dlineWidth,
60414             oddPath = [], evenPath = [];
60415         
60416         if ((gutter[1] !== 0 && (position == 'left' || position == 'right')) ||
60417             (gutter[0] !== 0 && (position == 'top' || position == 'bottom'))) {
60418             i = 0;
60419             ln++;
60420         }
60421         for (; i < ln; i++) {
60422             point = inflections[i];
60423             prevPoint = inflections[i - 1];
60424             if (odd || even) {
60425                 path = (i % 2)? oddPath : evenPath;
60426                 styles = ((i % 2)? odd : even) || {};
60427                 lineWidth = (styles.lineWidth || styles['stroke-width'] || 0) / 2;
60428                 dlineWidth = 2 * lineWidth;
60429                 if (position == 'left') {
60430                     path.push("M", prevPoint[0] + 1 + lineWidth, prevPoint[1] + 0.5 - lineWidth, 
60431                               "L", prevPoint[0] + 1 + width - lineWidth, prevPoint[1] + 0.5 - lineWidth,
60432                               "L", point[0] + 1 + width - lineWidth, point[1] + 0.5 + lineWidth,
60433                               "L", point[0] + 1 + lineWidth, point[1] + 0.5 + lineWidth, "Z");
60434                 }
60435                 else if (position == 'right') {
60436                     path.push("M", prevPoint[0] - lineWidth, prevPoint[1] + 0.5 - lineWidth, 
60437                               "L", prevPoint[0] - width + lineWidth, prevPoint[1] + 0.5 - lineWidth,
60438                               "L", point[0] - width + lineWidth, point[1] + 0.5 + lineWidth,
60439                               "L", point[0] - lineWidth, point[1] + 0.5 + lineWidth, "Z");
60440                 }
60441                 else if (position == 'top') {
60442                     path.push("M", prevPoint[0] + 0.5 + lineWidth, prevPoint[1] + 1 + lineWidth, 
60443                               "L", prevPoint[0] + 0.5 + lineWidth, prevPoint[1] + 1 + width - lineWidth,
60444                               "L", point[0] + 0.5 - lineWidth, point[1] + 1 + width - lineWidth,
60445                               "L", point[0] + 0.5 - lineWidth, point[1] + 1 + lineWidth, "Z");
60446                 }
60447                 else {
60448                     path.push("M", prevPoint[0] + 0.5 + lineWidth, prevPoint[1] - lineWidth, 
60449                             "L", prevPoint[0] + 0.5 + lineWidth, prevPoint[1] - width + lineWidth,
60450                             "L", point[0] + 0.5 - lineWidth, point[1] - width + lineWidth,
60451                             "L", point[0] + 0.5 - lineWidth, point[1] - lineWidth, "Z");
60452                 }
60453             } else {
60454                 if (position == 'left') {
60455                     path = path.concat(["M", point[0] + 0.5, point[1] + 0.5, "l", width, 0]);
60456                 }
60457                 else if (position == 'right') {
60458                     path = path.concat(["M", point[0] - 0.5, point[1] + 0.5, "l", -width, 0]);
60459                 }
60460                 else if (position == 'top') {
60461                     path = path.concat(["M", point[0] + 0.5, point[1] + 0.5, "l", 0, width]);
60462                 }
60463                 else {
60464                     path = path.concat(["M", point[0] + 0.5, point[1] - 0.5, "l", 0, -width]);
60465                 }
60466             }
60467         }
60468         if (odd || even) {
60469             if (oddPath.length) {
60470                 if (!me.gridOdd && oddPath.length) {
60471                     me.gridOdd = surface.add({
60472                         type: 'path',
60473                         path: oddPath
60474                     });
60475                 }
60476                 me.gridOdd.setAttributes(Ext.apply({
60477                     path: oddPath,
60478                     hidden: false
60479                 }, odd || {}), true);
60480             }
60481             if (evenPath.length) {
60482                 if (!me.gridEven) {
60483                     me.gridEven = surface.add({
60484                         type: 'path',
60485                         path: evenPath
60486                     });
60487                 } 
60488                 me.gridEven.setAttributes(Ext.apply({
60489                     path: evenPath,
60490                     hidden: false
60491                 }, even || {}), true);
60492             }
60493         }
60494         else {
60495             if (path.length) {
60496                 if (!me.gridLines) {
60497                     me.gridLines = me.chart.surface.add({
60498                         type: 'path',
60499                         path: path,
60500                         "stroke-width": me.lineWidth || 1,
60501                         stroke: me.gridColor || '#ccc'
60502                     });
60503                 }
60504                 me.gridLines.setAttributes({
60505                     hidden: false,
60506                     path: path
60507                 }, true);
60508             }
60509             else if (me.gridLines) {
60510                 me.gridLines.hide(true);
60511             }
60512         }
60513     },
60514
60515     //@private
60516     getOrCreateLabel: function(i, text) {
60517         var me = this,
60518             labelGroup = me.labelGroup,
60519             textLabel = labelGroup.getAt(i),
60520             surface = me.chart.surface;
60521         if (textLabel) {
60522             if (text != textLabel.attr.text) {
60523                 textLabel.setAttributes(Ext.apply({
60524                     text: text
60525                 }, me.label), true);
60526                 textLabel._bbox = textLabel.getBBox();
60527             }
60528         }
60529         else {
60530             textLabel = surface.add(Ext.apply({
60531                 group: labelGroup,
60532                 type: 'text',
60533                 x: 0,
60534                 y: 0,
60535                 text: text
60536             }, me.label));
60537             surface.renderItem(textLabel);
60538             textLabel._bbox = textLabel.getBBox();
60539         }
60540         //get untransformed bounding box
60541         if (me.label.rotation) {
60542             textLabel.setAttributes({
60543                 rotation: {
60544                     degrees: 0    
60545                 }    
60546             }, true);
60547             textLabel._ubbox = textLabel.getBBox();
60548             textLabel.setAttributes(me.label, true);
60549         } else {
60550             textLabel._ubbox = textLabel._bbox;
60551         }
60552         return textLabel;
60553     },
60554     
60555     rect2pointArray: function(sprite) {
60556         var surface = this.chart.surface,
60557             rect = surface.getBBox(sprite, true),
60558             p1 = [rect.x, rect.y],
60559             p1p = p1.slice(),
60560             p2 = [rect.x + rect.width, rect.y],
60561             p2p = p2.slice(),
60562             p3 = [rect.x + rect.width, rect.y + rect.height],
60563             p3p = p3.slice(),
60564             p4 = [rect.x, rect.y + rect.height],
60565             p4p = p4.slice(),
60566             matrix = sprite.matrix;
60567         //transform the points
60568         p1[0] = matrix.x.apply(matrix, p1p);
60569         p1[1] = matrix.y.apply(matrix, p1p);
60570         
60571         p2[0] = matrix.x.apply(matrix, p2p);
60572         p2[1] = matrix.y.apply(matrix, p2p);
60573         
60574         p3[0] = matrix.x.apply(matrix, p3p);
60575         p3[1] = matrix.y.apply(matrix, p3p);
60576         
60577         p4[0] = matrix.x.apply(matrix, p4p);
60578         p4[1] = matrix.y.apply(matrix, p4p);
60579         return [p1, p2, p3, p4];
60580     },
60581     
60582     intersect: function(l1, l2) {
60583         var r1 = this.rect2pointArray(l1),
60584             r2 = this.rect2pointArray(l2);
60585         return !!Ext.draw.Draw.intersect(r1, r2).length;
60586     },
60587     
60588     drawHorizontalLabels: function() {
60589        var  me = this,
60590             labelConf = me.label,
60591             floor = Math.floor,
60592             max = Math.max,
60593             axes = me.chart.axes,
60594             position = me.position,
60595             inflections = me.inflections,
60596             ln = inflections.length,
60597             labels = me.labels,
60598             labelGroup = me.labelGroup,
60599             maxHeight = 0,
60600             ratio,
60601             gutterY = me.chart.maxGutter[1],
60602             ubbox, bbox, point, prevX, prevLabel,
60603             projectedWidth = 0,
60604             textLabel, attr, textRight, text,
60605             label, last, x, y, i, firstLabel;
60606
60607         last = ln - 1;
60608         //get a reference to the first text label dimensions
60609         point = inflections[0];
60610         firstLabel = me.getOrCreateLabel(0, me.label.renderer(labels[0]));
60611         ratio = Math.abs(Math.sin(labelConf.rotate && (labelConf.rotate.degrees * Math.PI / 180) || 0)) >> 0;
60612         
60613         for (i = 0; i < ln; i++) {
60614             point = inflections[i];
60615             text = me.label.renderer(labels[i]);
60616             textLabel = me.getOrCreateLabel(i, text);
60617             bbox = textLabel._bbox;
60618             maxHeight = max(maxHeight, bbox.height + me.dashSize + me.label.padding);
60619             x = floor(point[0] - (ratio? bbox.height : bbox.width) / 2);
60620             if (me.chart.maxGutter[0] == 0) {
60621                 if (i == 0 && axes.findIndex('position', 'left') == -1) {
60622                     x = point[0];
60623                 }
60624                 else if (i == last && axes.findIndex('position', 'right') == -1) {
60625                     x = point[0] - bbox.width;
60626                 }
60627             }
60628             if (position == 'top') {
60629                 y = point[1] - (me.dashSize * 2) - me.label.padding - (bbox.height / 2);
60630             }
60631             else {
60632                 y = point[1] + (me.dashSize * 2) + me.label.padding + (bbox.height / 2);
60633             }
60634             
60635             textLabel.setAttributes({
60636                 hidden: false,
60637                 x: x,
60638                 y: y
60639             }, true);
60640
60641             // Skip label if there isn't available minimum space
60642             if (i != 0 && (me.intersect(textLabel, prevLabel)
60643                 || me.intersect(textLabel, firstLabel))) {
60644                 textLabel.hide(true);
60645                 continue;
60646             }
60647             
60648             prevLabel = textLabel;
60649         }
60650
60651         return maxHeight;
60652     },
60653     
60654     drawVerticalLabels: function() {
60655         var me = this,
60656             inflections = me.inflections,
60657             position = me.position,
60658             ln = inflections.length,
60659             labels = me.labels,
60660             maxWidth = 0,
60661             max = Math.max,
60662             floor = Math.floor,
60663             ceil = Math.ceil,
60664             axes = me.chart.axes,
60665             gutterY = me.chart.maxGutter[1],
60666             ubbox, bbox, point, prevLabel,
60667             projectedWidth = 0,
60668             textLabel, attr, textRight, text,
60669             label, last, x, y, i;
60670
60671         last = ln;
60672         for (i = 0; i < last; i++) {
60673             point = inflections[i];
60674             text = me.label.renderer(labels[i]);
60675             textLabel = me.getOrCreateLabel(i, text);
60676             bbox = textLabel._bbox;
60677             
60678             maxWidth = max(maxWidth, bbox.width + me.dashSize + me.label.padding);
60679             y = point[1];
60680             if (gutterY < bbox.height / 2) {
60681                 if (i == last - 1 && axes.findIndex('position', 'top') == -1) {
60682                     y = me.y - me.length + ceil(bbox.height / 2);
60683                 }
60684                 else if (i == 0 && axes.findIndex('position', 'bottom') == -1) {
60685                     y = me.y - floor(bbox.height / 2);
60686                 }
60687             }
60688             if (position == 'left') {
60689                 x = point[0] - bbox.width - me.dashSize - me.label.padding - 2;
60690             }
60691             else {
60692                 x = point[0] + me.dashSize + me.label.padding + 2;
60693             }    
60694             textLabel.setAttributes(Ext.apply({
60695                 hidden: false,
60696                 x: x,
60697                 y: y
60698             }, me.label), true);
60699             // Skip label if there isn't available minimum space
60700             if (i != 0 && me.intersect(textLabel, prevLabel)) {
60701                 textLabel.hide(true);
60702                 continue;
60703             }
60704             prevLabel = textLabel;
60705         }
60706         
60707         return maxWidth;
60708     },
60709
60710     /**
60711      * Renders the labels in the axes.
60712      */
60713     drawLabel: function() {
60714         var me = this,
60715             position = me.position,
60716             labelGroup = me.labelGroup,
60717             inflections = me.inflections,
60718             maxWidth = 0,
60719             maxHeight = 0,
60720             ln, i;
60721
60722         if (position == 'left' || position == 'right') {
60723             maxWidth = me.drawVerticalLabels();    
60724         } else {
60725             maxHeight = me.drawHorizontalLabels();
60726         }
60727
60728         // Hide unused bars
60729         ln = labelGroup.getCount();
60730         i = inflections.length;
60731         for (; i < ln; i++) {
60732             labelGroup.getAt(i).hide(true);
60733         }
60734
60735         me.bbox = {};
60736         Ext.apply(me.bbox, me.axisBBox);
60737         me.bbox.height = maxHeight;
60738         me.bbox.width = maxWidth;
60739         if (Ext.isString(me.title)) {
60740             me.drawTitle(maxWidth, maxHeight);
60741         }
60742     },
60743
60744     // @private creates the elipsis for the text.
60745     elipsis: function(sprite, text, desiredWidth, minWidth, center) {
60746         var bbox,
60747             x;
60748
60749         if (desiredWidth < minWidth) {
60750             sprite.hide(true);
60751             return false;
60752         }
60753         while (text.length > 4) {
60754             text = text.substr(0, text.length - 4) + "...";
60755             sprite.setAttributes({
60756                 text: text
60757             }, true);
60758             bbox = sprite.getBBox();
60759             if (bbox.width < desiredWidth) {
60760                 if (typeof center == 'number') {
60761                     sprite.setAttributes({
60762                         x: Math.floor(center - (bbox.width / 2))
60763                     }, true);
60764                 }
60765                 break;
60766             }
60767         }
60768         return true;
60769     },
60770
60771     /**
60772      * Updates the {@link #title} of this axis.
60773      * @param {String} title
60774      */
60775     setTitle: function(title) {
60776         this.title = title;
60777         this.drawLabel();
60778     },
60779
60780     // @private draws the title for the axis.
60781     drawTitle: function(maxWidth, maxHeight) {
60782         var me = this,
60783             position = me.position,
60784             surface = me.chart.surface,
60785             displaySprite = me.displaySprite,
60786             title = me.title,
60787             rotate = (position == 'left' || position == 'right'),
60788             x = me.x,
60789             y = me.y,
60790             base, bbox, pad;
60791
60792         if (displaySprite) {
60793             displaySprite.setAttributes({text: title}, true);
60794         } else {
60795             base = {
60796                 type: 'text',
60797                 x: 0,
60798                 y: 0,
60799                 text: title
60800             };
60801             displaySprite = me.displaySprite = surface.add(Ext.apply(base, me.axisTitleStyle, me.labelTitle));
60802             surface.renderItem(displaySprite);
60803         }
60804         bbox = displaySprite.getBBox();
60805         pad = me.dashSize + me.label.padding;
60806
60807         if (rotate) {
60808             y -= ((me.length / 2) - (bbox.height / 2));
60809             if (position == 'left') {
60810                 x -= (maxWidth + pad + (bbox.width / 2));
60811             }
60812             else {
60813                 x += (maxWidth + pad + bbox.width - (bbox.width / 2));
60814             }
60815             me.bbox.width += bbox.width + 10;
60816         }
60817         else {
60818             x += (me.length / 2) - (bbox.width * 0.5);
60819             if (position == 'top') {
60820                 y -= (maxHeight + pad + (bbox.height * 0.3));
60821             }
60822             else {
60823                 y += (maxHeight + pad + (bbox.height * 0.8));
60824             }
60825             me.bbox.height += bbox.height + 10;
60826         }
60827         displaySprite.setAttributes({
60828             translate: {
60829                 x: x,
60830                 y: y
60831             }
60832         }, true);
60833     }
60834 });
60835 /**
60836  * @class Ext.chart.axis.Category
60837  * @extends Ext.chart.axis.Axis
60838  *
60839  * A type of axis that displays items in categories. This axis is generally used to
60840  * display categorical information like names of items, month names, quarters, etc.
60841  * but no quantitative values. For that other type of information <em>Number</em>
60842  * axis are more suitable.
60843  *
60844  * As with other axis you can set the position of the axis and its title. For example:
60845  * {@img Ext.chart.axis.Category/Ext.chart.axis.Category.png Ext.chart.axis.Category chart axis}
60846     <pre><code>
60847    var store = Ext.create('Ext.data.JsonStore', {
60848         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
60849         data: [
60850             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
60851             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
60852             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
60853             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
60854             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}                                                
60855         ]
60856     });
60857     
60858     Ext.create('Ext.chart.Chart', {
60859         renderTo: Ext.getBody(),
60860         width: 500,
60861         height: 300,
60862         store: store,
60863         axes: [{
60864             type: 'Numeric',
60865             grid: true,
60866             position: 'left',
60867             fields: ['data1', 'data2', 'data3', 'data4', 'data5'],
60868             title: 'Sample Values',
60869             grid: {
60870                 odd: {
60871                     opacity: 1,
60872                     fill: '#ddd',
60873                     stroke: '#bbb',
60874                     'stroke-width': 1
60875                 }
60876             },
60877             minimum: 0,
60878             adjustMinimumByMajorUnit: 0
60879         }, {
60880             type: 'Category',
60881             position: 'bottom',
60882             fields: ['name'],
60883             title: 'Sample Metrics',
60884             grid: true,
60885             label: {
60886                 rotate: {
60887                     degrees: 315
60888                 }
60889             }
60890         }],
60891         series: [{
60892             type: 'area',
60893             highlight: false,
60894             axis: 'left',
60895             xField: 'name',
60896             yField: ['data1', 'data2', 'data3', 'data4', 'data5'],
60897             style: {
60898                 opacity: 0.93
60899             }
60900         }]
60901     });
60902     </code></pre>
60903
60904     In this example with set the category axis to the bottom of the surface, bound the axis to
60905     the <em>name</em> property and set as title <em>Month of the Year</em>.
60906  */
60907
60908 Ext.define('Ext.chart.axis.Category', {
60909
60910     /* Begin Definitions */
60911
60912     extend: 'Ext.chart.axis.Axis',
60913
60914     alternateClassName: 'Ext.chart.CategoryAxis',
60915
60916     alias: 'axis.category',
60917
60918     /* End Definitions */
60919
60920     /**
60921      * A list of category names to display along this axis.
60922      *
60923      * @property categoryNames
60924      * @type Array
60925      */
60926     categoryNames: null,
60927
60928     /**
60929      * Indicates whether or not to calculate the number of categories (ticks and
60930      * labels) when there is not enough room to display all labels on the axis.
60931      * If set to true, the axis will determine the number of categories to plot.
60932      * If not, all categories will be plotted.
60933      *
60934      * @property calculateCategoryCount
60935      * @type Boolean
60936      */
60937     calculateCategoryCount: false,
60938
60939     // @private creates an array of labels to be used when rendering.
60940     setLabels: function() {
60941         var store = this.chart.store,
60942             fields = this.fields,
60943             ln = fields.length,
60944             i;
60945
60946         this.labels = [];
60947         store.each(function(record) {
60948             for (i = 0; i < ln; i++) {
60949                 this.labels.push(record.get(fields[i]));
60950             }
60951         }, this);
60952     },
60953
60954     // @private calculates labels positions and marker positions for rendering.
60955     applyData: function() {
60956         this.callParent();
60957         this.setLabels();
60958         var count = this.chart.store.getCount();
60959         return {
60960             from: 0,
60961             to: count,
60962             power: 1,
60963             step: 1,
60964             steps: count - 1
60965         };
60966     }
60967 });
60968
60969 /**
60970  * @class Ext.chart.axis.Gauge
60971  * @extends Ext.chart.axis.Abstract
60972  *
60973  * Gauge Axis is the axis to be used with a Gauge series. The Gauge axis
60974  * displays numeric data from an interval defined by the `minimum`, `maximum` and
60975  * `step` configuration properties. The placement of the numeric data can be changed
60976  * by altering the `margin` option that is set to `10` by default.
60977  *
60978  * A possible configuration for this axis would look like:
60979  *
60980             axes: [{
60981                 type: 'gauge',
60982                 position: 'gauge',
60983                 minimum: 0,
60984                 maximum: 100,
60985                 steps: 10,
60986                 margin: 7
60987             }],
60988  * 
60989  */
60990 Ext.define('Ext.chart.axis.Gauge', {
60991
60992     /* Begin Definitions */
60993
60994     extend: 'Ext.chart.axis.Abstract',
60995
60996     /* End Definitions */
60997     
60998     /**
60999      * @cfg {Number} minimum (required) the minimum value of the interval to be displayed in the axis.
61000      */
61001
61002     /**
61003      * @cfg {Number} maximum (required) the maximum value of the interval to be displayed in the axis.
61004      */
61005
61006     /**
61007      * @cfg {Number} steps (required) the number of steps and tick marks to add to the interval.
61008      */
61009
61010     /**
61011      * @cfg {Number} margin (optional) the offset positioning of the tick marks and labels in pixels. Default's 10.
61012      */
61013
61014     position: 'gauge',
61015
61016     alias: 'axis.gauge',
61017
61018     drawAxis: function(init) {
61019         var chart = this.chart,
61020             surface = chart.surface,
61021             bbox = chart.chartBBox,
61022             centerX = bbox.x + (bbox.width / 2),
61023             centerY = bbox.y + bbox.height,
61024             margin = this.margin || 10,
61025             rho = Math.min(bbox.width, 2 * bbox.height) /2 + margin,
61026             sprites = [], sprite,
61027             steps = this.steps,
61028             i, pi = Math.PI,
61029             cos = Math.cos,
61030             sin = Math.sin;
61031
61032         if (this.sprites && !chart.resizing) {
61033             this.drawLabel();
61034             return;
61035         }
61036
61037         if (this.margin >= 0) {
61038             if (!this.sprites) {
61039                 //draw circles
61040                 for (i = 0; i <= steps; i++) {
61041                     sprite = surface.add({
61042                         type: 'path',
61043                         path: ['M', centerX + (rho - margin) * cos(i / steps * pi - pi),
61044                                     centerY + (rho - margin) * sin(i / steps * pi - pi),
61045                                     'L', centerX + rho * cos(i / steps * pi - pi),
61046                                     centerY + rho * sin(i / steps * pi - pi), 'Z'],
61047                         stroke: '#ccc'
61048                     });
61049                     sprite.setAttributes({
61050                         hidden: false
61051                     }, true);
61052                     sprites.push(sprite);
61053                 }
61054             } else {
61055                 sprites = this.sprites;
61056                 //draw circles
61057                 for (i = 0; i <= steps; i++) {
61058                     sprites[i].setAttributes({
61059                         path: ['M', centerX + (rho - margin) * cos(i / steps * pi - pi),
61060                                     centerY + (rho - margin) * sin(i / steps * pi - pi),
61061                                'L', centerX + rho * cos(i / steps * pi - pi),
61062                                     centerY + rho * sin(i / steps * pi - pi), 'Z'],
61063                         stroke: '#ccc'
61064                     }, true);
61065                 }
61066             }
61067         }
61068         this.sprites = sprites;
61069         this.drawLabel();
61070         if (this.title) {
61071             this.drawTitle();
61072         }
61073     },
61074     
61075     drawTitle: function() {
61076         var me = this,
61077             chart = me.chart,
61078             surface = chart.surface,
61079             bbox = chart.chartBBox,
61080             labelSprite = me.titleSprite,
61081             labelBBox;
61082         
61083         if (!labelSprite) {
61084             me.titleSprite = labelSprite = surface.add({
61085                 type: 'text',
61086                 zIndex: 2
61087             });    
61088         }
61089         labelSprite.setAttributes(Ext.apply({
61090             text: me.title
61091         }, me.label || {}), true);
61092         labelBBox = labelSprite.getBBox();
61093         labelSprite.setAttributes({
61094             x: bbox.x + (bbox.width / 2) - (labelBBox.width / 2),
61095             y: bbox.y + bbox.height - (labelBBox.height / 2) - 4
61096         }, true);
61097     },
61098
61099     /**
61100      * Updates the {@link #title} of this axis.
61101      * @param {String} title
61102      */
61103     setTitle: function(title) {
61104         this.title = title;
61105         this.drawTitle();
61106     },
61107
61108     drawLabel: function() {
61109         var chart = this.chart,
61110             surface = chart.surface,
61111             bbox = chart.chartBBox,
61112             centerX = bbox.x + (bbox.width / 2),
61113             centerY = bbox.y + bbox.height,
61114             margin = this.margin || 10,
61115             rho = Math.min(bbox.width, 2 * bbox.height) /2 + 2 * margin,
61116             round = Math.round,
61117             labelArray = [], label,
61118             maxValue = this.maximum || 0,
61119             steps = this.steps, i = 0,
61120             adjY,
61121             pi = Math.PI,
61122             cos = Math.cos,
61123             sin = Math.sin,
61124             labelConf = this.label,
61125             renderer = labelConf.renderer || function(v) { return v; };
61126
61127         if (!this.labelArray) {
61128             //draw scale
61129             for (i = 0; i <= steps; i++) {
61130                 // TODO Adjust for height of text / 2 instead
61131                 adjY = (i === 0 || i === steps) ? 7 : 0;
61132                 label = surface.add({
61133                     type: 'text',
61134                     text: renderer(round(i / steps * maxValue)),
61135                     x: centerX + rho * cos(i / steps * pi - pi),
61136                     y: centerY + rho * sin(i / steps * pi - pi) - adjY,
61137                     'text-anchor': 'middle',
61138                     'stroke-width': 0.2,
61139                     zIndex: 10,
61140                     stroke: '#333'
61141                 });
61142                 label.setAttributes({
61143                     hidden: false
61144                 }, true);
61145                 labelArray.push(label);
61146             }
61147         }
61148         else {
61149             labelArray = this.labelArray;
61150             //draw values
61151             for (i = 0; i <= steps; i++) {
61152                 // TODO Adjust for height of text / 2 instead
61153                 adjY = (i === 0 || i === steps) ? 7 : 0;
61154                 labelArray[i].setAttributes({
61155                     text: renderer(round(i / steps * maxValue)),
61156                     x: centerX + rho * cos(i / steps * pi - pi),
61157                     y: centerY + rho * sin(i / steps * pi - pi) - adjY
61158                 }, true);
61159             }
61160         }
61161         this.labelArray = labelArray;
61162     }
61163 });
61164 /**
61165  * @class Ext.chart.axis.Numeric
61166  * @extends Ext.chart.axis.Axis
61167  *
61168  * An axis to handle numeric values. This axis is used for quantitative data as
61169  * opposed to the category axis. You can set mininum and maximum values to the
61170  * axis so that the values are bound to that. If no values are set, then the
61171  * scale will auto-adjust to the values.
61172  * {@img Ext.chart.axis.Numeric/Ext.chart.axis.Numeric.png Ext.chart.axis.Numeric chart axis}
61173  * For example:
61174
61175     <pre><code>
61176    var store = Ext.create('Ext.data.JsonStore', {
61177         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
61178         data: [
61179             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
61180             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
61181             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
61182             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
61183             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}                                                
61184         ]
61185     });
61186     
61187     Ext.create('Ext.chart.Chart', {
61188         renderTo: Ext.getBody(),
61189         width: 500,
61190         height: 300,
61191         store: store,
61192         axes: [{
61193             type: 'Numeric',
61194             grid: true,
61195             position: 'left',
61196             fields: ['data1', 'data2', 'data3', 'data4', 'data5'],
61197             title: 'Sample Values',
61198             grid: {
61199                 odd: {
61200                     opacity: 1,
61201                     fill: '#ddd',
61202                     stroke: '#bbb',
61203                     'stroke-width': 1
61204                 }
61205             },
61206             minimum: 0,
61207             adjustMinimumByMajorUnit: 0
61208         }, {
61209             type: 'Category',
61210             position: 'bottom',
61211             fields: ['name'],
61212             title: 'Sample Metrics',
61213             grid: true,
61214             label: {
61215                 rotate: {
61216                     degrees: 315
61217                 }
61218             }
61219         }],
61220         series: [{
61221             type: 'area',
61222             highlight: false,
61223             axis: 'left',
61224             xField: 'name',
61225             yField: ['data1', 'data2', 'data3', 'data4', 'data5'],
61226             style: {
61227                 opacity: 0.93
61228             }
61229         }]
61230     });
61231     </code></pre>
61232
61233  *
61234  * In this example we create an axis of Numeric type. We set a minimum value so that
61235  * even if all series have values greater than zero, the grid starts at zero. We bind
61236  * the axis onto the left part of the surface by setting <em>position</em> to <em>left</em>.
61237  * We bind three different store fields to this axis by setting <em>fields</em> to an array.
61238  * We set the title of the axis to <em>Number of Hits</em> by using the <em>title</em> property.
61239  * We use a <em>grid</em> configuration to set odd background rows to a certain style and even rows
61240  * to be transparent/ignored.
61241  *
61242  *
61243  * @constructor
61244  */
61245 Ext.define('Ext.chart.axis.Numeric', {
61246
61247     /* Begin Definitions */
61248
61249     extend: 'Ext.chart.axis.Axis',
61250
61251     alternateClassName: 'Ext.chart.NumericAxis',
61252
61253     /* End Definitions */
61254
61255     type: 'numeric',
61256
61257     alias: 'axis.numeric',
61258
61259     constructor: function(config) {
61260         var me = this, label, f;
61261         me.callParent([config]);
61262         label = me.label;
61263         if (me.roundToDecimal === false) {
61264             return;
61265         }
61266         if (label.renderer) {
61267             f = label.renderer;
61268             label.renderer = function(v) {
61269                 return me.roundToDecimal( f(v), me.decimals );
61270             };
61271         } else {
61272             label.renderer = function(v) {
61273                 return me.roundToDecimal(v, me.decimals);
61274             };
61275         }
61276     },
61277     
61278     roundToDecimal: function(v, dec) {
61279         var val = Math.pow(10, dec || 0);
61280         return ((v * val) >> 0) / val;
61281     },
61282     
61283     /**
61284      * The minimum value drawn by the axis. If not set explicitly, the axis
61285      * minimum will be calculated automatically.
61286      *
61287      * @property minimum
61288      * @type Number
61289      */
61290     minimum: NaN,
61291
61292     /**
61293      * The maximum value drawn by the axis. If not set explicitly, the axis
61294      * maximum will be calculated automatically.
61295      *
61296      * @property maximum
61297      * @type Number
61298      */
61299     maximum: NaN,
61300
61301     /**
61302      * The number of decimals to round the value to.
61303      * Default's 2.
61304      *
61305      * @property decimals
61306      * @type Number
61307      */
61308     decimals: 2,
61309
61310     /**
61311      * The scaling algorithm to use on this axis. May be "linear" or
61312      * "logarithmic".
61313      *
61314      * @property scale
61315      * @type String
61316      */
61317     scale: "linear",
61318
61319     /**
61320      * Indicates the position of the axis relative to the chart
61321      *
61322      * @property position
61323      * @type String
61324      */
61325     position: 'left',
61326
61327     /**
61328      * Indicates whether to extend maximum beyond data's maximum to the nearest
61329      * majorUnit.
61330      *
61331      * @property adjustMaximumByMajorUnit
61332      * @type Boolean
61333      */
61334     adjustMaximumByMajorUnit: false,
61335
61336     /**
61337      * Indicates whether to extend the minimum beyond data's minimum to the
61338      * nearest majorUnit.
61339      *
61340      * @property adjustMinimumByMajorUnit
61341      * @type Boolean
61342      */
61343     adjustMinimumByMajorUnit: false,
61344
61345     // @private apply data.
61346     applyData: function() {
61347         this.callParent();
61348         return this.calcEnds();
61349     }
61350 });
61351
61352 /**
61353  * @class Ext.chart.axis.Radial
61354  * @extends Ext.chart.axis.Abstract
61355  * @ignore
61356  */
61357 Ext.define('Ext.chart.axis.Radial', {
61358
61359     /* Begin Definitions */
61360
61361     extend: 'Ext.chart.axis.Abstract',
61362
61363     /* End Definitions */
61364
61365     position: 'radial',
61366
61367     alias: 'axis.radial',
61368
61369     drawAxis: function(init) {
61370         var chart = this.chart,
61371             surface = chart.surface,
61372             bbox = chart.chartBBox,
61373             store = chart.store,
61374             l = store.getCount(),
61375             centerX = bbox.x + (bbox.width / 2),
61376             centerY = bbox.y + (bbox.height / 2),
61377             rho = Math.min(bbox.width, bbox.height) /2,
61378             sprites = [], sprite,
61379             steps = this.steps,
61380             i, j, pi2 = Math.PI * 2,
61381             cos = Math.cos, sin = Math.sin;
61382
61383         if (this.sprites && !chart.resizing) {
61384             this.drawLabel();
61385             return;
61386         }
61387
61388         if (!this.sprites) {
61389             //draw circles
61390             for (i = 1; i <= steps; i++) {
61391                 sprite = surface.add({
61392                     type: 'circle',
61393                     x: centerX,
61394                     y: centerY,
61395                     radius: Math.max(rho * i / steps, 0),
61396                     stroke: '#ccc'
61397                 });
61398                 sprite.setAttributes({
61399                     hidden: false
61400                 }, true);
61401                 sprites.push(sprite);
61402             }
61403             //draw lines
61404             store.each(function(rec, i) {
61405                 sprite = surface.add({
61406                     type: 'path',
61407                     path: ['M', centerX, centerY, 'L', centerX + rho * cos(i / l * pi2), centerY + rho * sin(i / l * pi2), 'Z'],
61408                     stroke: '#ccc'
61409                 });
61410                 sprite.setAttributes({
61411                     hidden: false
61412                 }, true);
61413                 sprites.push(sprite);
61414             });
61415         } else {
61416             sprites = this.sprites;
61417             //draw circles
61418             for (i = 0; i < steps; i++) {
61419                 sprites[i].setAttributes({
61420                     x: centerX,
61421                     y: centerY,
61422                     radius: Math.max(rho * (i + 1) / steps, 0),
61423                     stroke: '#ccc'
61424                 }, true);
61425             }
61426             //draw lines
61427             store.each(function(rec, j) {
61428                 sprites[i + j].setAttributes({
61429                     path: ['M', centerX, centerY, 'L', centerX + rho * cos(j / l * pi2), centerY + rho * sin(j / l * pi2), 'Z'],
61430                     stroke: '#ccc'
61431                 }, true);
61432             });
61433         }
61434         this.sprites = sprites;
61435
61436         this.drawLabel();
61437     },
61438
61439     drawLabel: function() {
61440         var chart = this.chart,
61441             surface = chart.surface,
61442             bbox = chart.chartBBox,
61443             store = chart.store,
61444             centerX = bbox.x + (bbox.width / 2),
61445             centerY = bbox.y + (bbox.height / 2),
61446             rho = Math.min(bbox.width, bbox.height) /2,
61447             max = Math.max, round = Math.round,
61448             labelArray = [], label,
61449             fields = [], nfields,
61450             categories = [], xField,
61451             aggregate = !this.maximum,
61452             maxValue = this.maximum || 0,
61453             steps = this.steps, i = 0, j, dx, dy,
61454             pi2 = Math.PI * 2,
61455             cos = Math.cos, sin = Math.sin,
61456             display = this.label.display,
61457             draw = display !== 'none',
61458             margin = 10;
61459
61460         if (!draw) {
61461             return;
61462         }
61463
61464         //get all rendered fields
61465         chart.series.each(function(series) {
61466             fields.push(series.yField);
61467             xField = series.xField;
61468         });
61469         
61470         //get maxValue to interpolate
61471         store.each(function(record, i) {
61472             if (aggregate) {
61473                 for (i = 0, nfields = fields.length; i < nfields; i++) {
61474                     maxValue = max(+record.get(fields[i]), maxValue);
61475                 }
61476             }
61477             categories.push(record.get(xField));
61478         });
61479         if (!this.labelArray) {
61480             if (display != 'categories') {
61481                 //draw scale
61482                 for (i = 1; i <= steps; i++) {
61483                     label = surface.add({
61484                         type: 'text',
61485                         text: round(i / steps * maxValue),
61486                         x: centerX,
61487                         y: centerY - rho * i / steps,
61488                         'text-anchor': 'middle',
61489                         'stroke-width': 0.1,
61490                         stroke: '#333'
61491                     });
61492                     label.setAttributes({
61493                         hidden: false
61494                     }, true);
61495                     labelArray.push(label);
61496                 }
61497             }
61498             if (display != 'scale') {
61499                 //draw text
61500                 for (j = 0, steps = categories.length; j < steps; j++) {
61501                     dx = cos(j / steps * pi2) * (rho + margin);
61502                     dy = sin(j / steps * pi2) * (rho + margin);
61503                     label = surface.add({
61504                         type: 'text',
61505                         text: categories[j],
61506                         x: centerX + dx,
61507                         y: centerY + dy,
61508                         'text-anchor': dx * dx <= 0.001? 'middle' : (dx < 0? 'end' : 'start')
61509                     });
61510                     label.setAttributes({
61511                         hidden: false
61512                     }, true);
61513                     labelArray.push(label);
61514                 }
61515             }
61516         }
61517         else {
61518             labelArray = this.labelArray;
61519             if (display != 'categories') {
61520                 //draw values
61521                 for (i = 0; i < steps; i++) {
61522                     labelArray[i].setAttributes({
61523                         text: round((i + 1) / steps * maxValue),
61524                         x: centerX,
61525                         y: centerY - rho * (i + 1) / steps,
61526                         'text-anchor': 'middle',
61527                         'stroke-width': 0.1,
61528                         stroke: '#333'
61529                     }, true);
61530                 }
61531             }
61532             if (display != 'scale') {
61533                 //draw text
61534                 for (j = 0, steps = categories.length; j < steps; j++) {
61535                     dx = cos(j / steps * pi2) * (rho + margin);
61536                     dy = sin(j / steps * pi2) * (rho + margin);
61537                     if (labelArray[i + j]) {
61538                         labelArray[i + j].setAttributes({
61539                             type: 'text',
61540                             text: categories[j],
61541                             x: centerX + dx,
61542                             y: centerY + dy,
61543                             'text-anchor': dx * dx <= 0.001? 'middle' : (dx < 0? 'end' : 'start')
61544                         }, true);
61545                     }
61546                 }
61547             }
61548         }
61549         this.labelArray = labelArray;
61550     }
61551 });
61552 /**
61553  * @author Ed Spencer
61554  * @class Ext.data.AbstractStore
61555  *
61556  * <p>AbstractStore is a superclass of {@link Ext.data.Store} and {@link Ext.data.TreeStore}. It's never used directly,
61557  * but offers a set of methods used by both of those subclasses.</p>
61558  * 
61559  * <p>We've left it here in the docs for reference purposes, but unless you need to make a whole new type of Store, what
61560  * you're probably looking for is {@link Ext.data.Store}. If you're still interested, here's a brief description of what 
61561  * AbstractStore is and is not.</p>
61562  * 
61563  * <p>AbstractStore provides the basic configuration for anything that can be considered a Store. It expects to be 
61564  * given a {@link Ext.data.Model Model} that represents the type of data in the Store. It also expects to be given a 
61565  * {@link Ext.data.proxy.Proxy Proxy} that handles the loading of data into the Store.</p>
61566  * 
61567  * <p>AbstractStore provides a few helpful methods such as {@link #load} and {@link #sync}, which load and save data
61568  * respectively, passing the requests through the configured {@link #proxy}. Both built-in Store subclasses add extra
61569  * behavior to each of these functions. Note also that each AbstractStore subclass has its own way of storing data - 
61570  * in {@link Ext.data.Store} the data is saved as a flat {@link Ext.util.MixedCollection MixedCollection}, whereas in
61571  * {@link Ext.data.TreeStore TreeStore} we use a {@link Ext.data.Tree} to maintain the data's hierarchy.</p>
61572  * 
61573  * TODO: Update these docs to explain about the sortable and filterable mixins.
61574  * <p>Finally, AbstractStore provides an API for sorting and filtering data via its {@link #sorters} and {@link #filters}
61575  * {@link Ext.util.MixedCollection MixedCollections}. Although this functionality is provided by AbstractStore, there's a
61576  * good description of how to use it in the introduction of {@link Ext.data.Store}.
61577  * 
61578  */
61579 Ext.define('Ext.data.AbstractStore', {
61580     requires: ['Ext.util.MixedCollection', 'Ext.data.Operation', 'Ext.util.Filter'],
61581     
61582     mixins: {
61583         observable: 'Ext.util.Observable',
61584         sortable: 'Ext.util.Sortable'
61585     },
61586     
61587     statics: {
61588         create: function(store){
61589             if (!store.isStore) {
61590                 if (!store.type) {
61591                     store.type = 'store';
61592                 }
61593                 store = Ext.createByAlias('store.' + store.type, store);
61594             }
61595             return store;
61596         }    
61597     },
61598     
61599     remoteSort  : false,
61600     remoteFilter: false,
61601
61602     /**
61603      * @cfg {String/Ext.data.proxy.Proxy/Object} proxy The Proxy to use for this Store. This can be either a string, a config
61604      * object or a Proxy instance - see {@link #setProxy} for details.
61605      */
61606
61607     /**
61608      * @cfg {Boolean/Object} autoLoad If data is not specified, and if autoLoad is true or an Object, this store's load method
61609      * is automatically called after creation. If the value of autoLoad is an Object, this Object will be passed to the store's
61610      * load method. Defaults to false.
61611      */
61612     autoLoad: false,
61613
61614     /**
61615      * @cfg {Boolean} autoSync True to automatically sync the Store with its Proxy after every edit to one of its Records.
61616      * Defaults to false.
61617      */
61618     autoSync: false,
61619
61620     /**
61621      * Sets the updating behavior based on batch synchronization. 'operation' (the default) will update the Store's
61622      * internal representation of the data after each operation of the batch has completed, 'complete' will wait until
61623      * the entire batch has been completed before updating the Store's data. 'complete' is a good choice for local
61624      * storage proxies, 'operation' is better for remote proxies, where there is a comparatively high latency.
61625      * @property batchUpdateMode
61626      * @type String
61627      */
61628     batchUpdateMode: 'operation',
61629
61630     /**
61631      * If true, any filters attached to this Store will be run after loading data, before the datachanged event is fired.
61632      * Defaults to true, ignored if {@link #remoteFilter} is true
61633      * @property filterOnLoad
61634      * @type Boolean
61635      */
61636     filterOnLoad: true,
61637
61638     /**
61639      * If true, any sorters attached to this Store will be run after loading data, before the datachanged event is fired.
61640      * Defaults to true, igored if {@link #remoteSort} is true
61641      * @property sortOnLoad
61642      * @type Boolean
61643      */
61644     sortOnLoad: true,
61645
61646     /**
61647      * True if a model was created implicitly for this Store. This happens if a fields array is passed to the Store's constructor
61648      * instead of a model constructor or name.
61649      * @property implicitModel
61650      * @type Boolean
61651      * @private
61652      */
61653     implicitModel: false,
61654
61655     /**
61656      * The string type of the Proxy to create if none is specified. This defaults to creating a {@link Ext.data.proxy.Memory memory proxy}.
61657      * @property defaultProxyType
61658      * @type String
61659      */
61660     defaultProxyType: 'memory',
61661
61662     /**
61663      * True if the Store has already been destroyed via {@link #destroyStore}. If this is true, the reference to Store should be deleted
61664      * as it will not function correctly any more.
61665      * @property isDestroyed
61666      * @type Boolean
61667      */
61668     isDestroyed: false,
61669
61670     isStore: true,
61671
61672     /**
61673      * @cfg {String} storeId Optional unique identifier for this store. If present, this Store will be registered with 
61674      * the {@link Ext.data.StoreManager}, making it easy to reuse elsewhere. Defaults to undefined.
61675      */
61676     
61677     /**
61678      * @cfg {Array} fields
61679      * This may be used in place of specifying a {@link #model} configuration. The fields should be a 
61680      * set of {@link Ext.data.Field} configuration objects. The store will automatically create a {@link Ext.data.Model}
61681      * with these fields. In general this configuration option should be avoided, it exists for the purposes of
61682      * backwards compatibility. For anything more complicated, such as specifying a particular id property or
61683      * assocations, a {@link Ext.data.Model} should be defined and specified for the {@link #model} config.
61684      */
61685
61686     sortRoot: 'data',
61687     
61688     //documented above
61689     constructor: function(config) {
61690         var me = this;
61691         
61692         me.addEvents(
61693             /**
61694              * @event add
61695              * Fired when a Model instance has been added to this Store
61696              * @param {Ext.data.Store} store The store
61697              * @param {Array} records The Model instances that were added
61698              * @param {Number} index The index at which the instances were inserted
61699              */
61700             'add',
61701
61702             /**
61703              * @event remove
61704              * Fired when a Model instance has been removed from this Store
61705              * @param {Ext.data.Store} store The Store object
61706              * @param {Ext.data.Model} record The record that was removed
61707              * @param {Number} index The index of the record that was removed
61708              */
61709             'remove',
61710             
61711             /**
61712              * @event update
61713              * Fires when a Record has been updated
61714              * @param {Store} this
61715              * @param {Ext.data.Model} record The Model instance that was updated
61716              * @param {String} operation The update operation being performed. Value may be one of:
61717              * <pre><code>
61718                Ext.data.Model.EDIT
61719                Ext.data.Model.REJECT
61720                Ext.data.Model.COMMIT
61721              * </code></pre>
61722              */
61723             'update',
61724
61725             /**
61726              * @event datachanged
61727              * Fires whenever the records in the Store have changed in some way - this could include adding or removing records,
61728              * or updating the data in existing records
61729              * @param {Ext.data.Store} this The data store
61730              */
61731             'datachanged',
61732
61733             /**
61734              * @event beforeload
61735              * Event description
61736              * @param {Ext.data.Store} store This Store
61737              * @param {Ext.data.Operation} operation The Ext.data.Operation object that will be passed to the Proxy to load the Store
61738              */
61739             'beforeload',
61740
61741             /**
61742              * @event load
61743              * Fires whenever the store reads data from a remote data source.
61744              * @param {Ext.data.Store} this
61745              * @param {Array} records An array of records
61746              * @param {Boolean} successful True if the operation was successful.
61747              */
61748             'load',
61749
61750             /**
61751              * @event beforesync
61752              * Called before a call to {@link #sync} is executed. Return false from any listener to cancel the synv
61753              * @param {Object} options Hash of all records to be synchronized, broken down into create, update and destroy
61754              */
61755             'beforesync',
61756             /**
61757              * @event clear
61758              * Fired after the {@link #removeAll} method is called.
61759              * @param {Ext.data.Store} this
61760              */
61761             'clear'
61762         );
61763         
61764         Ext.apply(me, config);
61765
61766         /**
61767          * Temporary cache in which removed model instances are kept until successfully synchronised with a Proxy,
61768          * at which point this is cleared.
61769          * @private
61770          * @property removed
61771          * @type Array
61772          */
61773         me.removed = [];
61774
61775         me.mixins.observable.constructor.apply(me, arguments);
61776         me.model = Ext.ModelManager.getModel(config.model || me.model);
61777
61778         /**
61779          * @property modelDefaults
61780          * @type Object
61781          * @private
61782          * A set of default values to be applied to every model instance added via {@link #insert} or created via {@link #create}.
61783          * This is used internally by associations to set foreign keys and other fields. See the Association classes source code
61784          * for examples. This should not need to be used by application developers.
61785          */
61786         Ext.applyIf(me, {
61787             modelDefaults: {}
61788         });
61789
61790         //Supports the 3.x style of simply passing an array of fields to the store, implicitly creating a model
61791         if (!me.model && me.fields) {
61792             me.model = Ext.define('Ext.data.Store.ImplicitModel-' + (me.storeId || Ext.id()), {
61793                 extend: 'Ext.data.Model',
61794                 fields: me.fields,
61795                 proxy: me.proxy || me.defaultProxyType
61796             });
61797
61798             delete me.fields;
61799
61800             me.implicitModel = true;
61801         }
61802
61803         //ensures that the Proxy is instantiated correctly
61804         me.setProxy(config.proxy || me.proxy || me.model.getProxy());
61805
61806         if (me.id && !me.storeId) {
61807             me.storeId = me.id;
61808             delete me.id;
61809         }
61810
61811         if (me.storeId) {
61812             Ext.data.StoreManager.register(me);
61813         }
61814         
61815         me.mixins.sortable.initSortable.call(me);        
61816         
61817         /**
61818          * The collection of {@link Ext.util.Filter Filters} currently applied to this Store
61819          * @property filters
61820          * @type Ext.util.MixedCollection
61821          */
61822         me.filters = Ext.create('Ext.util.MixedCollection');
61823         me.filters.addAll(me.decodeFilters(config.filters));
61824     },
61825
61826     /**
61827      * Sets the Store's Proxy by string, config object or Proxy instance
61828      * @param {String|Object|Ext.data.proxy.Proxy} proxy The new Proxy, which can be either a type string, a configuration object
61829      * or an Ext.data.proxy.Proxy instance
61830      * @return {Ext.data.proxy.Proxy} The attached Proxy object
61831      */
61832     setProxy: function(proxy) {
61833         var me = this;
61834         
61835         if (proxy instanceof Ext.data.proxy.Proxy) {
61836             proxy.setModel(me.model);
61837         } else {
61838             if (Ext.isString(proxy)) {
61839                 proxy = {
61840                     type: proxy    
61841                 };
61842             }
61843             Ext.applyIf(proxy, {
61844                 model: me.model
61845             });
61846             
61847             proxy = Ext.createByAlias('proxy.' + proxy.type, proxy);
61848         }
61849         
61850         me.proxy = proxy;
61851         
61852         return me.proxy;
61853     },
61854
61855     /**
61856      * Returns the proxy currently attached to this proxy instance
61857      * @return {Ext.data.proxy.Proxy} The Proxy instance
61858      */
61859     getProxy: function() {
61860         return this.proxy;
61861     },
61862
61863     //saves any phantom records
61864     create: function(data, options) {
61865         var me = this,
61866             instance = Ext.ModelManager.create(Ext.applyIf(data, me.modelDefaults), me.model.modelName),
61867             operation;
61868         
61869         options = options || {};
61870
61871         Ext.applyIf(options, {
61872             action : 'create',
61873             records: [instance]
61874         });
61875
61876         operation = Ext.create('Ext.data.Operation', options);
61877
61878         me.proxy.create(operation, me.onProxyWrite, me);
61879         
61880         return instance;
61881     },
61882
61883     read: function() {
61884         return this.load.apply(this, arguments);
61885     },
61886
61887     onProxyRead: Ext.emptyFn,
61888
61889     update: function(options) {
61890         var me = this,
61891             operation;
61892         options = options || {};
61893
61894         Ext.applyIf(options, {
61895             action : 'update',
61896             records: me.getUpdatedRecords()
61897         });
61898
61899         operation = Ext.create('Ext.data.Operation', options);
61900
61901         return me.proxy.update(operation, me.onProxyWrite, me);
61902     },
61903
61904     /**
61905      * @private
61906      * Callback for any write Operation over the Proxy. Updates the Store's MixedCollection to reflect
61907      * the updates provided by the Proxy
61908      */
61909     onProxyWrite: function(operation) {
61910         var me = this,
61911             success = operation.wasSuccessful(),
61912             records = operation.getRecords();
61913
61914         switch (operation.action) {
61915             case 'create':
61916                 me.onCreateRecords(records, operation, success);
61917                 break;
61918             case 'update':
61919                 me.onUpdateRecords(records, operation, success);
61920                 break;
61921             case 'destroy':
61922                 me.onDestroyRecords(records, operation, success);
61923                 break;
61924         }
61925
61926         if (success) {
61927             me.fireEvent('write', me, operation);
61928             me.fireEvent('datachanged', me);
61929         }
61930         //this is a callback that would have been passed to the 'create', 'update' or 'destroy' function and is optional
61931         Ext.callback(operation.callback, operation.scope || me, [records, operation, success]);
61932     },
61933
61934
61935     //tells the attached proxy to destroy the given records
61936     destroy: function(options) {
61937         var me = this,
61938             operation;
61939             
61940         options = options || {};
61941
61942         Ext.applyIf(options, {
61943             action : 'destroy',
61944             records: me.getRemovedRecords()
61945         });
61946
61947         operation = Ext.create('Ext.data.Operation', options);
61948
61949         return me.proxy.destroy(operation, me.onProxyWrite, me);
61950     },
61951
61952     /**
61953      * @private
61954      * Attached as the 'operationcomplete' event listener to a proxy's Batch object. By default just calls through
61955      * to onProxyWrite.
61956      */
61957     onBatchOperationComplete: function(batch, operation) {
61958         return this.onProxyWrite(operation);
61959     },
61960
61961     /**
61962      * @private
61963      * Attached as the 'complete' event listener to a proxy's Batch object. Iterates over the batch operations
61964      * and updates the Store's internal data MixedCollection.
61965      */
61966     onBatchComplete: function(batch, operation) {
61967         var me = this,
61968             operations = batch.operations,
61969             length = operations.length,
61970             i;
61971
61972         me.suspendEvents();
61973
61974         for (i = 0; i < length; i++) {
61975             me.onProxyWrite(operations[i]);
61976         }
61977
61978         me.resumeEvents();
61979
61980         me.fireEvent('datachanged', me);
61981     },
61982
61983     onBatchException: function(batch, operation) {
61984         // //decide what to do... could continue with the next operation
61985         // batch.start();
61986         //
61987         // //or retry the last operation
61988         // batch.retry();
61989     },
61990
61991     /**
61992      * @private
61993      * Filter function for new records.
61994      */
61995     filterNew: function(item) {
61996         // only want phantom records that are valid
61997         return item.phantom === true && item.isValid();
61998     },
61999
62000     /**
62001      * Returns all Model instances that are either currently a phantom (e.g. have no id), or have an ID but have not
62002      * yet been saved on this Store (this happens when adding a non-phantom record from another Store into this one)
62003      * @return {Array} The Model instances
62004      */
62005     getNewRecords: function() {
62006         return [];
62007     },
62008
62009     /**
62010      * Returns all Model instances that have been updated in the Store but not yet synchronized with the Proxy
62011      * @return {Array} The updated Model instances
62012      */
62013     getUpdatedRecords: function() {
62014         return [];
62015     },
62016
62017     /**
62018      * @private
62019      * Filter function for updated records.
62020      */
62021     filterUpdated: function(item) {
62022         // only want dirty records, not phantoms that are valid
62023         return item.dirty === true && item.phantom !== true && item.isValid();
62024     },
62025
62026     //returns any records that have been removed from the store but not yet destroyed on the proxy
62027     getRemovedRecords: function() {
62028         return this.removed;
62029     },
62030
62031     filter: function(filters, value) {
62032
62033     },
62034
62035     /**
62036      * @private
62037      * Normalizes an array of filter objects, ensuring that they are all Ext.util.Filter instances
62038      * @param {Array} filters The filters array
62039      * @return {Array} Array of Ext.util.Filter objects
62040      */
62041     decodeFilters: function(filters) {
62042         if (!Ext.isArray(filters)) {
62043             if (filters === undefined) {
62044                 filters = [];
62045             } else {
62046                 filters = [filters];
62047             }
62048         }
62049
62050         var length = filters.length,
62051             Filter = Ext.util.Filter,
62052             config, i;
62053
62054         for (i = 0; i < length; i++) {
62055             config = filters[i];
62056
62057             if (!(config instanceof Filter)) {
62058                 Ext.apply(config, {
62059                     root: 'data'
62060                 });
62061
62062                 //support for 3.x style filters where a function can be defined as 'fn'
62063                 if (config.fn) {
62064                     config.filterFn = config.fn;
62065                 }
62066
62067                 //support a function to be passed as a filter definition
62068                 if (typeof config == 'function') {
62069                     config = {
62070                         filterFn: config
62071                     };
62072                 }
62073
62074                 filters[i] = new Filter(config);
62075             }
62076         }
62077
62078         return filters;
62079     },
62080
62081     clearFilter: function(supressEvent) {
62082
62083     },
62084
62085     isFiltered: function() {
62086
62087     },
62088
62089     filterBy: function(fn, scope) {
62090
62091     },
62092     
62093     /**
62094      * Synchronizes the Store with its Proxy. This asks the Proxy to batch together any new, updated
62095      * and deleted records in the store, updating the Store's internal representation of the records
62096      * as each operation completes.
62097      */
62098     sync: function() {
62099         var me        = this,
62100             options   = {},
62101             toCreate  = me.getNewRecords(),
62102             toUpdate  = me.getUpdatedRecords(),
62103             toDestroy = me.getRemovedRecords(),
62104             needsSync = false;
62105
62106         if (toCreate.length > 0) {
62107             options.create = toCreate;
62108             needsSync = true;
62109         }
62110
62111         if (toUpdate.length > 0) {
62112             options.update = toUpdate;
62113             needsSync = true;
62114         }
62115
62116         if (toDestroy.length > 0) {
62117             options.destroy = toDestroy;
62118             needsSync = true;
62119         }
62120
62121         if (needsSync && me.fireEvent('beforesync', options) !== false) {
62122             me.proxy.batch(options, me.getBatchListeners());
62123         }
62124     },
62125
62126
62127     /**
62128      * @private
62129      * Returns an object which is passed in as the listeners argument to proxy.batch inside this.sync.
62130      * This is broken out into a separate function to allow for customisation of the listeners
62131      * @return {Object} The listeners object
62132      */
62133     getBatchListeners: function() {
62134         var me = this,
62135             listeners = {
62136                 scope: me,
62137                 exception: me.onBatchException
62138             };
62139
62140         if (me.batchUpdateMode == 'operation') {
62141             listeners.operationcomplete = me.onBatchOperationComplete;
62142         } else {
62143             listeners.complete = me.onBatchComplete;
62144         }
62145
62146         return listeners;
62147     },
62148
62149     //deprecated, will be removed in 5.0
62150     save: function() {
62151         return this.sync.apply(this, arguments);
62152     },
62153
62154     /**
62155      * Loads the Store using its configured {@link #proxy}.
62156      * @param {Object} options Optional config object. This is passed into the {@link Ext.data.Operation Operation}
62157      * object that is created and then sent to the proxy's {@link Ext.data.proxy.Proxy#read} function
62158      */
62159     load: function(options) {
62160         var me = this,
62161             operation;
62162
62163         options = options || {};
62164
62165         Ext.applyIf(options, {
62166             action : 'read',
62167             filters: me.filters.items,
62168             sorters: me.getSorters()
62169         });
62170         
62171         operation = Ext.create('Ext.data.Operation', options);
62172
62173         if (me.fireEvent('beforeload', me, operation) !== false) {
62174             me.loading = true;
62175             me.proxy.read(operation, me.onProxyLoad, me);
62176         }
62177         
62178         return me;
62179     },
62180
62181     /**
62182      * @private
62183      * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to.
62184      * @param {Ext.data.Model} record The model instance that was edited
62185      */
62186     afterEdit : function(record) {
62187         var me = this;
62188         
62189         if (me.autoSync) {
62190             me.sync();
62191         }
62192         
62193         me.fireEvent('update', me, record, Ext.data.Model.EDIT);
62194     },
62195
62196     /**
62197      * @private
62198      * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to..
62199      * @param {Ext.data.Model} record The model instance that was edited
62200      */
62201     afterReject : function(record) {
62202         this.fireEvent('update', this, record, Ext.data.Model.REJECT);
62203     },
62204
62205     /**
62206      * @private
62207      * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to.
62208      * @param {Ext.data.Model} record The model instance that was edited
62209      */
62210     afterCommit : function(record) {
62211         this.fireEvent('update', this, record, Ext.data.Model.COMMIT);
62212     },
62213
62214     clearData: Ext.emptyFn,
62215
62216     destroyStore: function() {
62217         var me = this;
62218         
62219         if (!me.isDestroyed) {
62220             if (me.storeId) {
62221                 Ext.data.StoreManager.unregister(me);
62222             }
62223             me.clearData();
62224             me.data = null;
62225             me.tree = null;
62226             // Ext.destroy(this.proxy);
62227             me.reader = me.writer = null;
62228             me.clearListeners();
62229             me.isDestroyed = true;
62230
62231             if (me.implicitModel) {
62232                 Ext.destroy(me.model);
62233             }
62234         }
62235     },
62236     
62237     doSort: function(sorterFn) {
62238         var me = this;
62239         if (me.remoteSort) {
62240             //the load function will pick up the new sorters and request the sorted data from the proxy
62241             me.load();
62242         } else {
62243             me.data.sortBy(sorterFn);
62244             me.fireEvent('datachanged', me);
62245         }
62246     },
62247
62248     getCount: Ext.emptyFn,
62249
62250     getById: Ext.emptyFn,
62251     
62252     /**
62253      * Removes all records from the store. This method does a "fast remove",
62254      * individual remove events are not called. The {@link #clear} event is
62255      * fired upon completion.
62256      */
62257     removeAll: Ext.emptyFn,
62258     // individual substores should implement a "fast" remove
62259     // and fire a clear event afterwards
62260
62261     /**
62262      * Returns true if the Store is currently performing a load operation
62263      * @return {Boolean} True if the Store is currently loading
62264      */
62265     isLoading: function() {
62266         return this.loading;
62267      }
62268 });
62269
62270 /**
62271  * @class Ext.util.Grouper
62272  * @extends Ext.util.Sorter
62273  */
62274  
62275 Ext.define('Ext.util.Grouper', {
62276
62277     /* Begin Definitions */
62278
62279     extend: 'Ext.util.Sorter',
62280
62281     /* End Definitions */
62282
62283     /**
62284      * Function description
62285      * @param {Ext.data.Model} instance The Model instance
62286      * @return {String} The group string for this model
62287      */
62288     getGroupString: function(instance) {
62289         return instance.get(this.property);
62290     }
62291 });
62292 /**
62293  * @author Ed Spencer
62294  * @class Ext.data.Store
62295  * @extends Ext.data.AbstractStore
62296  *
62297  * <p>The Store class encapsulates a client side cache of {@link Ext.data.Model Model} objects. Stores load
62298  * data via a {@link Ext.data.proxy.Proxy Proxy}, and also provide functions for {@link #sort sorting},
62299  * {@link #filter filtering} and querying the {@link Ext.data.Model model} instances contained within it.</p>
62300  *
62301  * <p>Creating a Store is easy - we just tell it the Model and the Proxy to use to load and save its data:</p>
62302  *
62303 <pre><code>
62304 // Set up a {@link Ext.data.Model model} to use in our Store
62305 Ext.define('User', {
62306     extend: 'Ext.data.Model',
62307     fields: [
62308         {name: 'firstName', type: 'string'},
62309         {name: 'lastName',  type: 'string'},
62310         {name: 'age',       type: 'int'},
62311         {name: 'eyeColor',  type: 'string'}
62312     ]
62313 });
62314
62315 var myStore = new Ext.data.Store({
62316     model: 'User',
62317     proxy: {
62318         type: 'ajax',
62319         url : '/users.json',
62320         reader: {
62321             type: 'json',
62322             root: 'users'
62323         }
62324     },
62325     autoLoad: true
62326 });
62327 </code></pre>
62328
62329  * <p>In the example above we configured an AJAX proxy to load data from the url '/users.json'. We told our Proxy
62330  * to use a {@link Ext.data.reader.Json JsonReader} to parse the response from the server into Model object -
62331  * {@link Ext.data.reader.Json see the docs on JsonReader} for details.</p>
62332  *
62333  * <p><u>Inline data</u></p>
62334  *
62335  * <p>Stores can also load data inline. Internally, Store converts each of the objects we pass in as {@link #data}
62336  * into Model instances:</p>
62337  *
62338 <pre><code>
62339 new Ext.data.Store({
62340     model: 'User',
62341     data : [
62342         {firstName: 'Ed',    lastName: 'Spencer'},
62343         {firstName: 'Tommy', lastName: 'Maintz'},
62344         {firstName: 'Aaron', lastName: 'Conran'},
62345         {firstName: 'Jamie', lastName: 'Avins'}
62346     ]
62347 });
62348 </code></pre>
62349  *
62350  * <p>Loading inline data using the method above is great if the data is in the correct format already (e.g. it doesn't need
62351  * to be processed by a {@link Ext.data.reader.Reader reader}). If your inline data requires processing to decode the data structure,
62352  * use a {@link Ext.data.proxy.Memory MemoryProxy} instead (see the {@link Ext.data.proxy.Memory MemoryProxy} docs for an example).</p>
62353  *
62354  * <p>Additional data can also be loaded locally using {@link #add}.</p>
62355  *
62356  * <p><u>Loading Nested Data</u></p>
62357  *
62358  * <p>Applications often need to load sets of associated data - for example a CRM system might load a User and her Orders.
62359  * Instead of issuing an AJAX request for the User and a series of additional AJAX requests for each Order, we can load a nested dataset
62360  * and allow the Reader to automatically populate the associated models. Below is a brief example, see the {@link Ext.data.reader.Reader} intro
62361  * docs for a full explanation:</p>
62362  *
62363 <pre><code>
62364 var store = new Ext.data.Store({
62365     autoLoad: true,
62366     model: "User",
62367     proxy: {
62368         type: 'ajax',
62369         url : 'users.json',
62370         reader: {
62371             type: 'json',
62372             root: 'users'
62373         }
62374     }
62375 });
62376 </code></pre>
62377  *
62378  * <p>Which would consume a response like this:</p>
62379  *
62380 <pre><code>
62381 {
62382     "users": [
62383         {
62384             "id": 1,
62385             "name": "Ed",
62386             "orders": [
62387                 {
62388                     "id": 10,
62389                     "total": 10.76,
62390                     "status": "invoiced"
62391                 },
62392                 {
62393                     "id": 11,
62394                     "total": 13.45,
62395                     "status": "shipped"
62396                 }
62397             ]
62398         }
62399     ]
62400 }
62401 </code></pre>
62402  *
62403  * <p>See the {@link Ext.data.reader.Reader} intro docs for a full explanation.</p>
62404  *
62405  * <p><u>Filtering and Sorting</u></p>
62406  *
62407  * <p>Stores can be sorted and filtered - in both cases either remotely or locally. The {@link #sorters} and {@link #filters} are
62408  * held inside {@link Ext.util.MixedCollection MixedCollection} instances to make them easy to manage. Usually it is sufficient to
62409  * either just specify sorters and filters in the Store configuration or call {@link #sort} or {@link #filter}:
62410  *
62411 <pre><code>
62412 var store = new Ext.data.Store({
62413     model: 'User',
62414     sorters: [
62415         {
62416             property : 'age',
62417             direction: 'DESC'
62418         },
62419         {
62420             property : 'firstName',
62421             direction: 'ASC'
62422         }
62423     ],
62424
62425     filters: [
62426         {
62427             property: 'firstName',
62428             value   : /Ed/
62429         }
62430     ]
62431 });
62432 </code></pre>
62433  *
62434  * <p>The new Store will keep the configured sorters and filters in the MixedCollection instances mentioned above. By default, sorting
62435  * and filtering are both performed locally by the Store - see {@link #remoteSort} and {@link #remoteFilter} to allow the server to
62436  * perform these operations instead.</p>
62437  *
62438  * <p>Filtering and sorting after the Store has been instantiated is also easy. Calling {@link #filter} adds another filter to the Store
62439  * and automatically filters the dataset (calling {@link #filter} with no arguments simply re-applies all existing filters). Note that by
62440  * default {@link #sortOnFilter} is set to true, which means that your sorters are automatically reapplied if using local sorting.</p>
62441  *
62442 <pre><code>
62443 store.filter('eyeColor', 'Brown');
62444 </code></pre>
62445  *
62446  * <p>Change the sorting at any time by calling {@link #sort}:</p>
62447  *
62448 <pre><code>
62449 store.sort('height', 'ASC');
62450 </code></pre>
62451  *
62452  * <p>Note that all existing sorters will be removed in favor of the new sorter data (if {@link #sort} is called with no arguments,
62453  * the existing sorters are just reapplied instead of being removed). To keep existing sorters and add new ones, just add them
62454  * to the MixedCollection:</p>
62455  *
62456 <pre><code>
62457 store.sorters.add(new Ext.util.Sorter({
62458     property : 'shoeSize',
62459     direction: 'ASC'
62460 }));
62461
62462 store.sort();
62463 </code></pre>
62464  *
62465  * <p><u>Registering with StoreManager</u></p>
62466  *
62467  * <p>Any Store that is instantiated with a {@link #storeId} will automatically be registed with the {@link Ext.data.StoreManager StoreManager}.
62468  * This makes it easy to reuse the same store in multiple views:</p>
62469  *
62470  <pre><code>
62471 //this store can be used several times
62472 new Ext.data.Store({
62473     model: 'User',
62474     storeId: 'usersStore'
62475 });
62476
62477 new Ext.List({
62478     store: 'usersStore',
62479
62480     //other config goes here
62481 });
62482
62483 new Ext.view.View({
62484     store: 'usersStore',
62485
62486     //other config goes here
62487 });
62488 </code></pre>
62489  *
62490  * <p><u>Further Reading</u></p>
62491  *
62492  * <p>Stores are backed up by an ecosystem of classes that enables their operation. To gain a full understanding of these
62493  * pieces and how they fit together, see:</p>
62494  *
62495  * <ul style="list-style-type: disc; padding-left: 25px">
62496  * <li>{@link Ext.data.proxy.Proxy Proxy} - overview of what Proxies are and how they are used</li>
62497  * <li>{@link Ext.data.Model Model} - the core class in the data package</li>
62498  * <li>{@link Ext.data.reader.Reader Reader} - used by any subclass of {@link Ext.data.proxy.Server ServerProxy} to read a response</li>
62499  * </ul>
62500  *
62501  * @constructor
62502  * @param {Object} config Optional config object
62503  */
62504 Ext.define('Ext.data.Store', {
62505     extend: 'Ext.data.AbstractStore',
62506
62507     alias: 'store.store',
62508
62509     requires: ['Ext.ModelManager', 'Ext.data.Model', 'Ext.util.Grouper'],
62510     uses: ['Ext.data.proxy.Memory'],
62511
62512     /**
62513      * @cfg {Boolean} remoteSort
62514      * True to defer any sorting operation to the server. If false, sorting is done locally on the client. Defaults to <tt>false</tt>.
62515      */
62516     remoteSort: false,
62517
62518     /**
62519      * @cfg {Boolean} remoteFilter
62520      * True to defer any filtering operation to the server. If false, filtering is done locally on the client. Defaults to <tt>false</tt>.
62521      */
62522     remoteFilter: false,
62523     
62524     /**
62525      * @cfg {Boolean} remoteGroup
62526      * True if the grouping should apply on the server side, false if it is local only (defaults to false).  If the
62527      * grouping is local, it can be applied immediately to the data.  If it is remote, then it will simply act as a
62528      * helper, automatically sending the grouping information to the server.
62529      */
62530     remoteGroup : false,
62531
62532     /**
62533      * @cfg {String/Ext.data.proxy.Proxy/Object} proxy The Proxy to use for this Store. This can be either a string, a config
62534      * object or a Proxy instance - see {@link #setProxy} for details.
62535      */
62536
62537     /**
62538      * @cfg {Array} data Optional array of Model instances or data objects to load locally. See "Inline data" above for details.
62539      */
62540
62541     /**
62542      * @cfg {String} model The {@link Ext.data.Model} associated with this store
62543      */
62544
62545     /**
62546      * The (optional) field by which to group data in the store. Internally, grouping is very similar to sorting - the
62547      * groupField and {@link #groupDir} are injected as the first sorter (see {@link #sort}). Stores support a single
62548      * level of grouping, and groups can be fetched via the {@link #getGroups} method.
62549      * @property groupField
62550      * @type String
62551      */
62552     groupField: undefined,
62553
62554     /**
62555      * The direction in which sorting should be applied when grouping. Defaults to "ASC" - the other supported value is "DESC"
62556      * @property groupDir
62557      * @type String
62558      */
62559     groupDir: "ASC",
62560
62561     /**
62562      * The number of records considered to form a 'page'. This is used to power the built-in
62563      * paging using the nextPage and previousPage functions. Defaults to 25.
62564      * @property pageSize
62565      * @type Number
62566      */
62567     pageSize: 25,
62568
62569     /**
62570      * The page that the Store has most recently loaded (see {@link #loadPage})
62571      * @property currentPage
62572      * @type Number
62573      */
62574     currentPage: 1,
62575
62576     /**
62577      * @cfg {Boolean} clearOnPageLoad True to empty the store when loading another page via {@link #loadPage},
62578      * {@link #nextPage} or {@link #previousPage} (defaults to true). Setting to false keeps existing records, allowing
62579      * large data sets to be loaded one page at a time but rendered all together.
62580      */
62581     clearOnPageLoad: true,
62582
62583     /**
62584      * True if the Store is currently loading via its Proxy
62585      * @property loading
62586      * @type Boolean
62587      * @private
62588      */
62589     loading: false,
62590
62591     /**
62592      * @cfg {Boolean} sortOnFilter For local filtering only, causes {@link #sort} to be called whenever {@link #filter} is called,
62593      * causing the sorters to be reapplied after filtering. Defaults to true
62594      */
62595     sortOnFilter: true,
62596     
62597     /**
62598      * @cfg {Boolean} buffered
62599      * Allow the store to buffer and pre-fetch pages of records. This is to be used in conjunction with a view will
62600      * tell the store to pre-fetch records ahead of a time.
62601      */
62602     buffered: false,
62603     
62604     /**
62605      * @cfg {Number} purgePageCount 
62606      * The number of pages to keep in the cache before purging additional records. A value of 0 indicates to never purge the prefetched data.
62607      * This option is only relevant when the {@link #buffered} option is set to true.
62608      */
62609     purgePageCount: 5,
62610
62611     isStore: true,
62612
62613     //documented above
62614     constructor: function(config) {
62615         config = config || {};
62616
62617         var me = this,
62618             groupers = config.groupers,
62619             proxy,
62620             data;
62621             
62622         if (config.buffered || me.buffered) {
62623             me.prefetchData = Ext.create('Ext.util.MixedCollection', false, function(record) {
62624                 return record.index;
62625             });
62626             me.pendingRequests = [];
62627             me.pagesRequested = [];
62628             
62629             me.sortOnLoad = false;
62630             me.filterOnLoad = false;
62631         }
62632             
62633         me.addEvents(
62634             /**
62635              * @event beforeprefetch
62636              * Fires before a prefetch occurs. Return false to cancel.
62637              * @param {Ext.data.store} this
62638              * @param {Ext.data.Operation} operation The associated operation
62639              */
62640             'beforeprefetch',
62641             /**
62642              * @event groupchange
62643              * Fired whenever the grouping in the grid changes
62644              * @param {Ext.data.Store} store The store
62645              * @param {Array} groupers The array of grouper objects
62646              */
62647             'groupchange',
62648             /**
62649              * @event load
62650              * Fires whenever records have been prefetched
62651              * @param {Ext.data.store} this
62652              * @param {Array} records An array of records
62653              * @param {Boolean} successful True if the operation was successful.
62654              * @param {Ext.data.Operation} operation The associated operation
62655              */
62656             'prefetch'
62657         );
62658         data = config.data || me.data;
62659
62660         /**
62661          * The MixedCollection that holds this store's local cache of records
62662          * @property data
62663          * @type Ext.util.MixedCollection
62664          */
62665         me.data = Ext.create('Ext.util.MixedCollection', false, function(record) {
62666             return record.internalId;
62667         });
62668
62669         if (data) {
62670             me.inlineData = data;
62671             delete config.data;
62672         }
62673         
62674         if (!groupers && config.groupField) {
62675             groupers = [{
62676                 property : config.groupField,
62677                 direction: config.groupDir
62678             }];
62679         }
62680         delete config.groupers;
62681         
62682         /**
62683          * The collection of {@link Ext.util.Grouper Groupers} currently applied to this Store
62684          * @property groupers
62685          * @type Ext.util.MixedCollection
62686          */
62687         me.groupers = Ext.create('Ext.util.MixedCollection');
62688         me.groupers.addAll(me.decodeGroupers(groupers));
62689
62690         this.callParent([config]);
62691         
62692         if (me.groupers.items.length) {
62693             me.sort(me.groupers.items, 'prepend', false);
62694         }
62695
62696         proxy = me.proxy;
62697         data = me.inlineData;
62698
62699         if (data) {
62700             if (proxy instanceof Ext.data.proxy.Memory) {
62701                 proxy.data = data;
62702                 me.read();
62703             } else {
62704                 me.add.apply(me, data);
62705             }
62706
62707             me.sort();
62708             delete me.inlineData;
62709         } else if (me.autoLoad) {
62710             Ext.defer(me.load, 10, me, [typeof me.autoLoad === 'object' ? me.autoLoad: undefined]);
62711             // Remove the defer call, we may need reinstate this at some point, but currently it's not obvious why it's here.
62712             // this.load(typeof this.autoLoad == 'object' ? this.autoLoad : undefined);
62713         }
62714     },
62715     
62716     onBeforeSort: function() {
62717         this.sort(this.groupers.items, 'prepend', false);
62718     },
62719     
62720     /**
62721      * @private
62722      * Normalizes an array of grouper objects, ensuring that they are all Ext.util.Grouper instances
62723      * @param {Array} groupers The groupers array
62724      * @return {Array} Array of Ext.util.Grouper objects
62725      */
62726     decodeGroupers: function(groupers) {
62727         if (!Ext.isArray(groupers)) {
62728             if (groupers === undefined) {
62729                 groupers = [];
62730             } else {
62731                 groupers = [groupers];
62732             }
62733         }
62734
62735         var length  = groupers.length,
62736             Grouper = Ext.util.Grouper,
62737             config, i;
62738
62739         for (i = 0; i < length; i++) {
62740             config = groupers[i];
62741
62742             if (!(config instanceof Grouper)) {
62743                 if (Ext.isString(config)) {
62744                     config = {
62745                         property: config
62746                     };
62747                 }
62748                 
62749                 Ext.applyIf(config, {
62750                     root     : 'data',
62751                     direction: "ASC"
62752                 });
62753
62754                 //support for 3.x style sorters where a function can be defined as 'fn'
62755                 if (config.fn) {
62756                     config.sorterFn = config.fn;
62757                 }
62758
62759                 //support a function to be passed as a sorter definition
62760                 if (typeof config == 'function') {
62761                     config = {
62762                         sorterFn: config
62763                     };
62764                 }
62765
62766                 groupers[i] = new Grouper(config);
62767             }
62768         }
62769
62770         return groupers;
62771     },
62772     
62773     /**
62774      * Group data in the store
62775      * @param {String|Array} groupers Either a string name of one of the fields in this Store's configured {@link Ext.data.Model Model},
62776      * or an Array of grouper configurations.
62777      * @param {String} direction The overall direction to group the data by. Defaults to "ASC".
62778      */
62779     group: function(groupers, direction) {
62780         var me = this,
62781             grouper,
62782             newGroupers;
62783             
62784         if (Ext.isArray(groupers)) {
62785             newGroupers = groupers;
62786         } else if (Ext.isObject(groupers)) {
62787             newGroupers = [groupers];
62788         } else if (Ext.isString(groupers)) {
62789             grouper = me.groupers.get(groupers);
62790
62791             if (!grouper) {
62792                 grouper = {
62793                     property : groupers,
62794                     direction: direction
62795                 };
62796                 newGroupers = [grouper];
62797             } else if (direction === undefined) {
62798                 grouper.toggle();
62799             } else {
62800                 grouper.setDirection(direction);
62801             }
62802         }
62803         
62804         if (newGroupers && newGroupers.length) {
62805             newGroupers = me.decodeGroupers(newGroupers);
62806             me.groupers.clear();
62807             me.groupers.addAll(newGroupers);
62808         }
62809         
62810         if (me.remoteGroup) {
62811             me.load({
62812                 scope: me,
62813                 callback: me.fireGroupChange
62814             });
62815         } else {
62816             me.sort();
62817             me.fireEvent('groupchange', me, me.groupers);
62818         }
62819     },
62820     
62821     /**
62822      * Clear any groupers in the store
62823      */
62824     clearGrouping: function(){
62825         var me = this;
62826         // Clear any groupers we pushed on to the sorters
62827         me.groupers.each(function(grouper){
62828             me.sorters.remove(grouper);
62829         });
62830         me.groupers.clear();
62831         if (me.remoteGroup) {
62832             me.load({
62833                 scope: me,
62834                 callback: me.fireGroupChange
62835             });
62836         } else {
62837             me.sort();
62838             me.fireEvent('groupchange', me, me.groupers);
62839         }
62840     },
62841     
62842     /**
62843      * Checks if the store is currently grouped
62844      * @return {Boolean} True if the store is grouped.
62845      */
62846     isGrouped: function() {
62847         return this.groupers.getCount() > 0;    
62848     },
62849     
62850     /**
62851      * Fires the groupchange event. Abstracted out so we can use it
62852      * as a callback
62853      * @private
62854      */
62855     fireGroupChange: function(){
62856         this.fireEvent('groupchange', this, this.groupers);    
62857     },
62858
62859     /**
62860      * Returns an object containing the result of applying grouping to the records in this store. See {@link #groupField},
62861      * {@link #groupDir} and {@link #getGroupString}. Example for a store containing records with a color field:
62862 <pre><code>
62863 var myStore = new Ext.data.Store({
62864     groupField: 'color',
62865     groupDir  : 'DESC'
62866 });
62867
62868 myStore.getGroups(); //returns:
62869 [
62870     {
62871         name: 'yellow',
62872         children: [
62873             //all records where the color field is 'yellow'
62874         ]
62875     },
62876     {
62877         name: 'red',
62878         children: [
62879             //all records where the color field is 'red'
62880         ]
62881     }
62882 ]
62883 </code></pre>
62884      * @param {String} groupName (Optional) Pass in an optional groupName argument to access a specific group as defined by {@link #getGroupString}
62885      * @return {Array} The grouped data
62886      */
62887     getGroups: function(requestGroupString) {
62888         var records = this.data.items,
62889             length = records.length,
62890             groups = [],
62891             pointers = {},
62892             record,
62893             groupStr,
62894             group,
62895             i;
62896
62897         for (i = 0; i < length; i++) {
62898             record = records[i];
62899             groupStr = this.getGroupString(record);
62900             group = pointers[groupStr];
62901
62902             if (group === undefined) {
62903                 group = {
62904                     name: groupStr,
62905                     children: []
62906                 };
62907
62908                 groups.push(group);
62909                 pointers[groupStr] = group;
62910             }
62911
62912             group.children.push(record);
62913         }
62914
62915         return requestGroupString ? pointers[requestGroupString] : groups;
62916     },
62917
62918     /**
62919      * @private
62920      * For a given set of records and a Grouper, returns an array of arrays - each of which is the set of records
62921      * matching a certain group.
62922      */
62923     getGroupsForGrouper: function(records, grouper) {
62924         var length = records.length,
62925             groups = [],
62926             oldValue,
62927             newValue,
62928             record,
62929             group,
62930             i;
62931
62932         for (i = 0; i < length; i++) {
62933             record = records[i];
62934             newValue = grouper.getGroupString(record);
62935
62936             if (newValue !== oldValue) {
62937                 group = {
62938                     name: newValue,
62939                     grouper: grouper,
62940                     records: []
62941                 };
62942                 groups.push(group);
62943             }
62944
62945             group.records.push(record);
62946
62947             oldValue = newValue;
62948         }
62949
62950         return groups;
62951     },
62952
62953     /**
62954      * @private
62955      * This is used recursively to gather the records into the configured Groupers. The data MUST have been sorted for
62956      * this to work properly (see {@link #getGroupData} and {@link #getGroupsForGrouper}) Most of the work is done by
62957      * {@link #getGroupsForGrouper} - this function largely just handles the recursion.
62958      * @param {Array} records The set or subset of records to group
62959      * @param {Number} grouperIndex The grouper index to retrieve
62960      * @return {Array} The grouped records
62961      */
62962     getGroupsForGrouperIndex: function(records, grouperIndex) {
62963         var me = this,
62964             groupers = me.groupers,
62965             grouper = groupers.getAt(grouperIndex),
62966             groups = me.getGroupsForGrouper(records, grouper),
62967             length = groups.length,
62968             i;
62969
62970         if (grouperIndex + 1 < groupers.length) {
62971             for (i = 0; i < length; i++) {
62972                 groups[i].children = me.getGroupsForGrouperIndex(groups[i].records, grouperIndex + 1);
62973             }
62974         }
62975
62976         for (i = 0; i < length; i++) {
62977             groups[i].depth = grouperIndex;
62978         }
62979
62980         return groups;
62981     },
62982
62983     /**
62984      * @private
62985      * <p>Returns records grouped by the configured {@link #groupers grouper} configuration. Sample return value (in
62986      * this case grouping by genre and then author in a fictional books dataset):</p>
62987 <pre><code>
62988 [
62989     {
62990         name: 'Fantasy',
62991         depth: 0,
62992         records: [
62993             //book1, book2, book3, book4
62994         ],
62995         children: [
62996             {
62997                 name: 'Rowling',
62998                 depth: 1,
62999                 records: [
63000                     //book1, book2
63001                 ]
63002             },
63003             {
63004                 name: 'Tolkein',
63005                 depth: 1,
63006                 records: [
63007                     //book3, book4
63008                 ]
63009             }
63010         ]
63011     }
63012 ]
63013 </code></pre>
63014      * @param {Boolean} sort True to call {@link #sort} before finding groups. Sorting is required to make grouping
63015      * function correctly so this should only be set to false if the Store is known to already be sorted correctly
63016      * (defaults to true)
63017      * @return {Array} The group data
63018      */
63019     getGroupData: function(sort) {
63020         var me = this;
63021         if (sort !== false) {
63022             me.sort();
63023         }
63024
63025         return me.getGroupsForGrouperIndex(me.data.items, 0);
63026     },
63027
63028     /**
63029      * <p>Returns the string to group on for a given model instance. The default implementation of this method returns
63030      * the model's {@link #groupField}, but this can be overridden to group by an arbitrary string. For example, to
63031      * group by the first letter of a model's 'name' field, use the following code:</p>
63032 <pre><code>
63033 new Ext.data.Store({
63034     groupDir: 'ASC',
63035     getGroupString: function(instance) {
63036         return instance.get('name')[0];
63037     }
63038 });
63039 </code></pre>
63040      * @param {Ext.data.Model} instance The model instance
63041      * @return {String} The string to compare when forming groups
63042      */
63043     getGroupString: function(instance) {
63044         var group = this.groupers.first();
63045         if (group) {
63046             return instance.get(group.property);
63047         }
63048         return '';
63049     },
63050     /**
63051      * Inserts Model instances into the Store at the given index and fires the {@link #add} event.
63052      * See also <code>{@link #add}</code>.
63053      * @param {Number} index The start index at which to insert the passed Records.
63054      * @param {Ext.data.Model[]} records An Array of Ext.data.Model objects to add to the cache.
63055      */
63056     insert: function(index, records) {
63057         var me = this,
63058             sync = false,
63059             i,
63060             record,
63061             len;
63062
63063         records = [].concat(records);
63064         for (i = 0, len = records.length; i < len; i++) {
63065             record = me.createModel(records[i]);
63066             record.set(me.modelDefaults);
63067             // reassign the model in the array in case it wasn't created yet
63068             records[i] = record;
63069             
63070             me.data.insert(index + i, record);
63071             record.join(me);
63072
63073             sync = sync || record.phantom === true;
63074         }
63075
63076         if (me.snapshot) {
63077             me.snapshot.addAll(records);
63078         }
63079
63080         me.fireEvent('add', me, records, index);
63081         me.fireEvent('datachanged', me);
63082         if (me.autoSync && sync) {
63083             me.sync();
63084         }
63085     },
63086
63087     /**
63088      * Adds Model instances to the Store by instantiating them based on a JavaScript object. When adding already-
63089      * instantiated Models, use {@link #insert} instead. The instances will be added at the end of the existing collection.
63090      * This method accepts either a single argument array of Model instances or any number of model instance arguments.
63091      * Sample usage:
63092      *
63093 <pre><code>
63094 myStore.add({some: 'data'}, {some: 'other data'});
63095 </code></pre>
63096      *
63097      * @param {Object} data The data for each model
63098      * @return {Array} The array of newly created model instances
63099      */
63100     add: function(records) {
63101         //accept both a single-argument array of records, or any number of record arguments
63102         if (!Ext.isArray(records)) {
63103             records = Array.prototype.slice.apply(arguments);
63104         }
63105
63106         var me = this,
63107             i = 0,
63108             length = records.length,
63109             record;
63110
63111         for (; i < length; i++) {
63112             record = me.createModel(records[i]);
63113             // reassign the model in the array in case it wasn't created yet
63114             records[i] = record;
63115         }
63116
63117         me.insert(me.data.length, records);
63118
63119         return records;
63120     },
63121
63122     /**
63123      * Converts a literal to a model, if it's not a model already
63124      * @private
63125      * @param record {Ext.data.Model/Object} The record to create
63126      * @return {Ext.data.Model}
63127      */
63128     createModel: function(record) {
63129         if (!record.isModel) {
63130             record = Ext.ModelManager.create(record, this.model);
63131         }
63132
63133         return record;
63134     },
63135
63136     /**
63137      * Calls the specified function for each of the {@link Ext.data.Model Records} in the cache.
63138      * @param {Function} fn The function to call. The {@link Ext.data.Model Record} is passed as the first parameter.
63139      * Returning <tt>false</tt> aborts and exits the iteration.
63140      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
63141      * Defaults to the current {@link Ext.data.Model Record} in the iteration.
63142      */
63143     each: function(fn, scope) {
63144         this.data.each(fn, scope);
63145     },
63146
63147     /**
63148      * Removes the given record from the Store, firing the 'remove' event for each instance that is removed, plus a single
63149      * 'datachanged' event after removal.
63150      * @param {Ext.data.Model/Array} records The Ext.data.Model instance or array of instances to remove
63151      */
63152     remove: function(records, /* private */ isMove) {
63153         if (!Ext.isArray(records)) {
63154             records = [records];
63155         }
63156
63157         /*
63158          * Pass the isMove parameter if we know we're going to be re-inserting this record
63159          */
63160         isMove = isMove === true;
63161         var me = this,
63162             sync = false,
63163             i = 0,
63164             length = records.length,
63165             isPhantom,
63166             index,
63167             record;
63168
63169         for (; i < length; i++) {
63170             record = records[i];
63171             index = me.data.indexOf(record);
63172             
63173             if (me.snapshot) {
63174                 me.snapshot.remove(record);
63175             }
63176             
63177             if (index > -1) {
63178                 isPhantom = record.phantom === true;
63179                 if (!isMove && !isPhantom) {
63180                     // don't push phantom records onto removed
63181                     me.removed.push(record);
63182                 }
63183
63184                 record.unjoin(me);
63185                 me.data.remove(record);
63186                 sync = sync || !isPhantom;
63187
63188                 me.fireEvent('remove', me, record, index);
63189             }
63190         }
63191
63192         me.fireEvent('datachanged', me);
63193         if (!isMove && me.autoSync && sync) {
63194             me.sync();
63195         }
63196     },
63197
63198     /**
63199      * Removes the model instance at the given index
63200      * @param {Number} index The record index
63201      */
63202     removeAt: function(index) {
63203         var record = this.getAt(index);
63204
63205         if (record) {
63206             this.remove(record);
63207         }
63208     },
63209
63210     /**
63211      * <p>Loads data into the Store via the configured {@link #proxy}. This uses the Proxy to make an
63212      * asynchronous call to whatever storage backend the Proxy uses, automatically adding the retrieved
63213      * instances into the Store and calling an optional callback if required. Example usage:</p>
63214      *
63215 <pre><code>
63216 store.load({
63217     scope   : this,
63218     callback: function(records, operation, success) {
63219         //the {@link Ext.data.Operation operation} object contains all of the details of the load operation
63220         console.log(records);
63221     }
63222 });
63223 </code></pre>
63224      *
63225      * <p>If the callback scope does not need to be set, a function can simply be passed:</p>
63226      *
63227 <pre><code>
63228 store.load(function(records, operation, success) {
63229     console.log('loaded records');
63230 });
63231 </code></pre>
63232      *
63233      * @param {Object/Function} options Optional config object, passed into the Ext.data.Operation object before loading.
63234      */
63235     load: function(options) {
63236         var me = this;
63237             
63238         options = options || {};
63239
63240         if (Ext.isFunction(options)) {
63241             options = {
63242                 callback: options
63243             };
63244         }
63245
63246         Ext.applyIf(options, {
63247             groupers: me.groupers.items,
63248             page: me.currentPage,
63249             start: (me.currentPage - 1) * me.pageSize,
63250             limit: me.pageSize,
63251             addRecords: false
63252         });      
63253
63254         return me.callParent([options]);
63255     },
63256
63257     /**
63258      * @private
63259      * Called internally when a Proxy has completed a load request
63260      */
63261     onProxyLoad: function(operation) {
63262         var me = this,
63263             resultSet = operation.getResultSet(),
63264             records = operation.getRecords(),
63265             successful = operation.wasSuccessful();
63266
63267         if (resultSet) {
63268             me.totalCount = resultSet.total;
63269         }
63270
63271         if (successful) {
63272             me.loadRecords(records, operation);
63273         }
63274
63275         me.loading = false;
63276         me.fireEvent('load', me, records, successful);
63277
63278         //TODO: deprecate this event, it should always have been 'load' instead. 'load' is now documented, 'read' is not.
63279         //People are definitely using this so can't deprecate safely until 2.x
63280         me.fireEvent('read', me, records, operation.wasSuccessful());
63281
63282         //this is a callback that would have been passed to the 'read' function and is optional
63283         Ext.callback(operation.callback, operation.scope || me, [records, operation, successful]);
63284     },
63285     
63286     /**
63287      * Create any new records when a write is returned from the server.
63288      * @private
63289      * @param {Array} records The array of new records
63290      * @param {Ext.data.Operation} operation The operation that just completed
63291      * @param {Boolean} success True if the operation was successful
63292      */
63293     onCreateRecords: function(records, operation, success) {
63294         if (success) {
63295             var i = 0,
63296                 data = this.data,
63297                 snapshot = this.snapshot,
63298                 length = records.length,
63299                 originalRecords = operation.records,
63300                 record,
63301                 original,
63302                 index;
63303
63304             /**
63305              * Loop over each record returned from the server. Assume they are
63306              * returned in order of how they were sent. If we find a matching
63307              * record, replace it with the newly created one.
63308              */
63309             for (; i < length; ++i) {
63310                 record = records[i];
63311                 original = originalRecords[i];
63312                 if (original) {
63313                     index = data.indexOf(original);
63314                     if (index > -1) {
63315                         data.removeAt(index);
63316                         data.insert(index, record);
63317                     }
63318                     if (snapshot) {
63319                         index = snapshot.indexOf(original);
63320                         if (index > -1) {
63321                             snapshot.removeAt(index);
63322                             snapshot.insert(index, record);
63323                         }
63324                     }
63325                     record.phantom = false;
63326                     record.join(this);
63327                 }
63328             }
63329         }
63330     },
63331
63332     /**
63333      * Update any records when a write is returned from the server.
63334      * @private
63335      * @param {Array} records The array of updated records
63336      * @param {Ext.data.Operation} operation The operation that just completed
63337      * @param {Boolean} success True if the operation was successful
63338      */
63339     onUpdateRecords: function(records, operation, success){
63340         if (success) {
63341             var i = 0,
63342                 length = records.length,
63343                 data = this.data,
63344                 snapshot = this.snapshot,
63345                 record;
63346
63347             for (; i < length; ++i) {
63348                 record = records[i];
63349                 data.replace(record);
63350                 if (snapshot) {
63351                     snapshot.replace(record);
63352                 }
63353                 record.join(this);
63354             }
63355         }
63356     },
63357
63358     /**
63359      * Remove any records when a write is returned from the server.
63360      * @private
63361      * @param {Array} records The array of removed records
63362      * @param {Ext.data.Operation} operation The operation that just completed
63363      * @param {Boolean} success True if the operation was successful
63364      */
63365     onDestroyRecords: function(records, operation, success){
63366         if (success) {
63367             var me = this,
63368                 i = 0,
63369                 length = records.length,
63370                 data = me.data,
63371                 snapshot = me.snapshot,
63372                 record;
63373
63374             for (; i < length; ++i) {
63375                 record = records[i];
63376                 record.unjoin(me);
63377                 data.remove(record);
63378                 if (snapshot) {
63379                     snapshot.remove(record);
63380                 }
63381             }
63382             me.removed = [];
63383         }
63384     },
63385
63386     //inherit docs
63387     getNewRecords: function() {
63388         return this.data.filterBy(this.filterNew).items;
63389     },
63390
63391     //inherit docs
63392     getUpdatedRecords: function() {
63393         return this.data.filterBy(this.filterUpdated).items;
63394     },
63395
63396     /**
63397      * Filters the loaded set of records by a given set of filters.
63398      * @param {Mixed} filters The set of filters to apply to the data. These are stored internally on the store,
63399      * but the filtering itself is done on the Store's {@link Ext.util.MixedCollection MixedCollection}. See
63400      * MixedCollection's {@link Ext.util.MixedCollection#filter filter} method for filter syntax. Alternatively,
63401      * pass in a property string
63402      * @param {String} value Optional value to filter by (only if using a property string as the first argument)
63403      */
63404     filter: function(filters, value) {
63405         if (Ext.isString(filters)) {
63406             filters = {
63407                 property: filters,
63408                 value: value
63409             };
63410         }
63411
63412         var me = this,
63413             decoded = me.decodeFilters(filters),
63414             i = 0,
63415             doLocalSort = me.sortOnFilter && !me.remoteSort,
63416             length = decoded.length;
63417
63418         for (; i < length; i++) {
63419             me.filters.replace(decoded[i]);
63420         }
63421
63422         if (me.remoteFilter) {
63423             //the load function will pick up the new filters and request the filtered data from the proxy
63424             me.load();
63425         } else {
63426             /**
63427              * A pristine (unfiltered) collection of the records in this store. This is used to reinstate
63428              * records when a filter is removed or changed
63429              * @property snapshot
63430              * @type Ext.util.MixedCollection
63431              */
63432             if (me.filters.getCount()) {
63433                 me.snapshot = me.snapshot || me.data.clone();
63434                 me.data = me.data.filter(me.filters.items);
63435
63436                 if (doLocalSort) {
63437                     me.sort();
63438                 }
63439                 // fire datachanged event if it hasn't already been fired by doSort
63440                 if (!doLocalSort || me.sorters.length < 1) {
63441                     me.fireEvent('datachanged', me);
63442                 }
63443             }
63444         }
63445     },
63446
63447     /**
63448      * Revert to a view of the Record cache with no filtering applied.
63449      * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
63450      * {@link #datachanged} event.
63451      */
63452     clearFilter: function(suppressEvent) {
63453         var me = this;
63454
63455         me.filters.clear();
63456
63457         if (me.remoteFilter) {
63458             me.load();
63459         } else if (me.isFiltered()) {
63460             me.data = me.snapshot.clone();
63461             delete me.snapshot;
63462
63463             if (suppressEvent !== true) {
63464                 me.fireEvent('datachanged', me);
63465             }
63466         }
63467     },
63468
63469     /**
63470      * Returns true if this store is currently filtered
63471      * @return {Boolean}
63472      */
63473     isFiltered: function() {
63474         var snapshot = this.snapshot;
63475         return !! snapshot && snapshot !== this.data;
63476     },
63477
63478     /**
63479      * Filter by a function. The specified function will be called for each
63480      * Record in this Store. If the function returns <tt>true</tt> the Record is included,
63481      * otherwise it is filtered out.
63482      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
63483      * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
63484      * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
63485      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
63486      * </ul>
63487      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
63488      */
63489     filterBy: function(fn, scope) {
63490         var me = this;
63491
63492         me.snapshot = me.snapshot || me.data.clone();
63493         me.data = me.queryBy(fn, scope || me);
63494         me.fireEvent('datachanged', me);
63495     },
63496
63497     /**
63498      * Query the cached records in this Store using a filtering function. The specified function
63499      * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
63500      * included in the results.
63501      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
63502      * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
63503      * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
63504      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
63505      * </ul>
63506      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
63507      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
63508      **/
63509     queryBy: function(fn, scope) {
63510         var me = this,
63511         data = me.snapshot || me.data;
63512         return data.filterBy(fn, scope || me);
63513     },
63514
63515     /**
63516      * Loads an array of data straight into the Store
63517      * @param {Array} data Array of data to load. Any non-model instances will be cast into model instances first
63518      * @param {Boolean} append True to add the records to the existing records in the store, false to remove the old ones first
63519      */
63520     loadData: function(data, append) {
63521         var model = this.model,
63522             length = data.length,
63523             i,
63524             record;
63525
63526         //make sure each data element is an Ext.data.Model instance
63527         for (i = 0; i < length; i++) {
63528             record = data[i];
63529
63530             if (! (record instanceof Ext.data.Model)) {
63531                 data[i] = Ext.ModelManager.create(record, model);
63532             }
63533         }
63534
63535         this.loadRecords(data, {addRecords: append});
63536     },
63537
63538     /**
63539      * Loads an array of {@Ext.data.Model model} instances into the store, fires the datachanged event. This should only usually
63540      * be called internally when loading from the {@link Ext.data.proxy.Proxy Proxy}, when adding records manually use {@link #add} instead
63541      * @param {Array} records The array of records to load
63542      * @param {Object} options {addRecords: true} to add these records to the existing records, false to remove the Store's existing records first
63543      */
63544     loadRecords: function(records, options) {
63545         var me     = this,
63546             i      = 0,
63547             length = records.length;
63548
63549         options = options || {};
63550
63551
63552         if (!options.addRecords) {
63553             delete me.snapshot;
63554             me.data.clear();
63555         }
63556
63557         me.data.addAll(records);
63558
63559         //FIXME: this is not a good solution. Ed Spencer is totally responsible for this and should be forced to fix it immediately.
63560         for (; i < length; i++) {
63561             if (options.start !== undefined) {
63562                 records[i].index = options.start + i;
63563
63564             }
63565             records[i].join(me);
63566         }
63567
63568         /*
63569          * this rather inelegant suspension and resumption of events is required because both the filter and sort functions
63570          * fire an additional datachanged event, which is not wanted. Ideally we would do this a different way. The first
63571          * datachanged event is fired by the call to this.add, above.
63572          */
63573         me.suspendEvents();
63574
63575         if (me.filterOnLoad && !me.remoteFilter) {
63576             me.filter();
63577         }
63578
63579         if (me.sortOnLoad && !me.remoteSort) {
63580             me.sort();
63581         }
63582
63583         me.resumeEvents();
63584         me.fireEvent('datachanged', me, records);
63585     },
63586
63587     // PAGING METHODS
63588     /**
63589      * Loads a given 'page' of data by setting the start and limit values appropriately. Internally this just causes a normal
63590      * load operation, passing in calculated 'start' and 'limit' params
63591      * @param {Number} page The number of the page to load
63592      */
63593     loadPage: function(page) {
63594         var me = this;
63595
63596         me.currentPage = page;
63597
63598         me.read({
63599             page: page,
63600             start: (page - 1) * me.pageSize,
63601             limit: me.pageSize,
63602             addRecords: !me.clearOnPageLoad
63603         });
63604     },
63605
63606     /**
63607      * Loads the next 'page' in the current data set
63608      */
63609     nextPage: function() {
63610         this.loadPage(this.currentPage + 1);
63611     },
63612
63613     /**
63614      * Loads the previous 'page' in the current data set
63615      */
63616     previousPage: function() {
63617         this.loadPage(this.currentPage - 1);
63618     },
63619
63620     // private
63621     clearData: function() {
63622         this.data.each(function(record) {
63623             record.unjoin();
63624         });
63625
63626         this.data.clear();
63627     },
63628     
63629     // Buffering
63630     /**
63631      * Prefetches data the Store using its configured {@link #proxy}.
63632      * @param {Object} options Optional config object, passed into the Ext.data.Operation object before loading.
63633      * See {@link #load}
63634      */
63635     prefetch: function(options) {
63636         var me = this,
63637             operation,
63638             requestId = me.getRequestId();
63639
63640         options = options || {};
63641
63642         Ext.applyIf(options, {
63643             action : 'read',
63644             filters: me.filters.items,
63645             sorters: me.sorters.items,
63646             requestId: requestId
63647         });
63648         me.pendingRequests.push(requestId);
63649
63650         operation = Ext.create('Ext.data.Operation', options);
63651
63652         // HACK to implement loadMask support.
63653         //if (operation.blocking) {
63654         //    me.fireEvent('beforeload', me, operation);
63655         //}
63656         if (me.fireEvent('beforeprefetch', me, operation) !== false) {
63657             me.loading = true;
63658             me.proxy.read(operation, me.onProxyPrefetch, me);
63659         }
63660         
63661         return me;
63662     },
63663     
63664     /**
63665      * Prefetches a page of data.
63666      * @param {Number} page The page to prefetch
63667      * @param {Object} options Optional config object, passed into the Ext.data.Operation object before loading.
63668      * See {@link #load}
63669      * @param
63670      */
63671     prefetchPage: function(page, options) {
63672         var me = this,
63673             pageSize = me.pageSize,
63674             start = (page - 1) * me.pageSize,
63675             end = start + pageSize;
63676         
63677         // Currently not requesting this page and range isn't already satisified 
63678         if (Ext.Array.indexOf(me.pagesRequested, page) === -1 && !me.rangeSatisfied(start, end)) {
63679             options = options || {};
63680             me.pagesRequested.push(page);
63681             Ext.applyIf(options, {
63682                 page : page,
63683                 start: start,
63684                 limit: pageSize,
63685                 callback: me.onWaitForGuarantee,
63686                 scope: me
63687             });
63688             
63689             me.prefetch(options);
63690         }
63691         
63692     },
63693     
63694     /**
63695      * Returns a unique requestId to track requests.
63696      * @private
63697      */
63698     getRequestId: function() {
63699         this.requestSeed = this.requestSeed || 1;
63700         return this.requestSeed++;
63701     },
63702     
63703     /**
63704      * Handles a success pre-fetch
63705      * @private
63706      * @param {Ext.data.Operation} operation The operation that completed
63707      */
63708     onProxyPrefetch: function(operation) {
63709         var me         = this,
63710             resultSet  = operation.getResultSet(),
63711             records    = operation.getRecords(),
63712             
63713             successful = operation.wasSuccessful();
63714         
63715         if (resultSet) {
63716             me.totalCount = resultSet.total;
63717             me.fireEvent('totalcountchange', me.totalCount);
63718         }
63719         
63720         if (successful) {
63721             me.cacheRecords(records, operation);
63722         }
63723         Ext.Array.remove(me.pendingRequests, operation.requestId);
63724         if (operation.page) {
63725             Ext.Array.remove(me.pagesRequested, operation.page);
63726         }
63727         
63728         me.loading = false;
63729         me.fireEvent('prefetch', me, records, successful, operation);
63730         
63731         // HACK to support loadMask
63732         if (operation.blocking) {
63733             me.fireEvent('load', me, records, successful);
63734         }
63735
63736         //this is a callback that would have been passed to the 'read' function and is optional
63737         Ext.callback(operation.callback, operation.scope || me, [records, operation, successful]);
63738     },
63739     
63740     /**
63741      * Caches the records in the prefetch and stripes them with their server-side
63742      * index.
63743      * @private
63744      * @param {Array} records The records to cache
63745      * @param {Ext.data.Operation} The associated operation
63746      */
63747     cacheRecords: function(records, operation) {
63748         var me     = this,
63749             i      = 0,
63750             length = records.length,
63751             start  = operation ? operation.start : 0;
63752         
63753         if (!Ext.isDefined(me.totalCount)) {
63754             me.totalCount = records.length;
63755             me.fireEvent('totalcountchange', me.totalCount);
63756         }
63757         
63758         for (; i < length; i++) {
63759             // this is the true index, not the viewIndex
63760             records[i].index = start + i;
63761         }
63762         
63763         me.prefetchData.addAll(records);
63764         if (me.purgePageCount) {
63765             me.purgeRecords();
63766         }
63767         
63768     },
63769     
63770     
63771     /**
63772      * Purge the least recently used records in the prefetch if the purgeCount
63773      * has been exceeded.
63774      */
63775     purgeRecords: function() {
63776         var me = this,
63777             prefetchCount = me.prefetchData.getCount(),
63778             purgeCount = me.purgePageCount * me.pageSize,
63779             numRecordsToPurge = prefetchCount - purgeCount - 1,
63780             i = 0;
63781
63782         for (; i <= numRecordsToPurge; i++) {
63783             me.prefetchData.removeAt(0);
63784         }
63785     },
63786     
63787     /**
63788      * Determines if the range has already been satisfied in the prefetchData.
63789      * @private
63790      * @param {Number} start The start index
63791      * @param {Number} end The end index in the range
63792      */
63793     rangeSatisfied: function(start, end) {
63794         var me = this,
63795             i = start,
63796             satisfied = true;
63797
63798         for (; i < end; i++) {
63799             if (!me.prefetchData.getByKey(i)) {
63800                 satisfied = false;
63801                 if (end - i > me.pageSize) {
63802                     Ext.Error.raise("A single page prefetch could never satisfy this request.");
63803                 }
63804                 break;
63805             }
63806         }
63807         return satisfied;
63808     },
63809     
63810     /**
63811      * Determines the page from a record index
63812      * @param {Number} index The record index
63813      * @return {Number} The page the record belongs to
63814      */
63815     getPageFromRecordIndex: function(index) {
63816         return Math.floor(index / this.pageSize) + 1;
63817     },
63818     
63819     /**
63820      * Handles a guaranteed range being loaded
63821      * @private
63822      */
63823     onGuaranteedRange: function() {
63824         var me = this,
63825             totalCount = me.getTotalCount(),
63826             start = me.requestStart,
63827             end = ((totalCount - 1) < me.requestEnd) ? totalCount - 1 : me.requestEnd,
63828             range = [],
63829             record,
63830             i = start;
63831             
63832         if (start > end) {
63833             Ext.Error.raise("Start (" + start + ") was greater than end (" + end + ")");
63834         }
63835         
63836         if (start !== me.guaranteedStart && end !== me.guaranteedEnd) {
63837             me.guaranteedStart = start;
63838             me.guaranteedEnd = end;
63839             
63840             for (; i <= end; i++) {
63841                 record = me.prefetchData.getByKey(i);
63842                 if (!record) {
63843                     Ext.Error.raise("Record was not found and store said it was guaranteed");
63844                 }
63845                 range.push(record);
63846             }
63847             me.fireEvent('guaranteedrange', range, start, end);
63848             if (me.cb) {
63849                 me.cb.call(me.scope || me, range);
63850             }
63851         }
63852         
63853         me.unmask();
63854     },
63855     
63856     // hack to support loadmask
63857     mask: function() {
63858         this.masked = true;
63859         this.fireEvent('beforeload');
63860     },
63861     
63862     // hack to support loadmask
63863     unmask: function() {
63864         if (this.masked) {
63865             this.fireEvent('load');
63866         }
63867     },
63868     
63869     /**
63870      * Returns the number of pending requests out.
63871      */
63872     hasPendingRequests: function() {
63873         return this.pendingRequests.length;
63874     },
63875     
63876     
63877     // wait until all requests finish, until guaranteeing the range.
63878     onWaitForGuarantee: function() {
63879         if (!this.hasPendingRequests()) {
63880             this.onGuaranteedRange();
63881         }
63882     },
63883     
63884     /**
63885      * Guarantee a specific range, this will load the store with a range (that
63886      * must be the pageSize or smaller) and take care of any loading that may
63887      * be necessary.
63888      */
63889     guaranteeRange: function(start, end, cb, scope) {
63890         if (start && end) {
63891             if (end - start > this.pageSize) {
63892                 Ext.Error.raise({
63893                     start: start,
63894                     end: end,
63895                     pageSize: this.pageSize,
63896                     msg: "Requested a bigger range than the specified pageSize"
63897                 });
63898             }
63899         }
63900         
63901         end = (end > this.totalCount) ? this.totalCount - 1 : end;
63902         
63903         var me = this,
63904             i = start,
63905             prefetchData = me.prefetchData,
63906             range = [],
63907             startLoaded = !!prefetchData.getByKey(start),
63908             endLoaded = !!prefetchData.getByKey(end),
63909             startPage = me.getPageFromRecordIndex(start),
63910             endPage = me.getPageFromRecordIndex(end);
63911             
63912         me.cb = cb;
63913         me.scope = scope;
63914
63915         me.requestStart = start;
63916         me.requestEnd = end;
63917         // neither beginning or end are loaded
63918         if (!startLoaded || !endLoaded) {
63919             // same page, lets load it
63920             if (startPage === endPage) {
63921                 me.mask();
63922                 me.prefetchPage(startPage, {
63923                     //blocking: true,
63924                     callback: me.onWaitForGuarantee,
63925                     scope: me
63926                 });
63927             // need to load two pages
63928             } else {
63929                 me.mask();
63930                 me.prefetchPage(startPage, {
63931                     //blocking: true,
63932                     callback: me.onWaitForGuarantee,
63933                     scope: me
63934                 });
63935                 me.prefetchPage(endPage, {
63936                     //blocking: true,
63937                     callback: me.onWaitForGuarantee,
63938                     scope: me
63939                 });
63940             }
63941         // Request was already satisfied via the prefetch
63942         } else {
63943             me.onGuaranteedRange();
63944         }
63945     },
63946     
63947     // because prefetchData is stored by index
63948     // this invalidates all of the prefetchedData
63949     sort: function() {
63950         var me = this,
63951             prefetchData = me.prefetchData,
63952             sorters,
63953             start,
63954             end,
63955             range;
63956             
63957         if (me.buffered) {
63958             if (me.remoteSort) {
63959                 prefetchData.clear();
63960                 me.callParent(arguments);
63961             } else {
63962                 sorters = me.getSorters();
63963                 start = me.guaranteedStart;
63964                 end = me.guaranteedEnd;
63965                 range;
63966                 
63967                 if (sorters.length) {
63968                     prefetchData.sort(sorters);
63969                     range = prefetchData.getRange();
63970                     prefetchData.clear();
63971                     me.cacheRecords(range);
63972                     delete me.guaranteedStart;
63973                     delete me.guaranteedEnd;
63974                     me.guaranteeRange(start, end);
63975                 }
63976                 me.callParent(arguments);
63977             }
63978         } else {
63979             me.callParent(arguments);
63980         }
63981     },
63982
63983     // overriden to provide striping of the indexes as sorting occurs.
63984     // this cannot be done inside of sort because datachanged has already
63985     // fired and will trigger a repaint of the bound view.
63986     doSort: function(sorterFn) {
63987         var me = this;
63988         if (me.remoteSort) {
63989             //the load function will pick up the new sorters and request the sorted data from the proxy
63990             me.load();
63991         } else {
63992             me.data.sortBy(sorterFn);
63993             if (!me.buffered) {
63994                 var range = me.getRange(),
63995                     ln = range.length,
63996                     i  = 0;
63997                 for (; i < ln; i++) {
63998                     range[i].index = i;
63999                 }
64000             }
64001             me.fireEvent('datachanged', me);
64002         }
64003     },
64004     
64005     /**
64006      * Finds the index of the first matching Record in this store by a specific field value.
64007      * @param {String} fieldName The name of the Record field to test.
64008      * @param {String/RegExp} value Either a string that the field value
64009      * should begin with, or a RegExp to test against the field.
64010      * @param {Number} startIndex (optional) The index to start searching at
64011      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
64012      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
64013      * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
64014      * @return {Number} The matched index or -1
64015      */
64016     find: function(property, value, start, anyMatch, caseSensitive, exactMatch) {
64017         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch);
64018         return fn ? this.data.findIndexBy(fn, null, start) : -1;
64019     },
64020
64021     /**
64022      * Finds the first matching Record in this store by a specific field value.
64023      * @param {String} fieldName The name of the Record field to test.
64024      * @param {String/RegExp} value Either a string that the field value
64025      * should begin with, or a RegExp to test against the field.
64026      * @param {Number} startIndex (optional) The index to start searching at
64027      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
64028      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
64029      * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
64030      * @return {Ext.data.Model} The matched record or null
64031      */
64032     findRecord: function() {
64033         var me = this,
64034             index = me.find.apply(me, arguments);
64035         return index !== -1 ? me.getAt(index) : null;
64036     },
64037
64038     /**
64039      * @private
64040      * Returns a filter function used to test a the given property's value. Defers most of the work to
64041      * Ext.util.MixedCollection's createValueMatcher function
64042      * @param {String} property The property to create the filter function for
64043      * @param {String/RegExp} value The string/regex to compare the property value to
64044      * @param {Boolean} anyMatch True if we don't care if the filter value is not the full value (defaults to false)
64045      * @param {Boolean} caseSensitive True to create a case-sensitive regex (defaults to false)
64046      * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
64047      * Ignored if anyMatch is true.
64048      */
64049     createFilterFn: function(property, value, anyMatch, caseSensitive, exactMatch) {
64050         if (Ext.isEmpty(value)) {
64051             return false;
64052         }
64053         value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch);
64054         return function(r) {
64055             return value.test(r.data[property]);
64056         };
64057     },
64058
64059     /**
64060      * Finds the index of the first matching Record in this store by a specific field value.
64061      * @param {String} fieldName The name of the Record field to test.
64062      * @param {Mixed} value The value to match the field against.
64063      * @param {Number} startIndex (optional) The index to start searching at
64064      * @return {Number} The matched index or -1
64065      */
64066     findExact: function(property, value, start) {
64067         return this.data.findIndexBy(function(rec) {
64068             return rec.get(property) === value;
64069         },
64070         this, start);
64071     },
64072
64073     /**
64074      * Find the index of the first matching Record in this Store by a function.
64075      * If the function returns <tt>true</tt> it is considered a match.
64076      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
64077      * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
64078      * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
64079      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
64080      * </ul>
64081      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
64082      * @param {Number} startIndex (optional) The index to start searching at
64083      * @return {Number} The matched index or -1
64084      */
64085     findBy: function(fn, scope, start) {
64086         return this.data.findIndexBy(fn, scope, start);
64087     },
64088
64089     /**
64090      * Collects unique values for a particular dataIndex from this store.
64091      * @param {String} dataIndex The property to collect
64092      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
64093      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
64094      * @return {Array} An array of the unique values
64095      **/
64096     collect: function(dataIndex, allowNull, bypassFilter) {
64097         var me = this,
64098             data = (bypassFilter === true && me.snapshot) ? me.snapshot: me.data;
64099
64100         return data.collect(dataIndex, 'data', allowNull);
64101     },
64102
64103     /**
64104      * Gets the number of cached records.
64105      * <p>If using paging, this may not be the total size of the dataset. If the data object
64106      * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
64107      * the dataset size.  <b>Note</b>: see the Important note in {@link #load}.</p>
64108      * @return {Number} The number of Records in the Store's cache.
64109      */
64110     getCount: function() {
64111         return this.data.length || 0;
64112     },
64113
64114     /**
64115      * Returns the total number of {@link Ext.data.Model Model} instances that the {@link Ext.data.proxy.Proxy Proxy}
64116      * indicates exist. This will usually differ from {@link #getCount} when using paging - getCount returns the
64117      * number of records loaded into the Store at the moment, getTotalCount returns the number of records that
64118      * could be loaded into the Store if the Store contained all data
64119      * @return {Number} The total number of Model instances available via the Proxy
64120      */
64121     getTotalCount: function() {
64122         return this.totalCount;
64123     },
64124
64125     /**
64126      * Get the Record at the specified index.
64127      * @param {Number} index The index of the Record to find.
64128      * @return {Ext.data.Model} The Record at the passed index. Returns undefined if not found.
64129      */
64130     getAt: function(index) {
64131         return this.data.getAt(index);
64132     },
64133
64134     /**
64135      * Returns a range of Records between specified indices.
64136      * @param {Number} startIndex (optional) The starting index (defaults to 0)
64137      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
64138      * @return {Ext.data.Model[]} An array of Records
64139      */
64140     getRange: function(start, end) {
64141         return this.data.getRange(start, end);
64142     },
64143
64144     /**
64145      * Get the Record with the specified id.
64146      * @param {String} id The id of the Record to find.
64147      * @return {Ext.data.Model} The Record with the passed id. Returns undefined if not found.
64148      */
64149     getById: function(id) {
64150         return (this.snapshot || this.data).findBy(function(record) {
64151             return record.getId() === id;
64152         });
64153     },
64154
64155     /**
64156      * Get the index within the cache of the passed Record.
64157      * @param {Ext.data.Model} record The Ext.data.Model object to find.
64158      * @return {Number} The index of the passed Record. Returns -1 if not found.
64159      */
64160     indexOf: function(record) {
64161         return this.data.indexOf(record);
64162     },
64163
64164
64165     /**
64166      * Get the index within the entire dataset. From 0 to the totalCount.
64167      * @param {Ext.data.Model} record The Ext.data.Model object to find.
64168      * @return {Number} The index of the passed Record. Returns -1 if not found.
64169      */
64170     indexOfTotal: function(record) {
64171         return record.index || this.indexOf(record);
64172     },
64173
64174     /**
64175      * Get the index within the cache of the Record with the passed id.
64176      * @param {String} id The id of the Record to find.
64177      * @return {Number} The index of the Record. Returns -1 if not found.
64178      */
64179     indexOfId: function(id) {
64180         return this.data.indexOfKey(id);
64181     },
64182         
64183     /**
64184      * Remove all items from the store.
64185      * @param {Boolean} silent Prevent the `clear` event from being fired.
64186      */
64187     removeAll: function(silent) {
64188         var me = this;
64189
64190         me.clearData();
64191         if (me.snapshot) {
64192             me.snapshot.clear();
64193         }
64194         if (silent !== true) {
64195             me.fireEvent('clear', me);
64196         }
64197     },
64198
64199     /*
64200      * Aggregation methods
64201      */
64202
64203     /**
64204      * Convenience function for getting the first model instance in the store
64205      * @param {Boolean} grouped (Optional) True to perform the operation for each group
64206      * in the store. The value returned will be an object literal with the key being the group
64207      * name and the first record being the value. The grouped parameter is only honored if
64208      * the store has a groupField.
64209      * @return {Ext.data.Model/undefined} The first model instance in the store, or undefined
64210      */
64211     first: function(grouped) {
64212         var me = this;
64213
64214         if (grouped && me.isGrouped()) {
64215             return me.aggregate(function(records) {
64216                 return records.length ? records[0] : undefined;
64217             }, me, true);
64218         } else {
64219             return me.data.first();
64220         }
64221     },
64222
64223     /**
64224      * Convenience function for getting the last model instance in the store
64225      * @param {Boolean} grouped (Optional) True to perform the operation for each group
64226      * in the store. The value returned will be an object literal with the key being the group
64227      * name and the last record being the value. The grouped parameter is only honored if
64228      * the store has a groupField.
64229      * @return {Ext.data.Model/undefined} The last model instance in the store, or undefined
64230      */
64231     last: function(grouped) {
64232         var me = this;
64233
64234         if (grouped && me.isGrouped()) {
64235             return me.aggregate(function(records) {
64236                 var len = records.length;
64237                 return len ? records[len - 1] : undefined;
64238             }, me, true);
64239         } else {
64240             return me.data.last();
64241         }
64242     },
64243
64244     /**
64245      * Sums the value of <tt>property</tt> for each {@link Ext.data.Model record} between <tt>start</tt>
64246      * and <tt>end</tt> and returns the result.
64247      * @param {String} field A field in each record
64248      * @param {Boolean} grouped (Optional) True to perform the operation for each group
64249      * in the store. The value returned will be an object literal with the key being the group
64250      * name and the sum for that group being the value. The grouped parameter is only honored if
64251      * the store has a groupField.
64252      * @return {Number} The sum
64253      */
64254     sum: function(field, grouped) {
64255         var me = this;
64256
64257         if (grouped && me.isGrouped()) {
64258             return me.aggregate(me.getSum, me, true, [field]);
64259         } else {
64260             return me.getSum(me.data.items, field);
64261         }
64262     },
64263
64264     // @private, see sum
64265     getSum: function(records, field) {
64266         var total = 0,
64267             i = 0,
64268             len = records.length;
64269
64270         for (; i < len; ++i) {
64271             total += records[i].get(field);
64272         }
64273
64274         return total;
64275     },
64276
64277     /**
64278      * Gets the count of items in the store.
64279      * @param {Boolean} grouped (Optional) True to perform the operation for each group
64280      * in the store. The value returned will be an object literal with the key being the group
64281      * name and the count for each group being the value. The grouped parameter is only honored if
64282      * the store has a groupField.
64283      * @return {Number} the count
64284      */
64285     count: function(grouped) {
64286         var me = this;
64287
64288         if (grouped && me.isGrouped()) {
64289             return me.aggregate(function(records) {
64290                 return records.length;
64291             }, me, true);
64292         } else {
64293             return me.getCount();
64294         }
64295     },
64296
64297     /**
64298      * Gets the minimum value in the store.
64299      * @param {String} field The field in each record
64300      * @param {Boolean} grouped (Optional) True to perform the operation for each group
64301      * in the store. The value returned will be an object literal with the key being the group
64302      * name and the minimum in the group being the value. The grouped parameter is only honored if
64303      * the store has a groupField.
64304      * @return {Mixed/undefined} The minimum value, if no items exist, undefined.
64305      */
64306     min: function(field, grouped) {
64307         var me = this;
64308
64309         if (grouped && me.isGrouped()) {
64310             return me.aggregate(me.getMin, me, true, [field]);
64311         } else {
64312             return me.getMin(me.data.items, field);
64313         }
64314     },
64315
64316     // @private, see min
64317     getMin: function(records, field){
64318         var i = 1,
64319             len = records.length,
64320             value, min;
64321
64322         if (len > 0) {
64323             min = records[0].get(field);
64324         }
64325
64326         for (; i < len; ++i) {
64327             value = records[i].get(field);
64328             if (value < min) {
64329                 min = value;
64330             }
64331         }
64332         return min;
64333     },
64334
64335     /**
64336      * Gets the maximum value in the store.
64337      * @param {String} field The field in each record
64338      * @param {Boolean} grouped (Optional) True to perform the operation for each group
64339      * in the store. The value returned will be an object literal with the key being the group
64340      * name and the maximum in the group being the value. The grouped parameter is only honored if
64341      * the store has a groupField.
64342      * @return {Mixed/undefined} The maximum value, if no items exist, undefined.
64343      */
64344     max: function(field, grouped) {
64345         var me = this;
64346
64347         if (grouped && me.isGrouped()) {
64348             return me.aggregate(me.getMax, me, true, [field]);
64349         } else {
64350             return me.getMax(me.data.items, field);
64351         }
64352     },
64353
64354     // @private, see max
64355     getMax: function(records, field) {
64356         var i = 1,
64357             len = records.length,
64358             value,
64359             max;
64360
64361         if (len > 0) {
64362             max = records[0].get(field);
64363         }
64364
64365         for (; i < len; ++i) {
64366             value = records[i].get(field);
64367             if (value > max) {
64368                 max = value;
64369             }
64370         }
64371         return max;
64372     },
64373
64374     /**
64375      * Gets the average value in the store.
64376      * @param {String} field The field in each record
64377      * @param {Boolean} grouped (Optional) True to perform the operation for each group
64378      * in the store. The value returned will be an object literal with the key being the group
64379      * name and the group average being the value. The grouped parameter is only honored if
64380      * the store has a groupField.
64381      * @return {Mixed/undefined} The average value, if no items exist, 0.
64382      */
64383     average: function(field, grouped) {
64384         var me = this;
64385         if (grouped && me.isGrouped()) {
64386             return me.aggregate(me.getAverage, me, true, [field]);
64387         } else {
64388             return me.getAverage(me.data.items, field);
64389         }
64390     },
64391
64392     // @private, see average
64393     getAverage: function(records, field) {
64394         var i = 0,
64395             len = records.length,
64396             sum = 0;
64397
64398         if (records.length > 0) {
64399             for (; i < len; ++i) {
64400                 sum += records[i].get(field);
64401             }
64402             return sum / len;
64403         }
64404         return 0;
64405     },
64406
64407     /**
64408      * Runs the aggregate function for all the records in the store.
64409      * @param {Function} fn The function to execute. The function is called with a single parameter,
64410      * an array of records for that group.
64411      * @param {Object} scope (optional) The scope to execute the function in. Defaults to the store.
64412      * @param {Boolean} grouped (Optional) True to perform the operation for each group
64413      * in the store. The value returned will be an object literal with the key being the group
64414      * name and the group average being the value. The grouped parameter is only honored if
64415      * the store has a groupField.
64416      * @param {Array} args (optional) Any arguments to append to the function call
64417      * @return {Object} An object literal with the group names and their appropriate values.
64418      */
64419     aggregate: function(fn, scope, grouped, args) {
64420         args = args || [];
64421         if (grouped && this.isGrouped()) {
64422             var groups = this.getGroups(),
64423                 i = 0,
64424                 len = groups.length,
64425                 out = {},
64426                 group;
64427
64428             for (; i < len; ++i) {
64429                 group = groups[i];
64430                 out[group.name] = fn.apply(scope || this, [group.children].concat(args));
64431             }
64432             return out;
64433         } else {
64434             return fn.apply(scope || this, [this.data.items].concat(args));
64435         }
64436     }
64437 });
64438
64439 /**
64440  * @author Ed Spencer
64441  * @class Ext.data.JsonStore
64442  * @extends Ext.data.Store
64443  * @ignore
64444  *
64445  * <p>Small helper class to make creating {@link Ext.data.Store}s from JSON data easier.
64446  * A JsonStore will be automatically configured with a {@link Ext.data.reader.Json}.</p>
64447  *
64448  * <p>A store configuration would be something like:</p>
64449  *
64450 <pre><code>
64451 var store = new Ext.data.JsonStore({
64452     // store configs
64453     autoDestroy: true,
64454     storeId: 'myStore'
64455
64456     proxy: {
64457         type: 'ajax',
64458         url: 'get-images.php',
64459         reader: {
64460             type: 'json',
64461             root: 'images',
64462             idProperty: 'name'
64463         }
64464     },
64465
64466     //alternatively, a {@link Ext.data.Model} name can be given (see {@link Ext.data.Store} for an example)
64467     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
64468 });
64469 </code></pre>
64470  *
64471  * <p>This store is configured to consume a returned object of the form:<pre><code>
64472 {
64473     images: [
64474         {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
64475         {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
64476     ]
64477 }
64478 </code></pre>
64479  *
64480  * <p>An object literal of this form could also be used as the {@link #data} config option.</p>
64481  *
64482  * @constructor
64483  * @param {Object} config
64484  * @xtype jsonstore
64485  */
64486 Ext.define('Ext.data.JsonStore',  {
64487     extend: 'Ext.data.Store',
64488     alias: 'store.json',
64489
64490     /**
64491      * @cfg {Ext.data.DataReader} reader @hide
64492      */
64493     constructor: function(config) {
64494         config = config || {};
64495
64496         Ext.applyIf(config, {
64497             proxy: {
64498                 type  : 'ajax',
64499                 reader: 'json',
64500                 writer: 'json'
64501             }
64502         });
64503
64504         this.callParent([config]);
64505     }
64506 });
64507
64508 /**
64509  * @class Ext.chart.axis.Time
64510  * @extends Ext.chart.axis.Axis
64511  *
64512  * A type of axis whose units are measured in time values. Use this axis
64513  * for listing dates that you will want to group or dynamically change.
64514  * If you just want to display dates as categories then use the
64515  * Category class for axis instead.
64516  *
64517  * For example:
64518  *
64519   <pre><code>
64520     axes: [{
64521         type: 'Time',
64522         position: 'bottom',
64523         fields: 'date',
64524         title: 'Day',
64525         dateFormat: 'M d',
64526         groupBy: 'year,month,day',
64527         aggregateOp: 'sum',
64528
64529         constrain: true,
64530         fromDate: new Date('1/1/11'),
64531         toDate: new Date('1/7/11')
64532     }]
64533   </code></pre>
64534  *
64535  * In this example we're creating a time axis that has as title <em>Day</em>.
64536  * The field the axis is bound to is <em>date</em>.
64537  * The date format to use to display the text for the axis labels is <em>M d</em>
64538  * which is a three letter month abbreviation followed by the day number.
64539  * The time axis will show values for dates betwee <em>fromDate</em> and <em>toDate</em>.
64540  * Since <em>constrain</em> is set to true all other values for other dates not between
64541  * the fromDate and toDate will not be displayed.
64542  * 
64543  * @constructor
64544  */
64545 Ext.define('Ext.chart.axis.Time', {
64546
64547     /* Begin Definitions */
64548
64549     extend: 'Ext.chart.axis.Category',
64550
64551     alternateClassName: 'Ext.chart.TimeAxis',
64552
64553     alias: 'axis.time',
64554
64555     requires: ['Ext.data.Store', 'Ext.data.JsonStore'],
64556
64557     /* End Definitions */
64558
64559      /**
64560       * The minimum value drawn by the axis. If not set explicitly, the axis
64561       * minimum will be calculated automatically.
64562       * @property calculateByLabelSize
64563       * @type Boolean
64564       */
64565     calculateByLabelSize: true,
64566     
64567      /**
64568      * Indicates the format the date will be rendered on. 
64569      * For example: 'M d' will render the dates as 'Jan 30', etc.
64570       *
64571      * @property dateFormat
64572      * @type {String|Boolean}
64573       */
64574     dateFormat: false,
64575     
64576      /**
64577      * Indicates the time unit to use for each step. Can be 'day', 'month', 'year' or a comma-separated combination of all of them.
64578      * Default's 'year,month,day'.
64579      *
64580      * @property timeUnit
64581      * @type {String}
64582      */
64583     groupBy: 'year,month,day',
64584     
64585     /**
64586      * Aggregation operation when grouping. Possible options are 'sum', 'avg', 'max', 'min'. Default's 'sum'.
64587      * 
64588      * @property aggregateOp
64589      * @type {String}
64590       */
64591     aggregateOp: 'sum',
64592     
64593     /**
64594      * The starting date for the time axis.
64595      * @property fromDate
64596      * @type Date
64597      */
64598     fromDate: false,
64599     
64600     /**
64601      * The ending date for the time axis.
64602      * @property toDate
64603      * @type Date
64604      */
64605     toDate: false,
64606     
64607     /**
64608      * An array with two components: The first is the unit of the step (day, month, year, etc). The second one is the number of units for the step (1, 2, etc.).
64609      * Default's [Ext.Date.DAY, 1].
64610      * 
64611      * @property step 
64612      * @type Array
64613      */
64614     step: [Ext.Date.DAY, 1],
64615     
64616     /**
64617      * If true, the values of the chart will be rendered only if they belong between the fromDate and toDate. 
64618      * If false, the time axis will adapt to the new values by adding/removing steps.
64619      * Default's [Ext.Date.DAY, 1].
64620      * 
64621      * @property constrain 
64622      * @type Boolean
64623      */
64624     constrain: false,
64625     
64626     // @private a wrapper for date methods.
64627     dateMethods: {
64628         'year': function(date) {
64629             return date.getFullYear();
64630         },
64631         'month': function(date) {
64632             return date.getMonth() + 1;
64633         },
64634         'day': function(date) {
64635             return date.getDate();
64636         },
64637         'hour': function(date) {
64638             return date.getHours();
64639         },
64640         'minute': function(date) {
64641             return date.getMinutes();
64642         },
64643         'second': function(date) {
64644             return date.getSeconds();
64645         },
64646         'millisecond': function(date) {
64647             return date.getMilliseconds();
64648         }
64649     },
64650     
64651     // @private holds aggregate functions.
64652     aggregateFn: (function() {
64653         var etype = (function() {
64654             var rgxp = /^\[object\s(.*)\]$/,
64655                 toString = Object.prototype.toString;
64656             return function(e) {
64657                 return toString.call(e).match(rgxp)[1];
64658             };
64659         })();
64660         return {
64661             'sum': function(list) {
64662                 var i = 0, l = list.length, acum = 0;
64663                 if (!list.length || etype(list[0]) != 'Number') {
64664                     return list[0];
64665                 }
64666                 for (; i < l; i++) {
64667                     acum += list[i];
64668                 }
64669                 return acum;
64670             },
64671             'max': function(list) {
64672                 if (!list.length || etype(list[0]) != 'Number') {
64673                     return list[0];
64674                 }
64675                 return Math.max.apply(Math, list);
64676             },
64677             'min': function(list) {
64678                 if (!list.length || etype(list[0]) != 'Number') {
64679                     return list[0];
64680                 }
64681                 return Math.min.apply(Math, list);
64682             },
64683             'avg': function(list) {
64684                 var i = 0, l = list.length, acum = 0;
64685                 if (!list.length || etype(list[0]) != 'Number') {
64686                     return list[0];
64687                 }
64688                 for (; i < l; i++) {
64689                     acum += list[i];
64690                 }
64691                 return acum / l;
64692             }
64693         };
64694     })(),
64695     
64696     // @private normalized the store to fill date gaps in the time interval.
64697     constrainDates: function() {
64698         var fromDate = Ext.Date.clone(this.fromDate),
64699             toDate = Ext.Date.clone(this.toDate),
64700             step = this.step,
64701             field = this.fields,
64702             store = this.chart.store,
64703             record, recObj, fieldNames = [],
64704             newStore = Ext.create('Ext.data.Store', {
64705                 model: store.model
64706             });
64707         
64708         var getRecordByDate = (function() {
64709             var index = 0, l = store.getCount();
64710             return function(date) {
64711                 var rec, recDate;
64712                 for (; index < l; index++) {
64713                     rec = store.getAt(index);
64714                     recDate = rec.get(field);
64715                     if (+recDate > +date) {
64716                         return false;
64717                     } else if (+recDate == +date) {
64718                         return rec;
64719                     }
64720                 }
64721                 return false;
64722             };
64723         })();
64724         
64725         if (!this.constrain) {
64726             this.chart.filteredStore = this.chart.store;
64727             return;
64728         }
64729
64730         while(+fromDate <= +toDate) {
64731             record = getRecordByDate(fromDate);
64732             recObj = {};
64733             if (record) {
64734                 newStore.add(record.data);
64735             } else {
64736                 newStore.model.prototype.fields.each(function(f) {
64737                     recObj[f.name] = false;
64738                 });
64739                 recObj.date = fromDate;
64740                 newStore.add(recObj);
64741             }
64742             fromDate = Ext.Date.add(fromDate, step[0], step[1]);
64743         }
64744          
64745         this.chart.filteredStore = newStore;
64746     },
64747     
64748     // @private aggregates values if multiple store elements belong to the same time step.
64749     aggregate: function() {
64750         var aggStore = {}, 
64751             aggKeys = [], key, value,
64752             op = this.aggregateOp,
64753             field = this.fields, i,
64754             fields = this.groupBy.split(','),
64755             curField,
64756             recFields = [],
64757             recFieldsLen = 0,
64758             obj,
64759             dates = [],
64760             json = [],
64761             l = fields.length,
64762             dateMethods = this.dateMethods,
64763             aggregateFn = this.aggregateFn,
64764             store = this.chart.filteredStore || this.chart.store;
64765         
64766         store.each(function(rec) {
64767             //get all record field names in a simple array
64768             if (!recFields.length) {
64769                 rec.fields.each(function(f) {
64770                     recFields.push(f.name);
64771                 });
64772                 recFieldsLen = recFields.length;
64773             }
64774             //get record date value
64775             value = rec.get(field);
64776             //generate key for grouping records
64777             for (i = 0; i < l; i++) {
64778                 if (i == 0) {
64779                     key = String(dateMethods[fields[i]](value));
64780                 } else {
64781                     key += '||' + dateMethods[fields[i]](value);
64782                 }
64783             }
64784             //get aggregation record from hash
64785             if (key in aggStore) {
64786                 obj = aggStore[key];
64787             } else {
64788                 obj = aggStore[key] = {};
64789                 aggKeys.push(key);
64790                 dates.push(value);
64791             }
64792             //append record values to an aggregation record
64793             for (i = 0; i < recFieldsLen; i++) {
64794                 curField = recFields[i];
64795                 if (!obj[curField]) {
64796                     obj[curField] = [];
64797                 }
64798                 if (rec.get(curField) !== undefined) {
64799                     obj[curField].push(rec.get(curField));
64800                 }
64801             }
64802         });
64803         //perform aggregation operations on fields
64804         for (key in aggStore) {
64805             obj = aggStore[key];
64806             for (i = 0; i < recFieldsLen; i++) {
64807                 curField = recFields[i];
64808                 obj[curField] = aggregateFn[op](obj[curField]);
64809             }
64810             json.push(obj);
64811         }
64812         this.chart.substore = Ext.create('Ext.data.JsonStore', {
64813             fields: recFields,
64814             data: json
64815         });
64816         
64817         this.dates = dates;
64818     },
64819     
64820     // @private creates a label array to be used as the axis labels.
64821      setLabels: function() {
64822         var store = this.chart.substore,
64823             fields = this.fields,
64824             format = this.dateFormat,
64825             labels, i, dates = this.dates,
64826             formatFn = Ext.Date.format;
64827         this.labels = labels = [];
64828         store.each(function(record, i) {
64829             if (!format) {
64830                 labels.push(record.get(fields));
64831             } else {
64832                 labels.push(formatFn(dates[i], format));
64833             }
64834          }, this);
64835      },
64836
64837     processView: function() {
64838          //TODO(nico): fix this eventually...
64839          if (this.constrain) {
64840              this.constrainDates();
64841              this.aggregate();
64842              this.chart.substore = this.chart.filteredStore;
64843          } else {
64844              this.aggregate();
64845          }
64846     },
64847
64848      // @private modifies the store and creates the labels for the axes.
64849      applyData: function() {
64850         this.setLabels();
64851         var count = this.chart.substore.getCount();
64852          return {
64853              from: 0,
64854              to: count,
64855              steps: count - 1,
64856              step: 1
64857          };
64858      }
64859  });
64860
64861
64862 /**
64863  * @class Ext.chart.series.Series
64864  * 
64865  * Series is the abstract class containing the common logic to all chart series. Series includes 
64866  * methods from Labels, Highlights, Tips and Callouts mixins. This class implements the logic of handling 
64867  * mouse events, animating, hiding, showing all elements and returning the color of the series to be used as a legend item.
64868  *
64869  * ## Listeners
64870  *
64871  * The series class supports listeners via the Observable syntax. Some of these listeners are:
64872  *
64873  *  - `itemmouseup` When the user interacts with a marker.
64874  *  - `itemmousedown` When the user interacts with a marker.
64875  *  - `itemmousemove` When the user iteracts with a marker.
64876  *  - `afterrender` Will be triggered when the animation ends or when the series has been rendered completely.
64877  *
64878  * For example:
64879  *
64880  *     series: [{
64881  *             type: 'column',
64882  *             axis: 'left',
64883  *             listeners: {
64884  *                     'afterrender': function() {
64885  *                             console('afterrender');
64886  *                     }
64887  *             },
64888  *             xField: 'category',
64889  *             yField: 'data1'
64890  *     }]
64891  *     
64892  */
64893 Ext.define('Ext.chart.series.Series', {
64894
64895     /* Begin Definitions */
64896
64897     mixins: {
64898         observable: 'Ext.util.Observable',
64899         labels: 'Ext.chart.Label',
64900         highlights: 'Ext.chart.Highlight',
64901         tips: 'Ext.chart.Tip',
64902         callouts: 'Ext.chart.Callout'
64903     },
64904
64905     /* End Definitions */
64906
64907     /**
64908      * @cfg {Boolean|Object} highlight
64909      * If set to `true` it will highlight the markers or the series when hovering
64910      * with the mouse. This parameter can also be an object with the same style
64911      * properties you would apply to a {@link Ext.draw.Sprite} to apply custom
64912      * styles to markers and series.
64913      */
64914
64915     /**
64916      * @cfg {Object} tips
64917      * Add tooltips to the visualization's markers. The options for the tips are the
64918      * same configuration used with {@link Ext.tip.ToolTip}. For example:
64919      *
64920      *     tips: {
64921      *       trackMouse: true,
64922      *       width: 140,
64923      *       height: 28,
64924      *       renderer: function(storeItem, item) {
64925      *         this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' views');
64926      *       }
64927      *     },
64928      */
64929
64930     /**
64931      * @cfg {String} type
64932      * The type of series. Set in subclasses.
64933      */
64934     type: null,
64935
64936     /**
64937      * @cfg {String} title
64938      * The human-readable name of the series.
64939      */
64940     title: null,
64941
64942     /**
64943      * @cfg {Boolean} showInLegend
64944      * Whether to show this series in the legend.
64945      */
64946     showInLegend: true,
64947
64948     /**
64949      * @cfg {Function} renderer
64950      * A function that can be overridden to set custom styling properties to each rendered element.
64951      * Passes in (sprite, record, attributes, index, store) to the function.
64952      */
64953     renderer: function(sprite, record, attributes, index, store) {
64954         return attributes;
64955     },
64956
64957     /**
64958      * @cfg {Array} shadowAttributes
64959      * An array with shadow attributes
64960      */
64961     shadowAttributes: null,
64962     
64963     //@private triggerdrawlistener flag
64964     triggerAfterDraw: false,
64965
64966     /**
64967      * @cfg {Object} listeners  
64968      * An (optional) object with event callbacks. All event callbacks get the target *item* as first parameter. The callback functions are:
64969      *  
64970      *  <ul>
64971      *      <li>itemmouseover</li>
64972      *      <li>itemmouseout</li>
64973      *      <li>itemmousedown</li>
64974      *      <li>itemmouseup</li>
64975      *  </ul>
64976      */
64977     
64978     constructor: function(config) {
64979         var me = this;
64980         if (config) {
64981             Ext.apply(me, config);
64982         }
64983         
64984         me.shadowGroups = [];
64985         
64986         me.mixins.labels.constructor.call(me, config);
64987         me.mixins.highlights.constructor.call(me, config);
64988         me.mixins.tips.constructor.call(me, config);
64989         me.mixins.callouts.constructor.call(me, config);
64990
64991         me.addEvents({
64992             scope: me,
64993             itemmouseover: true,
64994             itemmouseout: true,
64995             itemmousedown: true,
64996             itemmouseup: true,
64997             mouseleave: true,
64998             afterdraw: true,
64999
65000             /**
65001              * @event titlechange
65002              * Fires when the series title is changed via {@link #setTitle}.
65003              * @param {String} title The new title value
65004              * @param {Number} index The index in the collection of titles
65005              */
65006             titlechange: true
65007         });
65008
65009         me.mixins.observable.constructor.call(me, config);
65010
65011         me.on({
65012             scope: me,
65013             itemmouseover: me.onItemMouseOver,
65014             itemmouseout: me.onItemMouseOut,
65015             mouseleave: me.onMouseLeave
65016         });
65017     },
65018
65019     // @private set the bbox and clipBox for the series
65020     setBBox: function(noGutter) {
65021         var me = this,
65022             chart = me.chart,
65023             chartBBox = chart.chartBBox,
65024             gutterX = noGutter ? 0 : chart.maxGutter[0],
65025             gutterY = noGutter ? 0 : chart.maxGutter[1],
65026             clipBox, bbox;
65027
65028         clipBox = {
65029             x: chartBBox.x,
65030             y: chartBBox.y,
65031             width: chartBBox.width,
65032             height: chartBBox.height
65033         };
65034         me.clipBox = clipBox;
65035
65036         bbox = {
65037             x: (clipBox.x + gutterX) - (chart.zoom.x * chart.zoom.width),
65038             y: (clipBox.y + gutterY) - (chart.zoom.y * chart.zoom.height),
65039             width: (clipBox.width - (gutterX * 2)) * chart.zoom.width,
65040             height: (clipBox.height - (gutterY * 2)) * chart.zoom.height
65041         };
65042         me.bbox = bbox;
65043     },
65044
65045     // @private set the animation for the sprite
65046     onAnimate: function(sprite, attr) {
65047         var me = this;
65048         sprite.stopAnimation();
65049         if (me.triggerAfterDraw) {
65050             return sprite.animate(Ext.applyIf(attr, me.chart.animate));
65051         } else {
65052             me.triggerAfterDraw = true;
65053             return sprite.animate(Ext.apply(Ext.applyIf(attr, me.chart.animate), {
65054                 listeners: {
65055                     'afteranimate': function() {
65056                         me.triggerAfterDraw = false;
65057                         me.fireEvent('afterrender');
65058                     }    
65059                 }    
65060             }));
65061         }
65062     },
65063     
65064     // @private return the gutter.
65065     getGutters: function() {
65066         return [0, 0];
65067     },
65068
65069     // @private wrapper for the itemmouseover event.
65070     onItemMouseOver: function(item) { 
65071         var me = this;
65072         if (item.series === me) {
65073             if (me.highlight) {
65074                 me.highlightItem(item);
65075             }
65076             if (me.tooltip) {
65077                 me.showTip(item);
65078             }
65079         }
65080     },
65081
65082     // @private wrapper for the itemmouseout event.
65083     onItemMouseOut: function(item) {
65084         var me = this;
65085         if (item.series === me) {
65086             me.unHighlightItem();
65087             if (me.tooltip) {
65088                 me.hideTip(item);
65089             }
65090         }
65091     },
65092
65093     // @private wrapper for the mouseleave event.
65094     onMouseLeave: function() {
65095         var me = this;
65096         me.unHighlightItem();
65097         if (me.tooltip) {
65098             me.hideTip();
65099         }
65100     },
65101
65102     /**
65103      * For a given x/y point relative to the Surface, find a corresponding item from this
65104      * series, if any.
65105      * @param {Number} x
65106      * @param {Number} y
65107      * @return {Object} An object describing the item, or null if there is no matching item. The exact contents of
65108      *                  this object will vary by series type, but should always contain at least the following:
65109      *                  <ul>
65110      *                    <li>{Ext.chart.series.Series} series - the Series object to which the item belongs</li>
65111      *                    <li>{Object} value - the value(s) of the item's data point</li>
65112      *                    <li>{Array} point - the x/y coordinates relative to the chart box of a single point
65113      *                        for this data item, which can be used as e.g. a tooltip anchor point.</li>
65114      *                    <li>{Ext.draw.Sprite} sprite - the item's rendering Sprite.
65115      *                  </ul>
65116      */
65117     getItemForPoint: function(x, y) {
65118         //if there are no items to query just return null.
65119         if (!this.items || !this.items.length || this.seriesIsHidden) {
65120             return null;
65121         }
65122         var me = this,
65123             items = me.items,
65124             bbox = me.bbox,
65125             item, i, ln;
65126         // Check bounds
65127         if (!Ext.draw.Draw.withinBox(x, y, bbox)) {
65128             return null;
65129         }
65130         for (i = 0, ln = items.length; i < ln; i++) {
65131             if (items[i] && this.isItemInPoint(x, y, items[i], i)) {
65132                 return items[i];
65133             }
65134         }
65135         
65136         return null;
65137     },
65138     
65139     isItemInPoint: function(x, y, item, i) {
65140         return false;
65141     },
65142
65143     /**
65144      * Hides all the elements in the series.
65145      */
65146     hideAll: function() {
65147         var me = this,
65148             items = me.items,
65149             item, len, i, sprite;
65150
65151         me.seriesIsHidden = true;
65152         me._prevShowMarkers = me.showMarkers;
65153
65154         me.showMarkers = false;
65155         //hide all labels
65156         me.hideLabels(0);
65157         //hide all sprites
65158         for (i = 0, len = items.length; i < len; i++) {
65159             item = items[i];
65160             sprite = item.sprite;
65161             if (sprite) {
65162                 sprite.setAttributes({
65163                     hidden: true
65164                 }, true);
65165             }
65166         }
65167     },
65168
65169     /**
65170      * Shows all the elements in the series.
65171      */
65172     showAll: function() {
65173         var me = this,
65174             prevAnimate = me.chart.animate;
65175         me.chart.animate = false;
65176         me.seriesIsHidden = false;
65177         me.showMarkers = me._prevShowMarkers;
65178         me.drawSeries();
65179         me.chart.animate = prevAnimate;
65180     },
65181     
65182     /**
65183      * Returns a string with the color to be used for the series legend item. 
65184      */
65185     getLegendColor: function(index) {
65186         var me = this, fill, stroke;
65187         if (me.seriesStyle) {
65188             fill = me.seriesStyle.fill;
65189             stroke = me.seriesStyle.stroke;
65190             if (fill && fill != 'none') {
65191                 return fill;
65192             }
65193             return stroke;
65194         }
65195         return '#000';
65196     },
65197     
65198     /**
65199      * Checks whether the data field should be visible in the legend
65200      * @private
65201      * @param {Number} index The index of the current item
65202      */
65203     visibleInLegend: function(index){
65204         var excludes = this.__excludes;
65205         if (excludes) {
65206             return !excludes[index];
65207         }
65208         return !this.seriesIsHidden;
65209     },
65210
65211     /**
65212      * Changes the value of the {@link #title} for the series.
65213      * Arguments can take two forms:
65214      * <ul>
65215      * <li>A single String value: this will be used as the new single title for the series (applies
65216      * to series with only one yField)</li>
65217      * <li>A numeric index and a String value: this will set the title for a single indexed yField.</li>
65218      * </ul>
65219      * @param {Number} index
65220      * @param {String} title
65221      */
65222     setTitle: function(index, title) {
65223         var me = this,
65224             oldTitle = me.title;
65225
65226         if (Ext.isString(index)) {
65227             title = index;
65228             index = 0;
65229         }
65230
65231         if (Ext.isArray(oldTitle)) {
65232             oldTitle[index] = title;
65233         } else {
65234             me.title = title;
65235         }
65236
65237         me.fireEvent('titlechange', title, index);
65238     }
65239 });
65240
65241 /**
65242  * @class Ext.chart.series.Cartesian
65243  * @extends Ext.chart.series.Series
65244  *
65245  * Common base class for series implementations which plot values using x/y coordinates.
65246  *
65247  * @constructor
65248  */
65249 Ext.define('Ext.chart.series.Cartesian', {
65250
65251     /* Begin Definitions */
65252
65253     extend: 'Ext.chart.series.Series',
65254
65255     alternateClassName: ['Ext.chart.CartesianSeries', 'Ext.chart.CartesianChart'],
65256
65257     /* End Definitions */
65258
65259     /**
65260      * The field used to access the x axis value from the items from the data
65261      * source.
65262      *
65263      * @cfg xField
65264      * @type String
65265      */
65266     xField: null,
65267
65268     /**
65269      * The field used to access the y-axis value from the items from the data
65270      * source.
65271      *
65272      * @cfg yField
65273      * @type String
65274      */
65275     yField: null,
65276
65277     /**
65278      * Indicates which axis the series will bind to
65279      *
65280      * @property axis
65281      * @type String
65282      */
65283     axis: 'left'
65284 });
65285
65286 /**
65287  * @class Ext.chart.series.Area
65288  * @extends Ext.chart.series.Cartesian
65289  * 
65290  <p>
65291     Creates a Stacked Area Chart. The stacked area chart is useful when displaying multiple aggregated layers of information.
65292     As with all other series, the Area Series must be appended in the *series* Chart array configuration. See the Chart 
65293     documentation for more information. A typical configuration object for the area series could be:
65294  </p>
65295 {@img Ext.chart.series.Area/Ext.chart.series.Area.png Ext.chart.series.Area chart series} 
65296   <pre><code>
65297    var store = Ext.create('Ext.data.JsonStore', {
65298         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
65299         data: [
65300             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
65301             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
65302             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
65303             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
65304             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}                                                
65305         ]
65306     });
65307     
65308     Ext.create('Ext.chart.Chart', {
65309         renderTo: Ext.getBody(),
65310         width: 500,
65311         height: 300,
65312         store: store,
65313         axes: [{
65314             type: 'Numeric',
65315             grid: true,
65316             position: 'left',
65317             fields: ['data1', 'data2', 'data3', 'data4', 'data5'],
65318             title: 'Sample Values',
65319             grid: {
65320                 odd: {
65321                     opacity: 1,
65322                     fill: '#ddd',
65323                     stroke: '#bbb',
65324                     'stroke-width': 1
65325                 }
65326             },
65327             minimum: 0,
65328             adjustMinimumByMajorUnit: 0
65329         }, {
65330             type: 'Category',
65331             position: 'bottom',
65332             fields: ['name'],
65333             title: 'Sample Metrics',
65334             grid: true,
65335             label: {
65336                 rotate: {
65337                     degrees: 315
65338                 }
65339             }
65340         }],
65341         series: [{
65342             type: 'area',
65343             highlight: false,
65344             axis: 'left',
65345             xField: 'name',
65346             yField: ['data1', 'data2', 'data3', 'data4', 'data5'],
65347             style: {
65348                 opacity: 0.93
65349             }
65350         }]
65351     });
65352    </code></pre>
65353  
65354   
65355  <p>
65356   In this configuration we set `area` as the type for the series, set highlighting options to true for highlighting elements on hover, 
65357   take the left axis to measure the data in the area series, set as xField (x values) the name field of each element in the store, 
65358   and as yFields (aggregated layers) seven data fields from the same store. Then we override some theming styles by adding some opacity 
65359   to the style object.
65360  </p>
65361   
65362  * @xtype area
65363  * 
65364  */
65365 Ext.define('Ext.chart.series.Area', {
65366
65367     /* Begin Definitions */
65368
65369     extend: 'Ext.chart.series.Cartesian',
65370     
65371     alias: 'series.area',
65372
65373     requires: ['Ext.chart.axis.Axis', 'Ext.draw.Color', 'Ext.fx.Anim'],
65374
65375     /* End Definitions */
65376
65377     type: 'area',
65378
65379     // @private Area charts are alyways stacked
65380     stacked: true,
65381
65382     /**
65383      * @cfg {Object} style 
65384      * Append styling properties to this object for it to override theme properties.
65385      */
65386     style: {},
65387
65388     constructor: function(config) {
65389         this.callParent(arguments);
65390         var me = this,
65391             surface = me.chart.surface,
65392             i, l;
65393         Ext.apply(me, config, {
65394             __excludes: [],
65395             highlightCfg: {
65396                 lineWidth: 3,
65397                 stroke: '#55c',
65398                 opacity: 0.8,
65399                 color: '#f00'
65400             }
65401         });
65402         if (me.highlight) {
65403             me.highlightSprite = surface.add({
65404                 type: 'path',
65405                 path: ['M', 0, 0],
65406                 zIndex: 1000,
65407                 opacity: 0.3,
65408                 lineWidth: 5,
65409                 hidden: true,
65410                 stroke: '#444'
65411             });
65412         }
65413         me.group = surface.getGroup(me.seriesId);
65414     },
65415
65416     // @private Shrinks dataSets down to a smaller size
65417     shrink: function(xValues, yValues, size) {
65418         var len = xValues.length,
65419             ratio = Math.floor(len / size),
65420             i, j,
65421             xSum = 0,
65422             yCompLen = this.areas.length,
65423             ySum = [],
65424             xRes = [],
65425             yRes = [];
65426         //initialize array
65427         for (j = 0; j < yCompLen; ++j) {
65428             ySum[j] = 0;
65429         }
65430         for (i = 0; i < len; ++i) {
65431             xSum += xValues[i];
65432             for (j = 0; j < yCompLen; ++j) {
65433                 ySum[j] += yValues[i][j];
65434             }
65435             if (i % ratio == 0) {
65436                 //push averages
65437                 xRes.push(xSum/ratio);
65438                 for (j = 0; j < yCompLen; ++j) {
65439                     ySum[j] /= ratio;
65440                 }
65441                 yRes.push(ySum);
65442                 //reset sum accumulators
65443                 xSum = 0;
65444                 for (j = 0, ySum = []; j < yCompLen; ++j) {
65445                     ySum[j] = 0;
65446                 }
65447             }
65448         }
65449         return {
65450             x: xRes,
65451             y: yRes
65452         };
65453     },
65454
65455     // @private Get chart and data boundaries
65456     getBounds: function() {
65457         var me = this,
65458             chart = me.chart,
65459             store = chart.substore || chart.store,
65460             areas = [].concat(me.yField),
65461             areasLen = areas.length,
65462             xValues = [],
65463             yValues = [],
65464             infinity = Infinity,
65465             minX = infinity,
65466             minY = infinity,
65467             maxX = -infinity,
65468             maxY = -infinity,
65469             math = Math,
65470             mmin = math.min,
65471             mmax = math.max,
65472             bbox, xScale, yScale, xValue, yValue, areaIndex, acumY, ln, sumValues, clipBox, areaElem;
65473
65474         me.setBBox();
65475         bbox = me.bbox;
65476
65477         // Run through the axis
65478         if (me.axis) {
65479             axis = chart.axes.get(me.axis);
65480             if (axis) {
65481                 out = axis.calcEnds();
65482                 minY = out.from || axis.prevMin;
65483                 maxY = mmax(out.to || axis.prevMax, 0);
65484             }
65485         }
65486
65487         if (me.yField && !Ext.isNumber(minY)) {
65488             axis = Ext.create('Ext.chart.axis.Axis', {
65489                 chart: chart,
65490                 fields: [].concat(me.yField)
65491             });
65492             out = axis.calcEnds();
65493             minY = out.from || axis.prevMin;
65494             maxY = mmax(out.to || axis.prevMax, 0);
65495         }
65496
65497         if (!Ext.isNumber(minY)) {
65498             minY = 0;
65499         }
65500         if (!Ext.isNumber(maxY)) {
65501             maxY = 0;
65502         }
65503
65504         store.each(function(record, i) {
65505             xValue = record.get(me.xField);
65506             yValue = [];
65507             if (typeof xValue != 'number') {
65508                 xValue = i;
65509             }
65510             xValues.push(xValue);
65511             acumY = 0;
65512             for (areaIndex = 0; areaIndex < areasLen; areaIndex++) {
65513                 areaElem = record.get(areas[areaIndex]);
65514                 if (typeof areaElem == 'number') {
65515                     minY = mmin(minY, areaElem);
65516                     yValue.push(areaElem);
65517                     acumY += areaElem;
65518                 }
65519             }
65520             minX = mmin(minX, xValue);
65521             maxX = mmax(maxX, xValue);
65522             maxY = mmax(maxY, acumY);
65523             yValues.push(yValue);
65524         }, me);
65525
65526         xScale = bbox.width / (maxX - minX);
65527         yScale = bbox.height / (maxY - minY);
65528
65529         ln = xValues.length;
65530         if ((ln > bbox.width) && me.areas) {
65531             sumValues = me.shrink(xValues, yValues, bbox.width);
65532             xValues = sumValues.x;
65533             yValues = sumValues.y;
65534         }
65535
65536         return {
65537             bbox: bbox,
65538             minX: minX,
65539             minY: minY,
65540             xValues: xValues,
65541             yValues: yValues,
65542             xScale: xScale,
65543             yScale: yScale,
65544             areasLen: areasLen
65545         };
65546     },
65547
65548     // @private Build an array of paths for the chart
65549     getPaths: function() {
65550         var me = this,
65551             chart = me.chart,
65552             store = chart.substore || chart.store,
65553             first = true,
65554             bounds = me.getBounds(),
65555             bbox = bounds.bbox,
65556             items = me.items = [],
65557             componentPaths = [],
65558             componentPath,
65559             paths = [],
65560             i, ln, x, y, xValue, yValue, acumY, areaIndex, prevAreaIndex, areaElem, path;
65561
65562         ln = bounds.xValues.length;
65563         // Start the path
65564         for (i = 0; i < ln; i++) {
65565             xValue = bounds.xValues[i];
65566             yValue = bounds.yValues[i];
65567             x = bbox.x + (xValue - bounds.minX) * bounds.xScale;
65568             acumY = 0;
65569             for (areaIndex = 0; areaIndex < bounds.areasLen; areaIndex++) {
65570                 // Excluded series
65571                 if (me.__excludes[areaIndex]) {
65572                     continue;
65573                 }
65574                 if (!componentPaths[areaIndex]) {
65575                     componentPaths[areaIndex] = [];
65576                 }
65577                 areaElem = yValue[areaIndex];
65578                 acumY += areaElem;
65579                 y = bbox.y + bbox.height - (acumY - bounds.minY) * bounds.yScale;
65580                 if (!paths[areaIndex]) {
65581                     paths[areaIndex] = ['M', x, y];
65582                     componentPaths[areaIndex].push(['L', x, y]);
65583                 } else {
65584                     paths[areaIndex].push('L', x, y);
65585                     componentPaths[areaIndex].push(['L', x, y]);
65586                 }
65587                 if (!items[areaIndex]) {
65588                     items[areaIndex] = {
65589                         pointsUp: [],
65590                         pointsDown: [],
65591                         series: me
65592                     };
65593                 }
65594                 items[areaIndex].pointsUp.push([x, y]);
65595             }
65596         }
65597         
65598         // Close the paths
65599         for (areaIndex = 0; areaIndex < bounds.areasLen; areaIndex++) {
65600             // Excluded series
65601             if (me.__excludes[areaIndex]) {
65602                 continue;
65603             }
65604             path = paths[areaIndex];
65605             // Close bottom path to the axis
65606             if (areaIndex == 0 || first) {
65607                 first = false;
65608                 path.push('L', x, bbox.y + bbox.height,
65609                           'L', bbox.x, bbox.y + bbox.height,
65610                           'Z');
65611             }
65612             // Close other paths to the one before them
65613             else {
65614                 componentPath = componentPaths[prevAreaIndex];
65615                 componentPath.reverse();
65616                 path.push('L', x, componentPath[0][2]);
65617                 for (i = 0; i < ln; i++) {
65618                     path.push(componentPath[i][0],
65619                               componentPath[i][1],
65620                               componentPath[i][2]);
65621                     items[areaIndex].pointsDown[ln -i -1] = [componentPath[i][1], componentPath[i][2]];
65622                 }
65623                 path.push('L', bbox.x, path[2], 'Z');
65624             }
65625             prevAreaIndex = areaIndex;
65626         }
65627         return {
65628             paths: paths,
65629             areasLen: bounds.areasLen
65630         };
65631     },
65632
65633     /**
65634      * Draws the series for the current chart.
65635      */
65636     drawSeries: function() {
65637         var me = this,
65638             chart = me.chart,
65639             store = chart.substore || chart.store,
65640             surface = chart.surface,
65641             animate = chart.animate,
65642             group = me.group,
65643             endLineStyle = Ext.apply(me.seriesStyle, me.style),
65644             colorArrayStyle = me.colorArrayStyle,
65645             colorArrayLength = colorArrayStyle && colorArrayStyle.length || 0,
65646             areaIndex, areaElem, paths, path, rendererAttributes;
65647
65648         me.unHighlightItem();
65649         me.cleanHighlights();
65650
65651         if (!store || !store.getCount()) {
65652             return;
65653         }
65654         
65655         paths = me.getPaths();
65656
65657         if (!me.areas) {
65658             me.areas = [];
65659         }
65660
65661         for (areaIndex = 0; areaIndex < paths.areasLen; areaIndex++) {
65662             // Excluded series
65663             if (me.__excludes[areaIndex]) {
65664                 continue;
65665             }
65666             if (!me.areas[areaIndex]) {
65667                 me.items[areaIndex].sprite = me.areas[areaIndex] = surface.add(Ext.apply({}, {
65668                     type: 'path',
65669                     group: group,
65670                     // 'clip-rect': me.clipBox,
65671                     path: paths.paths[areaIndex],
65672                     stroke: endLineStyle.stroke || colorArrayStyle[areaIndex % colorArrayLength],
65673                     fill: colorArrayStyle[areaIndex % colorArrayLength]
65674                 }, endLineStyle || {}));
65675             }
65676             areaElem = me.areas[areaIndex];
65677             path = paths.paths[areaIndex];
65678             if (animate) {
65679                 //Add renderer to line. There is not a unique record associated with this.
65680                 rendererAttributes = me.renderer(areaElem, false, { 
65681                     path: path,
65682                     // 'clip-rect': me.clipBox,
65683                     fill: colorArrayStyle[areaIndex % colorArrayLength],
65684                     stroke: endLineStyle.stroke || colorArrayStyle[areaIndex % colorArrayLength]
65685                 }, areaIndex, store);
65686                 //fill should not be used here but when drawing the special fill path object
65687                 me.animation = me.onAnimate(areaElem, {
65688                     to: rendererAttributes
65689                 });
65690             } else {
65691                 rendererAttributes = me.renderer(areaElem, false, { 
65692                     path: path,
65693                     // 'clip-rect': me.clipBox,
65694                     hidden: false,
65695                     fill: colorArrayStyle[areaIndex % colorArrayLength],
65696                     stroke: endLineStyle.stroke || colorArrayStyle[areaIndex % colorArrayLength]
65697                 }, areaIndex, store);
65698                 me.areas[areaIndex].setAttributes(rendererAttributes, true);
65699             }
65700         }
65701         me.renderLabels();
65702         me.renderCallouts();
65703     },
65704
65705     // @private
65706     onAnimate: function(sprite, attr) {
65707         sprite.show();
65708         return this.callParent(arguments);
65709     },
65710
65711     // @private
65712     onCreateLabel: function(storeItem, item, i, display) {
65713         var me = this,
65714             group = me.labelsGroup,
65715             config = me.label,
65716             bbox = me.bbox,
65717             endLabelStyle = Ext.apply(config, me.seriesLabelStyle);
65718
65719         return me.chart.surface.add(Ext.apply({
65720             'type': 'text',
65721             'text-anchor': 'middle',
65722             'group': group,
65723             'x': item.point[0],
65724             'y': bbox.y + bbox.height / 2
65725         }, endLabelStyle || {}));
65726     },
65727
65728     // @private
65729     onPlaceLabel: function(label, storeItem, item, i, display, animate, index) {
65730         var me = this,
65731             chart = me.chart,
65732             resizing = chart.resizing,
65733             config = me.label,
65734             format = config.renderer,
65735             field = config.field,
65736             bbox = me.bbox,
65737             x = item.point[0],
65738             y = item.point[1],
65739             bb, width, height;
65740         
65741         label.setAttributes({
65742             text: format(storeItem.get(field[index])),
65743             hidden: true
65744         }, true);
65745         
65746         bb = label.getBBox();
65747         width = bb.width / 2;
65748         height = bb.height / 2;
65749         
65750         x = x - width < bbox.x? bbox.x + width : x;
65751         x = (x + width > bbox.x + bbox.width) ? (x - (x + width - bbox.x - bbox.width)) : x;
65752         y = y - height < bbox.y? bbox.y + height : y;
65753         y = (y + height > bbox.y + bbox.height) ? (y - (y + height - bbox.y - bbox.height)) : y;
65754
65755         if (me.chart.animate && !me.chart.resizing) {
65756             label.show(true);
65757             me.onAnimate(label, {
65758                 to: {
65759                     x: x,
65760                     y: y
65761                 }
65762             });
65763         } else {
65764             label.setAttributes({
65765                 x: x,
65766                 y: y
65767             }, true);
65768             if (resizing) {
65769                 me.animation.on('afteranimate', function() {
65770                     label.show(true);
65771                 });
65772             } else {
65773                 label.show(true);
65774             }
65775         }
65776     },
65777
65778     // @private
65779     onPlaceCallout : function(callout, storeItem, item, i, display, animate, index) {
65780         var me = this,
65781             chart = me.chart,
65782             surface = chart.surface,
65783             resizing = chart.resizing,
65784             config = me.callouts,
65785             items = me.items,
65786             prev = (i == 0) ? false : items[i -1].point,
65787             next = (i == items.length -1) ? false : items[i +1].point,
65788             cur = item.point,
65789             dir, norm, normal, a, aprev, anext,
65790             bbox = callout.label.getBBox(),
65791             offsetFromViz = 30,
65792             offsetToSide = 10,
65793             offsetBox = 3,
65794             boxx, boxy, boxw, boxh,
65795             p, clipRect = me.clipRect,
65796             x, y;
65797
65798         //get the right two points
65799         if (!prev) {
65800             prev = cur;
65801         }
65802         if (!next) {
65803             next = cur;
65804         }
65805         a = (next[1] - prev[1]) / (next[0] - prev[0]);
65806         aprev = (cur[1] - prev[1]) / (cur[0] - prev[0]);
65807         anext = (next[1] - cur[1]) / (next[0] - cur[0]);
65808         
65809         norm = Math.sqrt(1 + a * a);
65810         dir = [1 / norm, a / norm];
65811         normal = [-dir[1], dir[0]];
65812         
65813         //keep the label always on the outer part of the "elbow"
65814         if (aprev > 0 && anext < 0 && normal[1] < 0 || aprev < 0 && anext > 0 && normal[1] > 0) {
65815             normal[0] *= -1;
65816             normal[1] *= -1;
65817         } else if (Math.abs(aprev) < Math.abs(anext) && normal[0] < 0 || Math.abs(aprev) > Math.abs(anext) && normal[0] > 0) {
65818             normal[0] *= -1;
65819             normal[1] *= -1;
65820         }
65821
65822         //position
65823         x = cur[0] + normal[0] * offsetFromViz;
65824         y = cur[1] + normal[1] * offsetFromViz;
65825         
65826         //box position and dimensions
65827         boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
65828         boxy = y - bbox.height /2 - offsetBox;
65829         boxw = bbox.width + 2 * offsetBox;
65830         boxh = bbox.height + 2 * offsetBox;
65831         
65832         //now check if we're out of bounds and invert the normal vector correspondingly
65833         //this may add new overlaps between labels (but labels won't be out of bounds).
65834         if (boxx < clipRect[0] || (boxx + boxw) > (clipRect[0] + clipRect[2])) {
65835             normal[0] *= -1;
65836         }
65837         if (boxy < clipRect[1] || (boxy + boxh) > (clipRect[1] + clipRect[3])) {
65838             normal[1] *= -1;
65839         }
65840
65841         //update positions
65842         x = cur[0] + normal[0] * offsetFromViz;
65843         y = cur[1] + normal[1] * offsetFromViz;
65844         
65845         //update box position and dimensions
65846         boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
65847         boxy = y - bbox.height /2 - offsetBox;
65848         boxw = bbox.width + 2 * offsetBox;
65849         boxh = bbox.height + 2 * offsetBox;
65850         
65851         //set the line from the middle of the pie to the box.
65852         callout.lines.setAttributes({
65853             path: ["M", cur[0], cur[1], "L", x, y, "Z"]
65854         }, true);
65855         //set box position
65856         callout.box.setAttributes({
65857             x: boxx,
65858             y: boxy,
65859             width: boxw,
65860             height: boxh
65861         }, true);
65862         //set text position
65863         callout.label.setAttributes({
65864             x: x + (normal[0] > 0? offsetBox : -(bbox.width + offsetBox)),
65865             y: y
65866         }, true);
65867         for (p in callout) {
65868             callout[p].show(true);
65869         }
65870     },
65871     
65872     isItemInPoint: function(x, y, item, i) {
65873         var me = this,
65874             pointsUp = item.pointsUp,
65875             pointsDown = item.pointsDown,
65876             abs = Math.abs,
65877             dist = Infinity, p, pln, point;
65878         
65879         for (p = 0, pln = pointsUp.length; p < pln; p++) {
65880             point = [pointsUp[p][0], pointsUp[p][1]];
65881             if (dist > abs(x - point[0])) {
65882                 dist = abs(x - point[0]);
65883             } else {
65884                 point = pointsUp[p -1];
65885                 if (y >= point[1] && (!pointsDown.length || y <= (pointsDown[p -1][1]))) {
65886                     item.storeIndex = p -1;
65887                     item.storeField = me.yField[i];
65888                     item.storeItem = me.chart.store.getAt(p -1);
65889                     item._points = pointsDown.length? [point, pointsDown[p -1]] : [point];
65890                     return true;
65891                 } else {
65892                     break;
65893                 }
65894             }
65895         }
65896         return false;
65897     },
65898
65899     /**
65900      * Highlight this entire series.
65901      * @param {Object} item Info about the item; same format as returned by #getItemForPoint.
65902      */
65903     highlightSeries: function() {
65904         var area, to, fillColor;
65905         if (this._index !== undefined) {
65906             area = this.areas[this._index];
65907             if (area.__highlightAnim) {
65908                 area.__highlightAnim.paused = true;
65909             }
65910             area.__highlighted = true;
65911             area.__prevOpacity = area.__prevOpacity || area.attr.opacity || 1;
65912             area.__prevFill = area.__prevFill || area.attr.fill;
65913             area.__prevLineWidth = area.__prevLineWidth || area.attr.lineWidth;
65914             fillColor = Ext.draw.Color.fromString(area.__prevFill);
65915             to = {
65916                 lineWidth: (area.__prevLineWidth || 0) + 2
65917             };
65918             if (fillColor) {
65919                 to.fill = fillColor.getLighter(0.2).toString();
65920             }
65921             else {
65922                 to.opacity = Math.max(area.__prevOpacity - 0.3, 0);
65923             }
65924             if (this.chart.animate) {
65925                 area.__highlightAnim = Ext.create('Ext.fx.Anim', Ext.apply({
65926                     target: area,
65927                     to: to
65928                 }, this.chart.animate));
65929             }
65930             else {
65931                 area.setAttributes(to, true);
65932             }
65933         }
65934     },
65935
65936     /**
65937      * UnHighlight this entire series.
65938      * @param {Object} item Info about the item; same format as returned by #getItemForPoint.
65939      */
65940     unHighlightSeries: function() {
65941         var area;
65942         if (this._index !== undefined) {
65943             area = this.areas[this._index];
65944             if (area.__highlightAnim) {
65945                 area.__highlightAnim.paused = true;
65946             }
65947             if (area.__highlighted) {
65948                 area.__highlighted = false;
65949                 area.__highlightAnim = Ext.create('Ext.fx.Anim', {
65950                     target: area,
65951                     to: {
65952                         fill: area.__prevFill,
65953                         opacity: area.__prevOpacity,
65954                         lineWidth: area.__prevLineWidth
65955                     }
65956                 });
65957             }
65958         }
65959     },
65960
65961     /**
65962      * Highlight the specified item. If no item is provided the whole series will be highlighted.
65963      * @param item {Object} Info about the item; same format as returned by #getItemForPoint
65964      */
65965     highlightItem: function(item) {
65966         var me = this,
65967             points, path;
65968         if (!item) {
65969             this.highlightSeries();
65970             return;
65971         }
65972         points = item._points;
65973         path = points.length == 2? ['M', points[0][0], points[0][1], 'L', points[1][0], points[1][1]]
65974                 : ['M', points[0][0], points[0][1], 'L', points[0][0], me.bbox.y + me.bbox.height];
65975         me.highlightSprite.setAttributes({
65976             path: path,
65977             hidden: false
65978         }, true);
65979     },
65980
65981     /**
65982      * un-highlights the specified item. If no item is provided it will un-highlight the entire series.
65983      * @param item {Object} Info about the item; same format as returned by #getItemForPoint
65984      */
65985     unHighlightItem: function(item) {
65986         if (!item) {
65987             this.unHighlightSeries();
65988         }
65989
65990         if (this.highlightSprite) {
65991             this.highlightSprite.hide(true);
65992         }
65993     },
65994
65995     // @private
65996     hideAll: function() {
65997         if (!isNaN(this._index)) {
65998             this.__excludes[this._index] = true;
65999             this.areas[this._index].hide(true);
66000             this.drawSeries();
66001         }
66002     },
66003
66004     // @private
66005     showAll: function() {
66006         if (!isNaN(this._index)) {
66007             this.__excludes[this._index] = false;
66008             this.areas[this._index].show(true);
66009             this.drawSeries();
66010         }
66011     },
66012
66013     /**
66014      * Returns the color of the series (to be displayed as color for the series legend item).
66015      * @param item {Object} Info about the item; same format as returned by #getItemForPoint
66016      */
66017     getLegendColor: function(index) {
66018         var me = this;
66019         return me.colorArrayStyle[index % me.colorArrayStyle.length];
66020     }
66021 });
66022
66023 /**
66024  * Creates a Bar Chart. A Bar Chart is a useful visualization technique to display quantitative information for
66025  * different categories that can show some progression (or regression) in the dataset. As with all other series, the Bar
66026  * Series must be appended in the *series* Chart array configuration. See the Chart documentation for more information.
66027  * A typical configuration object for the bar series could be:
66028  *
66029  * {@img Ext.chart.series.Bar/Ext.chart.series.Bar.png Ext.chart.series.Bar chart series}
66030  *
66031  *     var store = Ext.create('Ext.data.JsonStore', {
66032  *         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
66033  *         data: [
66034  *             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
66035  *             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
66036  *             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
66037  *             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
66038  *             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}
66039  *         ]
66040  *     });
66041  *     
66042  *     Ext.create('Ext.chart.Chart', {
66043  *         renderTo: Ext.getBody(),
66044  *         width: 500,
66045  *         height: 300,
66046  *         animate: true,
66047  *         store: store,
66048  *         axes: [{
66049  *             type: 'Numeric',
66050  *             position: 'bottom',
66051  *             fields: ['data1'],
66052  *             label: {
66053  *                 renderer: Ext.util.Format.numberRenderer('0,0')
66054  *             },
66055  *             title: 'Sample Values',
66056  *             grid: true,
66057  *             minimum: 0
66058  *         }, {
66059  *             type: 'Category',
66060  *             position: 'left',
66061  *             fields: ['name'],
66062  *             title: 'Sample Metrics'
66063  *         }],
66064  *         series: [{
66065  *             type: 'bar',
66066  *             axis: 'bottom',
66067  *             highlight: true,
66068  *             tips: {
66069  *               trackMouse: true,
66070  *               width: 140,
66071  *               height: 28,
66072  *               renderer: function(storeItem, item) {
66073  *                 this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' views');
66074  *               }
66075  *             },
66076  *             label: {
66077  *               display: 'insideEnd',
66078  *                 field: 'data1',
66079  *                 renderer: Ext.util.Format.numberRenderer('0'),
66080  *                 orientation: 'horizontal',
66081  *                 color: '#333',
66082  *                 'text-anchor': 'middle'
66083  *             },
66084  *             xField: 'name',
66085  *             yField: ['data1']
66086  *         }]
66087  *     });
66088  *
66089  * In this configuration we set `bar` as the series type, bind the values of the bar to the bottom axis and set the
66090  * xField or category field to the `name` parameter of the store. We also set `highlight` to true which enables smooth
66091  * animations when bars are hovered. We also set some configuration for the bar labels to be displayed inside the bar,
66092  * to display the information found in the `data1` property of each element store, to render a formated text with the
66093  * `Ext.util.Format` we pass in, to have an `horizontal` orientation (as opposed to a vertical one) and we also set
66094  * other styles like `color`, `text-anchor`, etc.
66095  */
66096 Ext.define('Ext.chart.series.Bar', {
66097
66098     /* Begin Definitions */
66099
66100     extend: 'Ext.chart.series.Cartesian',
66101
66102     alternateClassName: ['Ext.chart.BarSeries', 'Ext.chart.BarChart', 'Ext.chart.StackedBarChart'],
66103
66104     requires: ['Ext.chart.axis.Axis', 'Ext.fx.Anim'],
66105
66106     /* End Definitions */
66107
66108     type: 'bar',
66109
66110     alias: 'series.bar',
66111     /**
66112      * @cfg {Boolean} column Whether to set the visualization as column chart or horizontal bar chart.
66113      */
66114     column: false,
66115     
66116     /**
66117      * @cfg style Style properties that will override the theming series styles.
66118      */
66119     style: {},
66120     
66121     /**
66122      * @cfg {Number} gutter The gutter space between single bars, as a percentage of the bar width
66123      */
66124     gutter: 38.2,
66125
66126     /**
66127      * @cfg {Number} groupGutter The gutter space between groups of bars, as a percentage of the bar width
66128      */
66129     groupGutter: 38.2,
66130
66131     /**
66132      * @cfg {Number} xPadding Padding between the left/right axes and the bars
66133      */
66134     xPadding: 0,
66135
66136     /**
66137      * @cfg {Number} yPadding Padding between the top/bottom axes and the bars
66138      */
66139     yPadding: 10,
66140
66141     constructor: function(config) {
66142         this.callParent(arguments);
66143         var me = this,
66144             surface = me.chart.surface,
66145             shadow = me.chart.shadow,
66146             i, l;
66147         Ext.apply(me, config, {
66148             highlightCfg: {
66149                 lineWidth: 3,
66150                 stroke: '#55c',
66151                 opacity: 0.8,
66152                 color: '#f00'
66153             },
66154             
66155             shadowAttributes: [{
66156                 "stroke-width": 6,
66157                 "stroke-opacity": 0.05,
66158                 stroke: 'rgb(200, 200, 200)',
66159                 translate: {
66160                     x: 1.2,
66161                     y: 1.2
66162                 }
66163             }, {
66164                 "stroke-width": 4,
66165                 "stroke-opacity": 0.1,
66166                 stroke: 'rgb(150, 150, 150)',
66167                 translate: {
66168                     x: 0.9,
66169                     y: 0.9
66170                 }
66171             }, {
66172                 "stroke-width": 2,
66173                 "stroke-opacity": 0.15,
66174                 stroke: 'rgb(100, 100, 100)',
66175                 translate: {
66176                     x: 0.6,
66177                     y: 0.6
66178                 }
66179             }]
66180         });
66181         me.group = surface.getGroup(me.seriesId + '-bars');
66182         if (shadow) {
66183             for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
66184                 me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
66185             }
66186         }
66187     },
66188
66189     // @private sets the bar girth.
66190     getBarGirth: function() {
66191         var me = this,
66192             store = me.chart.store,
66193             column = me.column,
66194             ln = store.getCount(),
66195             gutter = me.gutter / 100;
66196         
66197         return (me.chart.chartBBox[column ? 'width' : 'height'] - me[column ? 'xPadding' : 'yPadding'] * 2) / (ln * (gutter + 1) - gutter);
66198     },
66199
66200     // @private returns the gutters.
66201     getGutters: function() {
66202         var me = this,
66203             column = me.column,
66204             gutter = Math.ceil(me[column ? 'xPadding' : 'yPadding'] + me.getBarGirth() / 2);
66205         return me.column ? [gutter, 0] : [0, gutter];
66206     },
66207
66208     // @private Get chart and data boundaries
66209     getBounds: function() {
66210         var me = this,
66211             chart = me.chart,
66212             store = chart.substore || chart.store,
66213             bars = [].concat(me.yField),
66214             barsLen = bars.length,
66215             groupBarsLen = barsLen,
66216             groupGutter = me.groupGutter / 100,
66217             column = me.column,
66218             xPadding = me.xPadding,
66219             yPadding = me.yPadding,
66220             stacked = me.stacked,
66221             barWidth = me.getBarGirth(),
66222             math = Math,
66223             mmax = math.max,
66224             mabs = math.abs,
66225             groupBarWidth, bbox, minY, maxY, axis, out,
66226             scale, zero, total, rec, j, plus, minus;
66227
66228         me.setBBox(true);
66229         bbox = me.bbox;
66230
66231         //Skip excluded series
66232         if (me.__excludes) {
66233             for (j = 0, total = me.__excludes.length; j < total; j++) {
66234                 if (me.__excludes[j]) {
66235                     groupBarsLen--;
66236                 }
66237             }
66238         }
66239
66240         if (me.axis) {
66241             axis = chart.axes.get(me.axis);
66242             if (axis) {
66243                 out = axis.calcEnds();
66244                 minY = out.from || axis.prevMin;
66245                 maxY = mmax(out.to || axis.prevMax, 0);
66246             }
66247         }
66248
66249         if (me.yField && !Ext.isNumber(minY)) {
66250             axis = Ext.create('Ext.chart.axis.Axis', {
66251                 chart: chart,
66252                 fields: [].concat(me.yField)
66253             });
66254             out = axis.calcEnds();
66255             minY = out.from || axis.prevMin;
66256             maxY = mmax(out.to || axis.prevMax, 0);
66257         }
66258
66259         if (!Ext.isNumber(minY)) {
66260             minY = 0;
66261         }
66262         if (!Ext.isNumber(maxY)) {
66263             maxY = 0;
66264         }
66265         scale = (column ? bbox.height - yPadding * 2 : bbox.width - xPadding * 2) / (maxY - minY);
66266         groupBarWidth = barWidth / ((stacked ? 1 : groupBarsLen) * (groupGutter + 1) - groupGutter);
66267         zero = (column) ? bbox.y + bbox.height - yPadding : bbox.x + xPadding;
66268
66269         if (stacked) {
66270             total = [[], []];
66271             store.each(function(record, i) {
66272                 total[0][i] = total[0][i] || 0;
66273                 total[1][i] = total[1][i] || 0;
66274                 for (j = 0; j < barsLen; j++) {
66275                     if (me.__excludes && me.__excludes[j]) {
66276                         continue;
66277                     }
66278                     rec = record.get(bars[j]);
66279                     total[+(rec > 0)][i] += mabs(rec);
66280                 }
66281             });
66282             total[+(maxY > 0)].push(mabs(maxY));
66283             total[+(minY > 0)].push(mabs(minY));
66284             minus = mmax.apply(math, total[0]);
66285             plus = mmax.apply(math, total[1]);
66286             scale = (column ? bbox.height - yPadding * 2 : bbox.width - xPadding * 2) / (plus + minus);
66287             zero = zero + minus * scale * (column ? -1 : 1);
66288         }
66289         else if (minY / maxY < 0) {
66290             zero = zero - minY * scale * (column ? -1 : 1);
66291         }
66292         return {
66293             bars: bars,
66294             bbox: bbox,
66295             barsLen: barsLen,
66296             groupBarsLen: groupBarsLen,
66297             barWidth: barWidth,
66298             groupBarWidth: groupBarWidth,
66299             scale: scale,
66300             zero: zero,
66301             xPadding: xPadding,
66302             yPadding: yPadding,
66303             signed: minY / maxY < 0,
66304             minY: minY,
66305             maxY: maxY
66306         };
66307     },
66308
66309     // @private Build an array of paths for the chart
66310     getPaths: function() {
66311         var me = this,
66312             chart = me.chart,
66313             store = chart.substore || chart.store,
66314             bounds = me.bounds = me.getBounds(),
66315             items = me.items = [],
66316             gutter = me.gutter / 100,
66317             groupGutter = me.groupGutter / 100,
66318             animate = chart.animate,
66319             column = me.column,
66320             group = me.group,
66321             enableShadows = chart.shadow,
66322             shadowGroups = me.shadowGroups,
66323             shadowAttributes = me.shadowAttributes,
66324             shadowGroupsLn = shadowGroups.length,
66325             bbox = bounds.bbox,
66326             xPadding = me.xPadding,
66327             yPadding = me.yPadding,
66328             stacked = me.stacked,
66329             barsLen = bounds.barsLen,
66330             colors = me.colorArrayStyle,
66331             colorLength = colors && colors.length || 0,
66332             math = Math,
66333             mmax = math.max,
66334             mmin = math.min,
66335             mabs = math.abs,
66336             j, yValue, height, totalDim, totalNegDim, bottom, top, hasShadow, barAttr, attrs, counter,
66337             shadowIndex, shadow, sprite, offset, floorY;
66338
66339         store.each(function(record, i, total) {
66340             bottom = bounds.zero;
66341             top = bounds.zero;
66342             totalDim = 0;
66343             totalNegDim = 0;
66344             hasShadow = false; 
66345             for (j = 0, counter = 0; j < barsLen; j++) {
66346                 // Excluded series
66347                 if (me.__excludes && me.__excludes[j]) {
66348                     continue;
66349                 }
66350                 yValue = record.get(bounds.bars[j]);
66351                 height = Math.round((yValue - ((bounds.minY < 0) ? 0 : bounds.minY)) * bounds.scale);
66352                 barAttr = {
66353                     fill: colors[(barsLen > 1 ? j : 0) % colorLength]
66354                 };
66355                 if (column) {
66356                     Ext.apply(barAttr, {
66357                         height: height,
66358                         width: mmax(bounds.groupBarWidth, 0),
66359                         x: (bbox.x + xPadding + i * bounds.barWidth * (1 + gutter) + counter * bounds.groupBarWidth * (1 + groupGutter) * !stacked),
66360                         y: bottom - height
66361                     });
66362                 }
66363                 else {
66364                     // draw in reverse order
66365                     offset = (total - 1) - i;
66366                     Ext.apply(barAttr, {
66367                         height: mmax(bounds.groupBarWidth, 0),
66368                         width: height + (bottom == bounds.zero),
66369                         x: bottom + (bottom != bounds.zero),
66370                         y: (bbox.y + yPadding + offset * bounds.barWidth * (1 + gutter) + counter * bounds.groupBarWidth * (1 + groupGutter) * !stacked + 1)
66371                     });
66372                 }
66373                 if (height < 0) {
66374                     if (column) {
66375                         barAttr.y = top;
66376                         barAttr.height = mabs(height);
66377                     } else {
66378                         barAttr.x = top + height;
66379                         barAttr.width = mabs(height);
66380                     }
66381                 }
66382                 if (stacked) {
66383                     if (height < 0) {
66384                         top += height * (column ? -1 : 1);
66385                     } else {
66386                         bottom += height * (column ? -1 : 1);
66387                     }
66388                     totalDim += mabs(height);
66389                     if (height < 0) {
66390                         totalNegDim += mabs(height);
66391                     }
66392                 }
66393                 barAttr.x = Math.floor(barAttr.x) + 1;
66394                 floorY = Math.floor(barAttr.y);
66395                 if (!Ext.isIE9 && barAttr.y > floorY) {
66396                     floorY--;
66397                 }
66398                 barAttr.y = floorY;
66399                 barAttr.width = Math.floor(barAttr.width);
66400                 barAttr.height = Math.floor(barAttr.height);
66401                 items.push({
66402                     series: me,
66403                     storeItem: record,
66404                     value: [record.get(me.xField), yValue],
66405                     attr: barAttr,
66406                     point: column ? [barAttr.x + barAttr.width / 2, yValue >= 0 ? barAttr.y : barAttr.y + barAttr.height] :
66407                                     [yValue >= 0 ? barAttr.x + barAttr.width : barAttr.x, barAttr.y + barAttr.height / 2]
66408                 });
66409                 // When resizing, reset before animating
66410                 if (animate && chart.resizing) {
66411                     attrs = column ? {
66412                         x: barAttr.x,
66413                         y: bounds.zero,
66414                         width: barAttr.width,
66415                         height: 0
66416                     } : {
66417                         x: bounds.zero,
66418                         y: barAttr.y,
66419                         width: 0,
66420                         height: barAttr.height
66421                     };
66422                     if (enableShadows && (stacked && !hasShadow || !stacked)) {
66423                         hasShadow = true;
66424                         //update shadows
66425                         for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
66426                             shadow = shadowGroups[shadowIndex].getAt(stacked ? i : (i * barsLen + j));
66427                             if (shadow) {
66428                                 shadow.setAttributes(attrs, true);
66429                             }
66430                         }
66431                     }
66432                     //update sprite position and width/height
66433                     sprite = group.getAt(i * barsLen + j);
66434                     if (sprite) {
66435                         sprite.setAttributes(attrs, true);
66436                     }
66437                 }
66438                 counter++;
66439             }
66440             if (stacked && items.length) {
66441                 items[i * counter].totalDim = totalDim;
66442                 items[i * counter].totalNegDim = totalNegDim;
66443             }
66444         }, me);
66445     },
66446
66447     // @private render/setAttributes on the shadows
66448     renderShadows: function(i, barAttr, baseAttrs, bounds) {
66449         var me = this,
66450             chart = me.chart,
66451             surface = chart.surface,
66452             animate = chart.animate,
66453             stacked = me.stacked,
66454             shadowGroups = me.shadowGroups,
66455             shadowAttributes = me.shadowAttributes,
66456             shadowGroupsLn = shadowGroups.length,
66457             store = chart.substore || chart.store,
66458             column = me.column,
66459             items = me.items,
66460             shadows = [],
66461             zero = bounds.zero,
66462             shadowIndex, shadowBarAttr, shadow, totalDim, totalNegDim, j, rendererAttributes;
66463
66464         if ((stacked && (i % bounds.groupBarsLen === 0)) || !stacked) {
66465             j = i / bounds.groupBarsLen;
66466             //create shadows
66467             for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
66468                 shadowBarAttr = Ext.apply({}, shadowAttributes[shadowIndex]);
66469                 shadow = shadowGroups[shadowIndex].getAt(stacked ? j : i);
66470                 Ext.copyTo(shadowBarAttr, barAttr, 'x,y,width,height');
66471                 if (!shadow) {
66472                     shadow = surface.add(Ext.apply({
66473                         type: 'rect',
66474                         group: shadowGroups[shadowIndex]
66475                     }, Ext.apply({}, baseAttrs, shadowBarAttr)));
66476                 }
66477                 if (stacked) {
66478                     totalDim = items[i].totalDim;
66479                     totalNegDim = items[i].totalNegDim;
66480                     if (column) {
66481                         shadowBarAttr.y = zero - totalNegDim;
66482                         shadowBarAttr.height = totalDim;
66483                     }
66484                     else {
66485                         shadowBarAttr.x = zero - totalNegDim;
66486                         shadowBarAttr.width = totalDim;
66487                     }
66488                 }
66489                 if (animate) {
66490                     if (!stacked) {
66491                         rendererAttributes = me.renderer(shadow, store.getAt(j), shadowBarAttr, i, store);
66492                         me.onAnimate(shadow, { to: rendererAttributes });
66493                     }
66494                     else {
66495                         rendererAttributes = me.renderer(shadow, store.getAt(j), Ext.apply(shadowBarAttr, { hidden: true }), i, store);
66496                         shadow.setAttributes(rendererAttributes, true);
66497                     }
66498                 }
66499                 else {
66500                     rendererAttributes = me.renderer(shadow, store.getAt(j), Ext.apply(shadowBarAttr, { hidden: false }), i, store);
66501                     shadow.setAttributes(rendererAttributes, true);
66502                 }
66503                 shadows.push(shadow);
66504             }
66505         }
66506         return shadows;
66507     },
66508
66509     /**
66510      * Draws the series for the current chart.
66511      */
66512     drawSeries: function() {
66513         var me = this,
66514             chart = me.chart,
66515             store = chart.substore || chart.store,
66516             surface = chart.surface,
66517             animate = chart.animate,
66518             stacked = me.stacked,
66519             column = me.column,
66520             enableShadows = chart.shadow,
66521             shadowGroups = me.shadowGroups,
66522             shadowGroupsLn = shadowGroups.length,
66523             group = me.group,
66524             seriesStyle = me.seriesStyle,
66525             items, ln, i, j, baseAttrs, sprite, rendererAttributes, shadowIndex, shadowGroup,
66526             bounds, endSeriesStyle, barAttr, attrs, anim;
66527         
66528         if (!store || !store.getCount()) {
66529             return;
66530         }
66531         
66532         //fill colors are taken from the colors array.
66533         delete seriesStyle.fill;
66534         endSeriesStyle = Ext.apply(seriesStyle, this.style);
66535         me.unHighlightItem();
66536         me.cleanHighlights();
66537
66538         me.getPaths();
66539         bounds = me.bounds;
66540         items = me.items;
66541
66542         baseAttrs = column ? {
66543             y: bounds.zero,
66544             height: 0
66545         } : {
66546             x: bounds.zero,
66547             width: 0
66548         };
66549         ln = items.length;
66550         // Create new or reuse sprites and animate/display
66551         for (i = 0; i < ln; i++) {
66552             sprite = group.getAt(i);
66553             barAttr = items[i].attr;
66554
66555             if (enableShadows) {
66556                 items[i].shadows = me.renderShadows(i, barAttr, baseAttrs, bounds);
66557             }
66558
66559             // Create a new sprite if needed (no height)
66560             if (!sprite) {
66561                 attrs = Ext.apply({}, baseAttrs, barAttr);
66562                 attrs = Ext.apply(attrs, endSeriesStyle || {});
66563                 sprite = surface.add(Ext.apply({}, {
66564                     type: 'rect',
66565                     group: group
66566                 }, attrs));
66567             }
66568             if (animate) {
66569                 rendererAttributes = me.renderer(sprite, store.getAt(i), barAttr, i, store);
66570                 sprite._to = rendererAttributes;
66571                 anim = me.onAnimate(sprite, { to: Ext.apply(rendererAttributes, endSeriesStyle) });
66572                 if (enableShadows && stacked && (i % bounds.barsLen === 0)) {
66573                     j = i / bounds.barsLen;
66574                     for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
66575                         anim.on('afteranimate', function() {
66576                             this.show(true);
66577                         }, shadowGroups[shadowIndex].getAt(j));
66578                     }
66579                 }
66580             }
66581             else {
66582                 rendererAttributes = me.renderer(sprite, store.getAt(i), Ext.apply(barAttr, { hidden: false }), i, store);
66583                 sprite.setAttributes(Ext.apply(rendererAttributes, endSeriesStyle), true);
66584             }
66585             items[i].sprite = sprite;
66586         }
66587
66588         // Hide unused sprites
66589         ln = group.getCount();
66590         for (j = i; j < ln; j++) {
66591             group.getAt(j).hide(true);
66592         }
66593         // Hide unused shadows
66594         if (enableShadows) {
66595             for (shadowIndex = 0; shadowIndex < shadowGroupsLn; shadowIndex++) {
66596                 shadowGroup = shadowGroups[shadowIndex];
66597                 ln = shadowGroup.getCount();
66598                 for (j = i; j < ln; j++) {
66599                     shadowGroup.getAt(j).hide(true);
66600                 }
66601             }
66602         }
66603         me.renderLabels();
66604     },
66605     
66606     // @private handled when creating a label.
66607     onCreateLabel: function(storeItem, item, i, display) {
66608         var me = this,
66609             surface = me.chart.surface,
66610             group = me.labelsGroup,
66611             config = me.label,
66612             endLabelStyle = Ext.apply({}, config, me.seriesLabelStyle || {}),
66613             sprite;
66614         return surface.add(Ext.apply({
66615             type: 'text',
66616             group: group
66617         }, endLabelStyle || {}));
66618     },
66619     
66620     // @private callback used when placing a label.
66621     onPlaceLabel: function(label, storeItem, item, i, display, animate, index) {
66622         // Determine the label's final position. Starts with the configured preferred value but
66623         // may get flipped from inside to outside or vice-versa depending on space.
66624         var me = this,
66625             opt = me.bounds,
66626             groupBarWidth = opt.groupBarWidth,
66627             column = me.column,
66628             chart = me.chart,
66629             chartBBox = chart.chartBBox,
66630             resizing = chart.resizing,
66631             xValue = item.value[0],
66632             yValue = item.value[1],
66633             attr = item.attr,
66634             config = me.label,
66635             rotate = config.orientation == 'vertical',
66636             field = [].concat(config.field),
66637             format = config.renderer,
66638             text = format(storeItem.get(field[index])),
66639             size = me.getLabelSize(text),
66640             width = size.width,
66641             height = size.height,
66642             zero = opt.zero,
66643             outside = 'outside',
66644             insideStart = 'insideStart',
66645             insideEnd = 'insideEnd',
66646             offsetX = 10,
66647             offsetY = 6,
66648             signed = opt.signed,
66649             x, y, finalAttr;
66650
66651         label.setAttributes({
66652             text: text
66653         });
66654
66655         if (column) {
66656             if (display == outside) {
66657                 if (height + offsetY + attr.height > (yValue >= 0 ? zero - chartBBox.y : chartBBox.y + chartBBox.height - zero)) {
66658                     display = insideEnd;
66659                 }
66660             } else {
66661                 if (height + offsetY > attr.height) {
66662                     display = outside;
66663                 }
66664             }
66665             x = attr.x + groupBarWidth / 2;
66666             y = display == insideStart ?
66667                     (zero + ((height / 2 + 3) * (yValue >= 0 ? -1 : 1))) :
66668                     (yValue >= 0 ? (attr.y + ((height / 2 + 3) * (display == outside ? -1 : 1))) :
66669                                    (attr.y + attr.height + ((height / 2 + 3) * (display === outside ? 1 : -1))));
66670         }
66671         else {
66672             if (display == outside) {
66673                 if (width + offsetX + attr.width > (yValue >= 0 ? chartBBox.x + chartBBox.width - zero : zero - chartBBox.x)) {
66674                     display = insideEnd;
66675                 }
66676             }
66677             else {
66678                 if (width + offsetX > attr.width) {
66679                     display = outside;
66680                 }
66681             }
66682             x = display == insideStart ?
66683                 (zero + ((width / 2 + 5) * (yValue >= 0 ? 1 : -1))) :
66684                 (yValue >= 0 ? (attr.x + attr.width + ((width / 2 + 5) * (display === outside ? 1 : -1))) :
66685                 (attr.x + ((width / 2 + 5) * (display === outside ? -1 : 1))));
66686             y = attr.y + groupBarWidth / 2;
66687         }
66688         //set position
66689         finalAttr = {
66690             x: x,
66691             y: y
66692         };
66693         //rotate
66694         if (rotate) {
66695             finalAttr.rotate = {
66696                 x: x,
66697                 y: y,
66698                 degrees: 270
66699             };
66700         }
66701         //check for resizing
66702         if (animate && resizing) {
66703             if (column) {
66704                 x = attr.x + attr.width / 2;
66705                 y = zero;
66706             } else {
66707                 x = zero;
66708                 y = attr.y + attr.height / 2;
66709             }
66710             label.setAttributes({
66711                 x: x,
66712                 y: y
66713             }, true);
66714             if (rotate) {
66715                 label.setAttributes({
66716                     rotate: {
66717                         x: x,
66718                         y: y,
66719                         degrees: 270
66720                     }
66721                 }, true);
66722             }
66723         }
66724         //handle animation
66725         if (animate) {
66726             me.onAnimate(label, { to: finalAttr });
66727         }
66728         else {
66729             label.setAttributes(Ext.apply(finalAttr, {
66730                 hidden: false
66731             }), true);
66732         }
66733     },
66734
66735     /* @private
66736      * Gets the dimensions of a given bar label. Uses a single hidden sprite to avoid
66737      * changing visible sprites.
66738      * @param value
66739      */
66740     getLabelSize: function(value) {
66741         var tester = this.testerLabel,
66742             config = this.label,
66743             endLabelStyle = Ext.apply({}, config, this.seriesLabelStyle || {}),
66744             rotated = config.orientation === 'vertical',
66745             bbox, w, h,
66746             undef;
66747         if (!tester) {
66748             tester = this.testerLabel = this.chart.surface.add(Ext.apply({
66749                 type: 'text',
66750                 opacity: 0
66751             }, endLabelStyle));
66752         }
66753         tester.setAttributes({
66754             text: value
66755         }, true);
66756
66757         // Flip the width/height if rotated, as getBBox returns the pre-rotated dimensions
66758         bbox = tester.getBBox();
66759         w = bbox.width;
66760         h = bbox.height;
66761         return {
66762             width: rotated ? h : w,
66763             height: rotated ? w : h
66764         };
66765     },
66766
66767     // @private used to animate label, markers and other sprites.
66768     onAnimate: function(sprite, attr) {
66769         sprite.show();
66770         return this.callParent(arguments);
66771     },
66772     
66773     isItemInPoint: function(x, y, item) {
66774         var bbox = item.sprite.getBBox();
66775         return bbox.x <= x && bbox.y <= y
66776             && (bbox.x + bbox.width) >= x
66777             && (bbox.y + bbox.height) >= y;
66778     },
66779     
66780     // @private hide all markers
66781     hideAll: function() {
66782         var axes = this.chart.axes;
66783         if (!isNaN(this._index)) {
66784             if (!this.__excludes) {
66785                 this.__excludes = [];
66786             }
66787             this.__excludes[this._index] = true;
66788             this.drawSeries();
66789             axes.each(function(axis) {
66790                 axis.drawAxis();
66791             });
66792         }
66793     },
66794
66795     // @private show all markers
66796     showAll: function() {
66797         var axes = this.chart.axes;
66798         if (!isNaN(this._index)) {
66799             if (!this.__excludes) {
66800                 this.__excludes = [];
66801             }
66802             this.__excludes[this._index] = false;
66803             this.drawSeries();
66804             axes.each(function(axis) {
66805                 axis.drawAxis();
66806             });
66807         }
66808     },
66809     
66810     /**
66811      * Returns a string with the color to be used for the series legend item.
66812      * @param index
66813      */
66814     getLegendColor: function(index) {
66815         var me = this;
66816         return me.colorArrayStyle[index % me.colorArrayStyle.length];
66817     }
66818 });
66819 /**
66820  * @class Ext.chart.series.Column
66821  * @extends Ext.chart.series.Bar
66822  * 
66823   <p>
66824   Creates a Column Chart. Much of the methods are inherited from Bar. A Column Chart is a useful visualization technique to display quantitative information for different 
66825   categories that can show some progression (or regression) in the data set.
66826   As with all other series, the Column Series must be appended in the *series* Chart array configuration. See the Chart 
66827   documentation for more information. A typical configuration object for the column series could be:
66828   </p>
66829 {@img Ext.chart.series.Column/Ext.chart.series.Column.png Ext.chart.series.Column chart series  
66830   <pre><code>
66831     var store = Ext.create('Ext.data.JsonStore', {
66832         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
66833         data: [
66834             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
66835             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
66836             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
66837             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
66838             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}                                                
66839         ]
66840     });
66841     
66842     Ext.create('Ext.chart.Chart', {
66843         renderTo: Ext.getBody(),
66844         width: 500,
66845         height: 300,
66846         animate: true,
66847         store: store,
66848         axes: [{
66849             type: 'Numeric',
66850             position: 'bottom',
66851             fields: ['data1'],
66852             label: {
66853                 renderer: Ext.util.Format.numberRenderer('0,0')
66854             },
66855             title: 'Sample Values',
66856             grid: true,
66857             minimum: 0
66858         }, {
66859             type: 'Category',
66860             position: 'left',
66861             fields: ['name'],
66862             title: 'Sample Metrics'
66863         }],
66864             axes: [{
66865                 type: 'Numeric',
66866                 position: 'left',
66867                 fields: ['data1'],
66868                 label: {
66869                     renderer: Ext.util.Format.numberRenderer('0,0')
66870                 },
66871                 title: 'Sample Values',
66872                 grid: true,
66873                 minimum: 0
66874             }, {
66875                 type: 'Category',
66876                 position: 'bottom',
66877                 fields: ['name'],
66878                 title: 'Sample Metrics'
66879             }],
66880             series: [{
66881                 type: 'column',
66882                 axis: 'left',
66883                 highlight: true,
66884                 tips: {
66885                   trackMouse: true,
66886                   width: 140,
66887                   height: 28,
66888                   renderer: function(storeItem, item) {
66889                     this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' $');
66890                   }
66891                 },
66892                 label: {
66893                   display: 'insideEnd',
66894                   'text-anchor': 'middle',
66895                     field: 'data1',
66896                     renderer: Ext.util.Format.numberRenderer('0'),
66897                     orientation: 'vertical',
66898                     color: '#333'
66899                 },
66900                 xField: 'name',
66901                 yField: 'data1'
66902             }]
66903     });
66904    </code></pre>
66905  
66906   <p>
66907   In this configuration we set `column` as the series type, bind the values of the bars to the bottom axis, set `highlight` to true so that bars are smoothly highlighted
66908   when hovered and bind the `xField` or category field to the data store `name` property and the `yField` as the data1 property of a store element. 
66909   </p>
66910  */
66911
66912 Ext.define('Ext.chart.series.Column', {
66913
66914     /* Begin Definitions */
66915
66916     alternateClassName: ['Ext.chart.ColumnSeries', 'Ext.chart.ColumnChart', 'Ext.chart.StackedColumnChart'],
66917
66918     extend: 'Ext.chart.series.Bar',
66919
66920     /* End Definitions */
66921
66922     type: 'column',
66923     alias: 'series.column',
66924
66925     column: true,
66926
66927     /**
66928      * @cfg {Number} xPadding
66929      * Padding between the left/right axes and the bars
66930      */
66931     xPadding: 10,
66932
66933     /**
66934      * @cfg {Number} yPadding
66935      * Padding between the top/bottom axes and the bars
66936      */
66937     yPadding: 0
66938 });
66939 /**
66940  * @class Ext.chart.series.Gauge
66941  * @extends Ext.chart.series.Series
66942  * 
66943  * Creates a Gauge Chart. Gauge Charts are used to show progress in a certain variable. There are two ways of using the Gauge chart.
66944  * One is setting a store element into the Gauge and selecting the field to be used from that store. Another one is instanciating the
66945  * visualization and using the `setValue` method to adjust the value you want.
66946  *
66947  * A chart/series configuration for the Gauge visualization could look like this:
66948  * 
66949  *     {
66950  *         xtype: 'chart',
66951  *         store: store,
66952  *         axes: [{
66953  *             type: 'gauge',
66954  *             position: 'gauge',
66955  *             minimum: 0,
66956  *             maximum: 100,
66957  *             steps: 10,
66958  *             margin: -10
66959  *         }],
66960  *         series: [{
66961  *             type: 'gauge',
66962  *             field: 'data1',
66963  *             donut: false,
66964  *             colorSet: ['#F49D10', '#ddd']
66965  *         }]
66966  *     }
66967  * 
66968  * In this configuration we create a special Gauge axis to be used with the gauge visualization (describing half-circle markers), and also we're
66969  * setting a maximum, minimum and steps configuration options into the axis. The Gauge series configuration contains the store field to be bound to
66970  * the visual display and the color set to be used with the visualization.
66971  * 
66972  * @xtype gauge
66973  */
66974 Ext.define('Ext.chart.series.Gauge', {
66975
66976     /* Begin Definitions */
66977
66978     extend: 'Ext.chart.series.Series',
66979
66980     /* End Definitions */
66981
66982     type: "gauge",
66983     alias: 'series.gauge',
66984
66985     rad: Math.PI / 180,
66986
66987     /**
66988      * @cfg {Number} highlightDuration
66989      * The duration for the pie slice highlight effect.
66990      */
66991     highlightDuration: 150,
66992
66993     /**
66994      * @cfg {String} angleField
66995      * The store record field name to be used for the pie angles.
66996      * The values bound to this field name must be positive real numbers.
66997      * This parameter is required.
66998      */
66999     angleField: false,
67000
67001     /**
67002      * @cfg {Boolean} needle
67003      * Use the Gauge Series as an area series or add a needle to it. Default's false.
67004      */
67005     needle: false,
67006     
67007     /**
67008      * @cfg {Boolean|Number} donut
67009      * Use the entire disk or just a fraction of it for the gauge. Default's false.
67010      */
67011     donut: false,
67012
67013     /**
67014      * @cfg {Boolean} showInLegend
67015      * Whether to add the pie chart elements as legend items. Default's false.
67016      */
67017     showInLegend: false,
67018
67019     /**
67020      * @cfg {Object} style
67021      * An object containing styles for overriding series styles from Theming.
67022      */
67023     style: {},
67024     
67025     constructor: function(config) {
67026         this.callParent(arguments);
67027         var me = this,
67028             chart = me.chart,
67029             surface = chart.surface,
67030             store = chart.store,
67031             shadow = chart.shadow, i, l, cfg;
67032         Ext.apply(me, config, {
67033             shadowAttributes: [{
67034                 "stroke-width": 6,
67035                 "stroke-opacity": 1,
67036                 stroke: 'rgb(200, 200, 200)',
67037                 translate: {
67038                     x: 1.2,
67039                     y: 2
67040                 }
67041             },
67042             {
67043                 "stroke-width": 4,
67044                 "stroke-opacity": 1,
67045                 stroke: 'rgb(150, 150, 150)',
67046                 translate: {
67047                     x: 0.9,
67048                     y: 1.5
67049                 }
67050             },
67051             {
67052                 "stroke-width": 2,
67053                 "stroke-opacity": 1,
67054                 stroke: 'rgb(100, 100, 100)',
67055                 translate: {
67056                     x: 0.6,
67057                     y: 1
67058                 }
67059             }]
67060         });
67061         me.group = surface.getGroup(me.seriesId);
67062         if (shadow) {
67063             for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
67064                 me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
67065             }
67066         }
67067         surface.customAttributes.segment = function(opt) {
67068             return me.getSegment(opt);
67069         };
67070     },
67071     
67072     //@private updates some onbefore render parameters.
67073     initialize: function() {
67074         var me = this,
67075             store = me.chart.substore || me.chart.store;
67076         //Add yFields to be used in Legend.js
67077         me.yField = [];
67078         if (me.label.field) {
67079             store.each(function(rec) {
67080                 me.yField.push(rec.get(me.label.field));
67081             });
67082         }
67083     },
67084
67085     // @private returns an object with properties for a Slice
67086     getSegment: function(opt) {
67087         var me = this,
67088             rad = me.rad,
67089             cos = Math.cos,
67090             sin = Math.sin,
67091             abs = Math.abs,
67092             x = me.centerX,
67093             y = me.centerY,
67094             x1 = 0, x2 = 0, x3 = 0, x4 = 0,
67095             y1 = 0, y2 = 0, y3 = 0, y4 = 0,
67096             delta = 1e-2,
67097             r = opt.endRho - opt.startRho,
67098             startAngle = opt.startAngle,
67099             endAngle = opt.endAngle,
67100             midAngle = (startAngle + endAngle) / 2 * rad,
67101             margin = opt.margin || 0,
67102             flag = abs(endAngle - startAngle) > 180,
67103             a1 = Math.min(startAngle, endAngle) * rad,
67104             a2 = Math.max(startAngle, endAngle) * rad,
67105             singleSlice = false;
67106
67107         x += margin * cos(midAngle);
67108         y += margin * sin(midAngle);
67109
67110         x1 = x + opt.startRho * cos(a1);
67111         y1 = y + opt.startRho * sin(a1);
67112
67113         x2 = x + opt.endRho * cos(a1);
67114         y2 = y + opt.endRho * sin(a1);
67115
67116         x3 = x + opt.startRho * cos(a2);
67117         y3 = y + opt.startRho * sin(a2);
67118
67119         x4 = x + opt.endRho * cos(a2);
67120         y4 = y + opt.endRho * sin(a2);
67121
67122         if (abs(x1 - x3) <= delta && abs(y1 - y3) <= delta) {
67123             singleSlice = true;
67124         }
67125         //Solves mysterious clipping bug with IE
67126         if (singleSlice) {
67127             return {
67128                 path: [
67129                 ["M", x1, y1],
67130                 ["L", x2, y2],
67131                 ["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
67132                 ["Z"]]
67133             };
67134         } else {
67135             return {
67136                 path: [
67137                 ["M", x1, y1],
67138                 ["L", x2, y2],
67139                 ["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
67140                 ["L", x3, y3],
67141                 ["A", opt.startRho, opt.startRho, 0, +flag, 0, x1, y1],
67142                 ["Z"]]
67143             };
67144         }
67145     },
67146
67147     // @private utility function to calculate the middle point of a pie slice.
67148     calcMiddle: function(item) {
67149         var me = this,
67150             rad = me.rad,
67151             slice = item.slice,
67152             x = me.centerX,
67153             y = me.centerY,
67154             startAngle = slice.startAngle,
67155             endAngle = slice.endAngle,
67156             radius = Math.max(('rho' in slice) ? slice.rho: me.radius, me.label.minMargin),
67157             donut = +me.donut,
67158             a1 = Math.min(startAngle, endAngle) * rad,
67159             a2 = Math.max(startAngle, endAngle) * rad,
67160             midAngle = -(a1 + (a2 - a1) / 2),
67161             xm = x + (item.endRho + item.startRho) / 2 * Math.cos(midAngle),
67162             ym = y - (item.endRho + item.startRho) / 2 * Math.sin(midAngle);
67163
67164         item.middle = {
67165             x: xm,
67166             y: ym
67167         };
67168     },
67169
67170     /**
67171      * Draws the series for the current chart.
67172      */
67173     drawSeries: function() {
67174         var me = this,
67175             chart = me.chart,
67176             store = chart.substore || chart.store,
67177             group = me.group,
67178             animate = me.chart.animate,
67179             axis = me.chart.axes.get(0),
67180             minimum = axis && axis.minimum || me.minimum || 0,
67181             maximum = axis && axis.maximum || me.maximum || 0,
67182             field = me.angleField || me.field || me.xField,
67183             surface = chart.surface,
67184             chartBBox = chart.chartBBox,
67185             rad = me.rad,
67186             donut = +me.donut,
67187             values = {},
67188             items = [],
67189             seriesStyle = me.seriesStyle,
67190             seriesLabelStyle = me.seriesLabelStyle,
67191             colorArrayStyle = me.colorArrayStyle,
67192             colorArrayLength = colorArrayStyle && colorArrayStyle.length || 0,
67193             gutterX = chart.maxGutter[0],
67194             gutterY = chart.maxGutter[1],
67195             cos = Math.cos,
67196             sin = Math.sin,
67197             rendererAttributes, centerX, centerY, slice, slices, sprite, value,
67198             item, ln, record, i, j, startAngle, endAngle, middleAngle, sliceLength, path,
67199             p, spriteOptions, bbox, splitAngle, sliceA, sliceB;
67200         
67201         Ext.apply(seriesStyle, me.style || {});
67202
67203         me.setBBox();
67204         bbox = me.bbox;
67205
67206         //override theme colors
67207         if (me.colorSet) {
67208             colorArrayStyle = me.colorSet;
67209             colorArrayLength = colorArrayStyle.length;
67210         }
67211         
67212         //if not store or store is empty then there's nothing to draw
67213         if (!store || !store.getCount()) {
67214             return;
67215         }
67216         
67217         centerX = me.centerX = chartBBox.x + (chartBBox.width / 2);
67218         centerY = me.centerY = chartBBox.y + chartBBox.height;
67219         me.radius = Math.min(centerX - chartBBox.x, centerY - chartBBox.y);
67220         me.slices = slices = [];
67221         me.items = items = [];
67222         
67223         if (!me.value) {
67224             record = store.getAt(0);
67225             me.value = record.get(field);
67226         }
67227         
67228         value = me.value;
67229         if (me.needle) {
67230             sliceA = {
67231                 series: me,
67232                 value: value,
67233                 startAngle: -180,
67234                 endAngle: 0,
67235                 rho: me.radius
67236             };
67237             splitAngle = -180 * (1 - (value - minimum) / (maximum - minimum));
67238             slices.push(sliceA);
67239         } else {
67240             splitAngle = -180 * (1 - (value - minimum) / (maximum - minimum));
67241             sliceA = {
67242                 series: me,
67243                 value: value,
67244                 startAngle: -180,
67245                 endAngle: splitAngle,
67246                 rho: me.radius
67247             };
67248             sliceB = {
67249                 series: me,
67250                 value: me.maximum - value,
67251                 startAngle: splitAngle,
67252                 endAngle: 0,
67253                 rho: me.radius
67254             };
67255             slices.push(sliceA, sliceB);
67256         }
67257         
67258         //do pie slices after.
67259         for (i = 0, ln = slices.length; i < ln; i++) {
67260             slice = slices[i];
67261             sprite = group.getAt(i);
67262             //set pie slice properties
67263             rendererAttributes = Ext.apply({
67264                 segment: {
67265                     startAngle: slice.startAngle,
67266                     endAngle: slice.endAngle,
67267                     margin: 0,
67268                     rho: slice.rho,
67269                     startRho: slice.rho * +donut / 100,
67270                     endRho: slice.rho
67271                 } 
67272             }, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[i % colorArrayLength] } || {}));
67273
67274             item = Ext.apply({},
67275             rendererAttributes.segment, {
67276                 slice: slice,
67277                 series: me,
67278                 storeItem: record,
67279                 index: i
67280             });
67281             items[i] = item;
67282             // Create a new sprite if needed (no height)
67283             if (!sprite) {
67284                 spriteOptions = Ext.apply({
67285                     type: "path",
67286                     group: group
67287                 }, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[i % colorArrayLength] } || {}));
67288                 sprite = surface.add(Ext.apply(spriteOptions, rendererAttributes));
67289             }
67290             slice.sprite = slice.sprite || [];
67291             item.sprite = sprite;
67292             slice.sprite.push(sprite);
67293             if (animate) {
67294                 rendererAttributes = me.renderer(sprite, record, rendererAttributes, i, store);
67295                 sprite._to = rendererAttributes;
67296                 me.onAnimate(sprite, {
67297                     to: rendererAttributes
67298                 });
67299             } else {
67300                 rendererAttributes = me.renderer(sprite, record, Ext.apply(rendererAttributes, {
67301                     hidden: false
67302                 }), i, store);
67303                 sprite.setAttributes(rendererAttributes, true);
67304             }
67305         }
67306         
67307         if (me.needle) {
67308             splitAngle = splitAngle * Math.PI / 180;
67309             
67310             if (!me.needleSprite) {
67311                 me.needleSprite = me.chart.surface.add({
67312                     type: 'path',
67313                     path: ['M', centerX + (me.radius * +donut / 100) * cos(splitAngle),
67314                                 centerY + -Math.abs((me.radius * +donut / 100) * sin(splitAngle)),
67315                            'L', centerX + me.radius * cos(splitAngle),
67316                                 centerY + -Math.abs(me.radius * sin(splitAngle))],
67317                     'stroke-width': 4,
67318                     'stroke': '#222'
67319                 });
67320             } else {
67321                 if (animate) {
67322                     me.onAnimate(me.needleSprite, {
67323                         to: {
67324                         path: ['M', centerX + (me.radius * +donut / 100) * cos(splitAngle),
67325                                     centerY + -Math.abs((me.radius * +donut / 100) * sin(splitAngle)),
67326                                'L', centerX + me.radius * cos(splitAngle),
67327                                     centerY + -Math.abs(me.radius * sin(splitAngle))]
67328                         }
67329                     });
67330                 } else {
67331                     me.needleSprite.setAttributes({
67332                         type: 'path',
67333                         path: ['M', centerX + (me.radius * +donut / 100) * cos(splitAngle),
67334                                     centerY + -Math.abs((me.radius * +donut / 100) * sin(splitAngle)),
67335                                'L', centerX + me.radius * cos(splitAngle),
67336                                     centerY + -Math.abs(me.radius * sin(splitAngle))]
67337                     });
67338                 }
67339             }
67340             me.needleSprite.setAttributes({
67341                 hidden: false    
67342             }, true);
67343         }
67344         
67345         delete me.value;
67346     },
67347     
67348     /**
67349      * Sets the Gauge chart to the current specified value.
67350     */
67351     setValue: function (value) {
67352         this.value = value;
67353         this.drawSeries();
67354     },
67355
67356     // @private callback for when creating a label sprite.
67357     onCreateLabel: function(storeItem, item, i, display) {},
67358
67359     // @private callback for when placing a label sprite.
67360     onPlaceLabel: function(label, storeItem, item, i, display, animate, index) {},
67361
67362     // @private callback for when placing a callout.
67363     onPlaceCallout: function() {},
67364
67365     // @private handles sprite animation for the series.
67366     onAnimate: function(sprite, attr) {
67367         sprite.show();
67368         return this.callParent(arguments);
67369     },
67370
67371     isItemInPoint: function(x, y, item, i) {
67372         return false;
67373     },
67374     
67375     // @private shows all elements in the series.
67376     showAll: function() {
67377         if (!isNaN(this._index)) {
67378             this.__excludes[this._index] = false;
67379             this.drawSeries();
67380         }
67381     },
67382     
67383     /**
67384      * Returns the color of the series (to be displayed as color for the series legend item).
67385      * @param item {Object} Info about the item; same format as returned by #getItemForPoint
67386      */
67387     getLegendColor: function(index) {
67388         var me = this;
67389         return me.colorArrayStyle[index % me.colorArrayStyle.length];
67390     }
67391 });
67392
67393
67394 /**
67395  * @class Ext.chart.series.Line
67396  * @extends Ext.chart.series.Cartesian
67397  * 
67398  <p> 
67399   Creates a Line Chart. A Line Chart is a useful visualization technique to display quantitative information for different 
67400   categories or other real values (as opposed to the bar chart), that can show some progression (or regression) in the dataset.
67401   As with all other series, the Line Series must be appended in the *series* Chart array configuration. See the Chart 
67402   documentation for more information. A typical configuration object for the line series could be:
67403  </p>
67404 {@img Ext.chart.series.Line/Ext.chart.series.Line.png Ext.chart.series.Line chart series}
67405   <pre><code>
67406     var store = Ext.create('Ext.data.JsonStore', {
67407         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
67408         data: [
67409             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
67410             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
67411             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
67412             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
67413             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}                                                
67414         ]
67415     });
67416     
67417     Ext.create('Ext.chart.Chart', {
67418         renderTo: Ext.getBody(),
67419         width: 500,
67420         height: 300,
67421         animate: true,
67422         store: store,
67423         axes: [{
67424             type: 'Numeric',
67425             position: 'bottom',
67426             fields: ['data1'],
67427             label: {
67428                 renderer: Ext.util.Format.numberRenderer('0,0')
67429             },
67430             title: 'Sample Values',
67431             grid: true,
67432             minimum: 0
67433         }, {
67434             type: 'Category',
67435             position: 'left',
67436             fields: ['name'],
67437             title: 'Sample Metrics'
67438         }],
67439         series: [{
67440             type: 'line',
67441             highlight: {
67442                 size: 7,
67443                 radius: 7
67444             },
67445             axis: 'left',
67446             xField: 'name',
67447             yField: 'data1',
67448             markerCfg: {
67449                 type: 'cross',
67450                 size: 4,
67451                 radius: 4,
67452                 'stroke-width': 0
67453             }
67454         }, {
67455             type: 'line',
67456             highlight: {
67457                 size: 7,
67458                 radius: 7
67459             },
67460             axis: 'left',
67461             fill: true,
67462             xField: 'name',
67463             yField: 'data3',
67464             markerCfg: {
67465                 type: 'circle',
67466                 size: 4,
67467                 radius: 4,
67468                 'stroke-width': 0
67469             }
67470         }]
67471     });
67472    </code></pre>
67473  
67474  <p> 
67475   In this configuration we're adding two series (or lines), one bound to the `data1` property of the store and the other to `data3`. The type for both configurations is 
67476   `line`. The `xField` for both series is the same, the name propert of the store. Both line series share the same axis, the left axis. You can set particular marker 
67477   configuration by adding properties onto the markerConfig object. Both series have an object as highlight so that markers animate smoothly to the properties in highlight 
67478   when hovered. The second series has `fill=true` which means that the line will also have an area below it of the same color.
67479  </p>
67480  */
67481
67482 Ext.define('Ext.chart.series.Line', {
67483
67484     /* Begin Definitions */
67485
67486     extend: 'Ext.chart.series.Cartesian',
67487
67488     alternateClassName: ['Ext.chart.LineSeries', 'Ext.chart.LineChart'],
67489
67490     requires: ['Ext.chart.axis.Axis', 'Ext.chart.Shape', 'Ext.draw.Draw', 'Ext.fx.Anim'],
67491
67492     /* End Definitions */
67493
67494     type: 'line',
67495     
67496     alias: 'series.line',
67497
67498     /**
67499      * @cfg {Number} selectionTolerance
67500      * The offset distance from the cursor position to the line series to trigger events (then used for highlighting series, etc).
67501      */
67502     selectionTolerance: 20,
67503     
67504     /**
67505      * @cfg {Boolean} showMarkers
67506      * Whether markers should be displayed at the data points along the line. If true,
67507      * then the {@link #markerConfig} config item will determine the markers' styling.
67508      */
67509     showMarkers: true,
67510
67511     /**
67512      * @cfg {Object} markerConfig
67513      * The display style for the markers. Only used if {@link #showMarkers} is true.
67514      * The markerConfig is a configuration object containing the same set of properties defined in
67515      * the Sprite class. For example, if we were to set red circles as markers to the line series we could
67516      * pass the object:
67517      *
67518      <pre><code>
67519         markerConfig: {
67520             type: 'circle',
67521             radius: 4,
67522             'fill': '#f00'
67523         }
67524      </code></pre>
67525      
67526      */
67527     markerConfig: {},
67528
67529     /**
67530      * @cfg {Object} style
67531      * An object containing styles for the visualization lines. These styles will override the theme styles. 
67532      * Some options contained within the style object will are described next.
67533      */
67534     style: {},
67535     
67536     /**
67537      * @cfg {Boolean} smooth
67538      * If true, the line will be smoothed/rounded around its points, otherwise straight line
67539      * segments will be drawn. Defaults to false.
67540      */
67541     smooth: false,
67542
67543     /**
67544      * @cfg {Boolean} fill
67545      * If true, the area below the line will be filled in using the {@link #style.eefill} and
67546      * {@link #style.opacity} config properties. Defaults to false.
67547      */
67548     fill: false,
67549
67550     constructor: function(config) {
67551         this.callParent(arguments);
67552         var me = this,
67553             surface = me.chart.surface,
67554             shadow = me.chart.shadow,
67555             i, l;
67556         Ext.apply(me, config, {
67557             highlightCfg: {
67558                 'stroke-width': 3
67559             },
67560             shadowAttributes: [{
67561                 "stroke-width": 6,
67562                 "stroke-opacity": 0.05,
67563                 stroke: 'rgb(0, 0, 0)',
67564                 translate: {
67565                     x: 1,
67566                     y: 1
67567                 }
67568             }, {
67569                 "stroke-width": 4,
67570                 "stroke-opacity": 0.1,
67571                 stroke: 'rgb(0, 0, 0)',
67572                 translate: {
67573                     x: 1,
67574                     y: 1
67575                 }
67576             }, {
67577                 "stroke-width": 2,
67578                 "stroke-opacity": 0.15,
67579                 stroke: 'rgb(0, 0, 0)',
67580                 translate: {
67581                     x: 1,
67582                     y: 1
67583                 }
67584             }]
67585         });
67586         me.group = surface.getGroup(me.seriesId);
67587         if (me.showMarkers) {
67588             me.markerGroup = surface.getGroup(me.seriesId + '-markers');
67589         }
67590         if (shadow) {
67591             for (i = 0, l = this.shadowAttributes.length; i < l; i++) {
67592                 me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
67593             }
67594         }
67595     },
67596     
67597     // @private makes an average of points when there are more data points than pixels to be rendered.
67598     shrink: function(xValues, yValues, size) {
67599         // Start at the 2nd point...
67600         var len = xValues.length,
67601             ratio = Math.floor(len / size),
67602             i = 1,
67603             xSum = 0,
67604             ySum = 0,
67605             xRes = [xValues[0]],
67606             yRes = [yValues[0]];
67607         
67608         for (; i < len; ++i) {
67609             xSum += xValues[i] || 0;
67610             ySum += yValues[i] || 0;
67611             if (i % ratio == 0) {
67612                 xRes.push(xSum/ratio);
67613                 yRes.push(ySum/ratio);
67614                 xSum = 0;
67615                 ySum = 0;
67616             }
67617         }
67618         return {
67619             x: xRes,
67620             y: yRes
67621         };
67622     },
67623
67624     /**
67625      * Draws the series for the current chart.
67626      */
67627     drawSeries: function() {
67628         var me = this,
67629             chart = me.chart,
67630             store = chart.substore || chart.store,
67631             surface = chart.surface,
67632             chartBBox = chart.chartBBox,
67633             bbox = {},
67634             group = me.group,
67635             gutterX = chart.maxGutter[0],
67636             gutterY = chart.maxGutter[1],
67637             showMarkers = me.showMarkers,
67638             markerGroup = me.markerGroup,
67639             enableShadows = chart.shadow,
67640             shadowGroups = me.shadowGroups,
67641             shadowAttributes = this.shadowAttributes,
67642             lnsh = shadowGroups.length,
67643             dummyPath = ["M"],
67644             path = ["M"],
67645             markerIndex = chart.markerIndex,
67646             axes = [].concat(me.axis),
67647             shadowGroup,
67648             shadowBarAttr,
67649             xValues = [],
67650             yValues = [],
67651             onbreak = false,
67652             markerStyle = me.markerStyle,
67653             seriesStyle = me.seriesStyle,
67654             seriesLabelStyle = me.seriesLabelStyle,
67655             colorArrayStyle = me.colorArrayStyle,
67656             colorArrayLength = colorArrayStyle && colorArrayStyle.length || 0,
67657             seriesIdx = me.seriesIdx, shadows, shadow, shindex, fromPath, fill, fillPath, rendererAttributes,
67658             x, y, prevX, prevY, firstY, markerCount, i, j, ln, axis, ends, marker, markerAux, item, xValue,
67659             yValue, coords, xScale, yScale, minX, maxX, minY, maxY, line, animation, endMarkerStyle,
67660             endLineStyle, type, props, firstMarker;
67661         
67662         //if store is empty then there's nothing to draw.
67663         if (!store || !store.getCount()) {
67664             return;
67665         }
67666         
67667         //prepare style objects for line and markers
67668         endMarkerStyle = Ext.apply(markerStyle, me.markerConfig);
67669         type = endMarkerStyle.type;
67670         delete endMarkerStyle.type;
67671         endLineStyle = Ext.apply(seriesStyle, me.style);
67672         //if no stroke with is specified force it to 0.5 because this is
67673         //about making *lines*
67674         if (!endLineStyle['stroke-width']) {
67675             endLineStyle['stroke-width'] = 0.5;
67676         }
67677         //If we're using a time axis and we need to translate the points,
67678         //then reuse the first markers as the last markers.
67679         if (markerIndex && markerGroup && markerGroup.getCount()) {
67680             for (i = 0; i < markerIndex; i++) {
67681                 marker = markerGroup.getAt(i);
67682                 markerGroup.remove(marker);
67683                 markerGroup.add(marker);
67684                 markerAux = markerGroup.getAt(markerGroup.getCount() - 2);
67685                 marker.setAttributes({
67686                     x: 0,
67687                     y: 0,
67688                     translate: {
67689                         x: markerAux.attr.translation.x,
67690                         y: markerAux.attr.translation.y
67691                     }
67692                 }, true);
67693             }
67694         }
67695         
67696         me.unHighlightItem();
67697         me.cleanHighlights();
67698
67699         me.setBBox();
67700         bbox = me.bbox;
67701
67702         me.clipRect = [bbox.x, bbox.y, bbox.width, bbox.height];
67703
67704         for (i = 0, ln = axes.length; i < ln; i++) { 
67705             axis = chart.axes.get(axes[i]);
67706             if (axis) {
67707                 ends = axis.calcEnds();
67708                 if (axis.position == 'top' || axis.position == 'bottom') {
67709                     minX = ends.from;
67710                     maxX = ends.to;
67711                 }
67712                 else {
67713                     minY = ends.from;
67714                     maxY = ends.to;
67715                 }
67716             }
67717         }
67718         // If a field was specified without a corresponding axis, create one to get bounds
67719         //only do this for the axis where real values are bound (that's why we check for
67720         //me.axis)
67721         if (me.xField && !Ext.isNumber(minX)
67722             && (me.axis == 'bottom' || me.axis == 'top')) {
67723             axis = Ext.create('Ext.chart.axis.Axis', {
67724                 chart: chart,
67725                 fields: [].concat(me.xField)
67726             }).calcEnds();
67727             minX = axis.from;
67728             maxX = axis.to;
67729         }
67730         if (me.yField && !Ext.isNumber(minY)
67731             && (me.axis == 'right' || me.axis == 'left')) {
67732             axis = Ext.create('Ext.chart.axis.Axis', {
67733                 chart: chart,
67734                 fields: [].concat(me.yField)
67735             }).calcEnds();
67736             minY = axis.from;
67737             maxY = axis.to;
67738         }
67739
67740         if (isNaN(minX)) {
67741             minX = 0;
67742             xScale = bbox.width / (store.getCount() - 1);
67743         }
67744         else {
67745             xScale = bbox.width / (maxX - minX);
67746         }
67747
67748         if (isNaN(minY)) {
67749             minY = 0;
67750             yScale = bbox.height / (store.getCount() - 1);
67751         } 
67752         else {
67753             yScale = bbox.height / (maxY - minY);
67754         }
67755
67756         store.each(function(record, i) {
67757             xValue = record.get(me.xField);
67758             yValue = record.get(me.yField);
67759             //skip undefined values
67760             if (typeof yValue == 'undefined' || (typeof yValue == 'string' && !yValue)) {
67761                 if (Ext.isDefined(Ext.global.console)) {
67762                     Ext.global.console.warn("[Ext.chart.series.Line]  Skipping a store element with an undefined value at ", record, xValue, yValue);
67763                 }
67764                 return;
67765             }
67766             // Ensure a value
67767             if (typeof xValue == 'string' || typeof xValue == 'object'
67768                 //set as uniform distribution if the axis is a category axis.
67769                 || (me.axis != 'top' && me.axis != 'bottom')) {
67770                 xValue = i;
67771             }
67772             if (typeof yValue == 'string' || typeof yValue == 'object'
67773                 //set as uniform distribution if the axis is a category axis.
67774                 || (me.axis != 'left' && me.axis != 'right')) {
67775                 yValue = i;
67776             }
67777             xValues.push(xValue);
67778             yValues.push(yValue);
67779         }, me);
67780
67781         ln = xValues.length;
67782         if (ln > bbox.width) {
67783             coords = me.shrink(xValues, yValues, bbox.width);
67784             xValues = coords.x;
67785             yValues = coords.y;
67786         }
67787
67788         me.items = [];
67789
67790         ln = xValues.length;
67791         for (i = 0; i < ln; i++) {
67792             xValue = xValues[i];
67793             yValue = yValues[i];
67794             if (yValue === false) {
67795                 if (path.length == 1) {
67796                     path = [];
67797                 }
67798                 onbreak = true;
67799                 me.items.push(false);
67800                 continue;
67801             } else {
67802                 x = (bbox.x + (xValue - minX) * xScale).toFixed(2);
67803                 y = ((bbox.y + bbox.height) - (yValue - minY) * yScale).toFixed(2);
67804                 if (onbreak) {
67805                     onbreak = false;
67806                     path.push('M');
67807                 } 
67808                 path = path.concat([x, y]);
67809             }
67810             if ((typeof firstY == 'undefined') && (typeof y != 'undefined')) {
67811                 firstY = y;
67812             }
67813             // If this is the first line, create a dummypath to animate in from.
67814             if (!me.line || chart.resizing) {
67815                 dummyPath = dummyPath.concat([x, bbox.y + bbox.height / 2]);
67816             }
67817
67818             // When resizing, reset before animating
67819             if (chart.animate && chart.resizing && me.line) {
67820                 me.line.setAttributes({
67821                     path: dummyPath
67822                 }, true);
67823                 if (me.fillPath) {
67824                     me.fillPath.setAttributes({
67825                         path: dummyPath,
67826                         opacity: 0.2
67827                     }, true);
67828                 }
67829                 if (me.line.shadows) {
67830                     shadows = me.line.shadows;
67831                     for (j = 0, lnsh = shadows.length; j < lnsh; j++) {
67832                         shadow = shadows[j];
67833                         shadow.setAttributes({
67834                             path: dummyPath
67835                         }, true);
67836                     }
67837                 }
67838             }
67839             if (showMarkers) {
67840                 marker = markerGroup.getAt(i);
67841                 if (!marker) {
67842                     marker = Ext.chart.Shape[type](surface, Ext.apply({
67843                         group: [group, markerGroup],
67844                         x: 0, y: 0,
67845                         translate: {
67846                             x: prevX || x, 
67847                             y: prevY || (bbox.y + bbox.height / 2)
67848                         },
67849                         value: '"' + xValue + ', ' + yValue + '"'
67850                     }, endMarkerStyle));
67851                     marker._to = {
67852                         translate: {
67853                             x: x,
67854                             y: y
67855                         }
67856                     };
67857                 } else {
67858                     marker.setAttributes({
67859                         value: '"' + xValue + ', ' + yValue + '"',
67860                         x: 0, y: 0,
67861                         hidden: false
67862                     }, true);
67863                     marker._to = {
67864                         translate: {
67865                             x: x, y: y
67866                         }
67867                     };
67868                 }
67869             }
67870             me.items.push({
67871                 series: me,
67872                 value: [xValue, yValue],
67873                 point: [x, y],
67874                 sprite: marker,
67875                 storeItem: store.getAt(i)
67876             });
67877             prevX = x;
67878             prevY = y;
67879         }
67880         
67881         if (path.length <= 1) {
67882             //nothing to be rendered
67883             return;    
67884         }
67885         
67886         if (me.smooth) {
67887             path = Ext.draw.Draw.smooth(path, 6);
67888         }
67889         
67890         //Correct path if we're animating timeAxis intervals
67891         if (chart.markerIndex && me.previousPath) {
67892             fromPath = me.previousPath;
67893             fromPath.splice(1, 2);
67894         } else {
67895             fromPath = path;
67896         }
67897
67898         // Only create a line if one doesn't exist.
67899         if (!me.line) {
67900             me.line = surface.add(Ext.apply({
67901                 type: 'path',
67902                 group: group,
67903                 path: dummyPath,
67904                 stroke: endLineStyle.stroke || endLineStyle.fill
67905             }, endLineStyle || {}));
67906             //unset fill here (there's always a default fill withing the themes).
67907             me.line.setAttributes({
67908                 fill: 'none'
67909             });
67910             if (!endLineStyle.stroke && colorArrayLength) {
67911                 me.line.setAttributes({
67912                     stroke: colorArrayStyle[seriesIdx % colorArrayLength]
67913                 }, true);
67914             }
67915             if (enableShadows) {
67916                 //create shadows
67917                 shadows = me.line.shadows = [];                
67918                 for (shindex = 0; shindex < lnsh; shindex++) {
67919                     shadowBarAttr = shadowAttributes[shindex];
67920                     shadowBarAttr = Ext.apply({}, shadowBarAttr, { path: dummyPath });
67921                     shadow = chart.surface.add(Ext.apply({}, {
67922                         type: 'path',
67923                         group: shadowGroups[shindex]
67924                     }, shadowBarAttr));
67925                     shadows.push(shadow);
67926                 }
67927             }
67928         }
67929         if (me.fill) {
67930             fillPath = path.concat([
67931                 ["L", x, bbox.y + bbox.height],
67932                 ["L", bbox.x, bbox.y + bbox.height],
67933                 ["L", bbox.x, firstY]
67934             ]);
67935             if (!me.fillPath) {
67936                 me.fillPath = surface.add({
67937                     group: group,
67938                     type: 'path',
67939                     opacity: endLineStyle.opacity || 0.3,
67940                     fill: colorArrayStyle[seriesIdx % colorArrayLength] || endLineStyle.fill,
67941                     path: dummyPath
67942                 });
67943             }
67944         }
67945         markerCount = showMarkers && markerGroup.getCount();
67946         if (chart.animate) {
67947             fill = me.fill;
67948             line = me.line;
67949             //Add renderer to line. There is not unique record associated with this.
67950             rendererAttributes = me.renderer(line, false, { path: path }, i, store);
67951             Ext.apply(rendererAttributes, endLineStyle || {}, {
67952                 stroke: endLineStyle.stroke || endLineStyle.fill
67953             });
67954             //fill should not be used here but when drawing the special fill path object
67955             delete rendererAttributes.fill;
67956             if (chart.markerIndex && me.previousPath) {
67957                 me.animation = animation = me.onAnimate(line, {
67958                     to: rendererAttributes,
67959                     from: {
67960                         path: fromPath
67961                     }
67962                 });
67963             } else {
67964                 me.animation = animation = me.onAnimate(line, {
67965                     to: rendererAttributes
67966                 });
67967             }
67968             //animate shadows
67969             if (enableShadows) {
67970                 shadows = line.shadows;
67971                 for(j = 0; j < lnsh; j++) {
67972                     if (chart.markerIndex && me.previousPath) {
67973                         me.onAnimate(shadows[j], {
67974                             to: { path: path },
67975                             from: { path: fromPath }
67976                         });
67977                     } else {
67978                         me.onAnimate(shadows[j], {
67979                             to: { path: path }
67980                         });
67981                     }
67982                 }
67983             }
67984             //animate fill path
67985             if (fill) {
67986                 me.onAnimate(me.fillPath, {
67987                     to: Ext.apply({}, {
67988                         path: fillPath,
67989                         fill: colorArrayStyle[seriesIdx % colorArrayLength] || endLineStyle.fill
67990                     }, endLineStyle || {})
67991                 });
67992             }
67993             //animate markers
67994             if (showMarkers) {
67995                 for(i = 0; i < ln; i++) {
67996                     item = markerGroup.getAt(i);
67997                     if (item) {
67998                         if (me.items[i]) {
67999                             rendererAttributes = me.renderer(item, store.getAt(i), item._to, i, store);
68000                             me.onAnimate(item, {
68001                                 to: Ext.apply(rendererAttributes, endMarkerStyle || {})
68002                             });
68003                         } else {
68004                             item.setAttributes(Ext.apply({
68005                                 hidden: true 
68006                             }, item._to), true);
68007                         }
68008                     }
68009                 }
68010                 for(; i < markerCount; i++) {
68011                     item = markerGroup.getAt(i);
68012                     item.hide(true);
68013                 }
68014 //                for(i = 0; i < (chart.markerIndex || 0)-1; i++) {
68015 //                    item = markerGroup.getAt(i);
68016 //                    item.hide(true);
68017 //                }
68018             }
68019         } else {
68020             rendererAttributes = me.renderer(me.line, false, { path: path, hidden: false }, i, store);
68021             Ext.apply(rendererAttributes, endLineStyle || {}, {
68022                 stroke: endLineStyle.stroke || endLineStyle.fill
68023             });
68024             //fill should not be used here but when drawing the special fill path object
68025             delete rendererAttributes.fill;
68026             me.line.setAttributes(rendererAttributes, true);
68027             //set path for shadows
68028             if (enableShadows) {
68029                 shadows = me.line.shadows;
68030                 for(j = 0; j < lnsh; j++) {
68031                     shadows[j].setAttributes({
68032                         path: path
68033                     }, true);
68034                 }
68035             }
68036             if (me.fill) {
68037                 me.fillPath.setAttributes({
68038                     path: fillPath
68039                 }, true);
68040             }
68041             if (showMarkers) {
68042                 for(i = 0; i < ln; i++) {
68043                     item = markerGroup.getAt(i);
68044                     if (item) {
68045                         if (me.items[i]) {
68046                             rendererAttributes = me.renderer(item, store.getAt(i), item._to, i, store);
68047                             item.setAttributes(Ext.apply(endMarkerStyle || {}, rendererAttributes || {}), true);
68048                         } else {
68049                             item.hide(true);
68050                         }
68051                     }
68052                 }
68053                 for(; i < markerCount; i++) {
68054                     item = markerGroup.getAt(i);
68055                     item.hide(true);
68056                 }
68057             }
68058         }
68059
68060         if (chart.markerIndex) {
68061             path.splice(1, 0, path[1], path[2]);
68062             me.previousPath = path;
68063         }
68064         me.renderLabels();
68065         me.renderCallouts();
68066     },
68067     
68068     // @private called when a label is to be created.
68069     onCreateLabel: function(storeItem, item, i, display) {
68070         var me = this,
68071             group = me.labelsGroup,
68072             config = me.label,
68073             bbox = me.bbox,
68074             endLabelStyle = Ext.apply(config, me.seriesLabelStyle);
68075
68076         return me.chart.surface.add(Ext.apply({
68077             'type': 'text',
68078             'text-anchor': 'middle',
68079             'group': group,
68080             'x': item.point[0],
68081             'y': bbox.y + bbox.height / 2
68082         }, endLabelStyle || {}));
68083     },
68084     
68085     // @private called when a label is to be created.
68086     onPlaceLabel: function(label, storeItem, item, i, display, animate) {
68087         var me = this,
68088             chart = me.chart,
68089             resizing = chart.resizing,
68090             config = me.label,
68091             format = config.renderer,
68092             field = config.field,
68093             bbox = me.bbox,
68094             x = item.point[0],
68095             y = item.point[1],
68096             radius = item.sprite.attr.radius,
68097             bb, width, height;
68098         
68099         label.setAttributes({
68100             text: format(storeItem.get(field)),
68101             hidden: true
68102         }, true);
68103         
68104         if (display == 'rotate') {
68105             label.setAttributes({
68106                 'text-anchor': 'start',
68107                 'rotation': {
68108                     x: x,
68109                     y: y,
68110                     degrees: -45
68111                 }
68112             }, true);
68113             //correct label position to fit into the box
68114             bb = label.getBBox();
68115             width = bb.width;
68116             height = bb.height;
68117             x = x < bbox.x? bbox.x : x;
68118             x = (x + width > bbox.x + bbox.width)? (x - (x + width - bbox.x - bbox.width)) : x;
68119             y = (y - height < bbox.y)? bbox.y + height : y;
68120         
68121         } else if (display == 'under' || display == 'over') {
68122             //TODO(nicolas): find out why width/height values in circle bounding boxes are undefined.
68123             bb = item.sprite.getBBox();
68124             bb.width = bb.width || (radius * 2);
68125             bb.height = bb.height || (radius * 2);
68126             y = y + (display == 'over'? -bb.height : bb.height);
68127             //correct label position to fit into the box
68128             bb = label.getBBox();
68129             width = bb.width/2;
68130             height = bb.height/2;
68131             x = x - width < bbox.x? bbox.x + width : x;
68132             x = (x + width > bbox.x + bbox.width) ? (x - (x + width - bbox.x - bbox.width)) : x;
68133             y = y - height < bbox.y? bbox.y + height : y;
68134             y = (y + height > bbox.y + bbox.height) ? (y - (y + height - bbox.y - bbox.height)) : y;
68135         }
68136         
68137         if (me.chart.animate && !me.chart.resizing) {
68138             label.show(true);
68139             me.onAnimate(label, {
68140                 to: {
68141                     x: x,
68142                     y: y
68143                 }
68144             });
68145         } else {
68146             label.setAttributes({
68147                 x: x,
68148                 y: y
68149             }, true);
68150             if (resizing) {
68151                 me.animation.on('afteranimate', function() {
68152                     label.show(true);
68153                 });
68154             } else {
68155                 label.show(true);
68156             }
68157         }
68158     },
68159
68160     //@private Overriding highlights.js highlightItem method.
68161     highlightItem: function() {
68162         var me = this;
68163         me.callParent(arguments);
68164         if (this.line && !this.highlighted) {
68165             if (!('__strokeWidth' in this.line)) {
68166                 this.line.__strokeWidth = this.line.attr['stroke-width'] || 0;
68167             }
68168             if (this.line.__anim) {
68169                 this.line.__anim.paused = true;
68170             }
68171             this.line.__anim = Ext.create('Ext.fx.Anim', {
68172                 target: this.line,
68173                 to: {
68174                     'stroke-width': this.line.__strokeWidth + 3
68175                 }
68176             });
68177             this.highlighted = true;
68178         }
68179     },
68180
68181     //@private Overriding highlights.js unHighlightItem method.
68182     unHighlightItem: function() {
68183         var me = this;
68184         me.callParent(arguments);
68185         if (this.line && this.highlighted) {
68186             this.line.__anim = Ext.create('Ext.fx.Anim', {
68187                 target: this.line,
68188                 to: {
68189                     'stroke-width': this.line.__strokeWidth
68190                 }
68191             });
68192             this.highlighted = false;
68193         }
68194     },
68195
68196     //@private called when a callout needs to be placed.
68197     onPlaceCallout : function(callout, storeItem, item, i, display, animate, index) {
68198         if (!display) {
68199             return;
68200         }
68201         
68202         var me = this,
68203             chart = me.chart,
68204             surface = chart.surface,
68205             resizing = chart.resizing,
68206             config = me.callouts,
68207             items = me.items,
68208             prev = i == 0? false : items[i -1].point,
68209             next = (i == items.length -1)? false : items[i +1].point,
68210             cur = [+item.point[0], +item.point[1]],
68211             dir, norm, normal, a, aprev, anext,
68212             offsetFromViz = config.offsetFromViz || 30,
68213             offsetToSide = config.offsetToSide || 10,
68214             offsetBox = config.offsetBox || 3,
68215             boxx, boxy, boxw, boxh,
68216             p, clipRect = me.clipRect,
68217             bbox = {
68218                 width: config.styles.width || 10,
68219                 height: config.styles.height || 10
68220             },
68221             x, y;
68222
68223         //get the right two points
68224         if (!prev) {
68225             prev = cur;
68226         }
68227         if (!next) {
68228             next = cur;
68229         }
68230         a = (next[1] - prev[1]) / (next[0] - prev[0]);
68231         aprev = (cur[1] - prev[1]) / (cur[0] - prev[0]);
68232         anext = (next[1] - cur[1]) / (next[0] - cur[0]);
68233         
68234         norm = Math.sqrt(1 + a * a);
68235         dir = [1 / norm, a / norm];
68236         normal = [-dir[1], dir[0]];
68237         
68238         //keep the label always on the outer part of the "elbow"
68239         if (aprev > 0 && anext < 0 && normal[1] < 0
68240             || aprev < 0 && anext > 0 && normal[1] > 0) {
68241             normal[0] *= -1;
68242             normal[1] *= -1;
68243         } else if (Math.abs(aprev) < Math.abs(anext) && normal[0] < 0
68244                    || Math.abs(aprev) > Math.abs(anext) && normal[0] > 0) {
68245             normal[0] *= -1;
68246             normal[1] *= -1;
68247         }
68248         //position
68249         x = cur[0] + normal[0] * offsetFromViz;
68250         y = cur[1] + normal[1] * offsetFromViz;
68251
68252         //box position and dimensions
68253         boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
68254         boxy = y - bbox.height /2 - offsetBox;
68255         boxw = bbox.width + 2 * offsetBox;
68256         boxh = bbox.height + 2 * offsetBox;
68257         
68258         //now check if we're out of bounds and invert the normal vector correspondingly
68259         //this may add new overlaps between labels (but labels won't be out of bounds).
68260         if (boxx < clipRect[0] || (boxx + boxw) > (clipRect[0] + clipRect[2])) {
68261             normal[0] *= -1;
68262         }
68263         if (boxy < clipRect[1] || (boxy + boxh) > (clipRect[1] + clipRect[3])) {
68264             normal[1] *= -1;
68265         }
68266
68267         //update positions
68268         x = cur[0] + normal[0] * offsetFromViz;
68269         y = cur[1] + normal[1] * offsetFromViz;
68270         
68271         //update box position and dimensions
68272         boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
68273         boxy = y - bbox.height /2 - offsetBox;
68274         boxw = bbox.width + 2 * offsetBox;
68275         boxh = bbox.height + 2 * offsetBox;
68276         
68277         if (chart.animate) {
68278             //set the line from the middle of the pie to the box.
68279             me.onAnimate(callout.lines, {
68280                 to: {
68281                     path: ["M", cur[0], cur[1], "L", x, y, "Z"]
68282                 }
68283             });
68284             //set component position
68285             if (callout.panel) {
68286                 callout.panel.setPosition(boxx, boxy, true);
68287             }
68288         }
68289         else {
68290             //set the line from the middle of the pie to the box.
68291             callout.lines.setAttributes({
68292                 path: ["M", cur[0], cur[1], "L", x, y, "Z"]
68293             }, true);
68294             //set component position
68295             if (callout.panel) {
68296                 callout.panel.setPosition(boxx, boxy);
68297             }
68298         }
68299         for (p in callout) {
68300             callout[p].show(true);
68301         }
68302     },
68303     
68304     isItemInPoint: function(x, y, item, i) {
68305         var me = this,
68306             items = me.items,
68307             tolerance = me.selectionTolerance,
68308             result = null,
68309             prevItem,
68310             nextItem,
68311             prevPoint,
68312             nextPoint,
68313             ln,
68314             x1,
68315             y1,
68316             x2,
68317             y2,
68318             xIntersect,
68319             yIntersect,
68320             dist1, dist2, dist, midx, midy,
68321             sqrt = Math.sqrt, abs = Math.abs;
68322         
68323         nextItem = items[i];
68324         prevItem = i && items[i - 1];
68325         
68326         if (i >= ln) {
68327             prevItem = items[ln - 1];
68328         }
68329         prevPoint = prevItem && prevItem.point;
68330         nextPoint = nextItem && nextItem.point;
68331         x1 = prevItem ? prevPoint[0] : nextPoint[0] - tolerance;
68332         y1 = prevItem ? prevPoint[1] : nextPoint[1];
68333         x2 = nextItem ? nextPoint[0] : prevPoint[0] + tolerance;
68334         y2 = nextItem ? nextPoint[1] : prevPoint[1];
68335         dist1 = sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
68336         dist2 = sqrt((x - x2) * (x - x2) + (y - y2) * (y - y2));
68337         dist = Math.min(dist1, dist2);
68338         
68339         if (dist <= tolerance) {
68340             return dist == dist1? prevItem : nextItem;
68341         }
68342         return false;
68343     },
68344     
68345     // @private toggle visibility of all series elements (markers, sprites).
68346     toggleAll: function(show) {
68347         var me = this,
68348             i, ln, shadow, shadows;
68349         if (!show) {
68350             Ext.chart.series.Line.superclass.hideAll.call(me);
68351         }
68352         else {
68353             Ext.chart.series.Line.superclass.showAll.call(me);
68354         }
68355         if (me.line) {
68356             me.line.setAttributes({
68357                 hidden: !show
68358             }, true);
68359             //hide shadows too
68360             if (me.line.shadows) {
68361                 for (i = 0, shadows = me.line.shadows, ln = shadows.length; i < ln; i++) {
68362                     shadow = shadows[i];
68363                     shadow.setAttributes({
68364                         hidden: !show
68365                     }, true);
68366                 }
68367             }
68368         }
68369         if (me.fillPath) {
68370             me.fillPath.setAttributes({
68371                 hidden: !show
68372             }, true);
68373         }
68374     },
68375     
68376     // @private hide all series elements (markers, sprites).
68377     hideAll: function() {
68378         this.toggleAll(false);
68379     },
68380     
68381     // @private hide all series elements (markers, sprites).
68382     showAll: function() {
68383         this.toggleAll(true);
68384     }
68385 });
68386 /**
68387  * @class Ext.chart.series.Pie
68388  * @extends Ext.chart.series.Series
68389  * 
68390  * Creates a Pie Chart. A Pie Chart is a useful visualization technique to display quantitative information for different 
68391  * categories that also have a meaning as a whole.
68392  * As with all other series, the Pie Series must be appended in the *series* Chart array configuration. See the Chart 
68393  * documentation for more information. A typical configuration object for the pie series could be:
68394  * 
68395 {@img Ext.chart.series.Pie/Ext.chart.series.Pie.png Ext.chart.series.Pie chart series}
68396   <pre><code>
68397     var store = Ext.create('Ext.data.JsonStore', {
68398         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
68399         data: [
68400             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
68401             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
68402             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
68403             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
68404             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}                                                
68405         ]
68406     });
68407     
68408     Ext.create('Ext.chart.Chart', {
68409         renderTo: Ext.getBody(),
68410         width: 500,
68411         height: 300,
68412         animate: true,
68413         store: store,
68414         theme: 'Base:gradients',
68415         series: [{
68416             type: 'pie',
68417             field: 'data1',
68418             showInLegend: true,
68419             tips: {
68420               trackMouse: true,
68421               width: 140,
68422               height: 28,
68423               renderer: function(storeItem, item) {
68424                 //calculate and display percentage on hover
68425                 var total = 0;
68426                 store.each(function(rec) {
68427                     total += rec.get('data1');
68428                 });
68429                 this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data1') / total * 100) + '%');
68430               }
68431             },
68432             highlight: {
68433               segment: {
68434                 margin: 20
68435               }
68436             },
68437             label: {
68438                 field: 'name',
68439                 display: 'rotate',
68440                 contrast: true,
68441                 font: '18px Arial'
68442             }
68443         }]    
68444     });
68445    </code></pre>
68446  
68447  * 
68448  * In this configuration we set `pie` as the type for the series, set an object with specific style properties for highlighting options 
68449  * (triggered when hovering elements). We also set true to `showInLegend` so all the pie slices can be represented by a legend item. 
68450  * We set `data1` as the value of the field to determine the angle span for each pie slice. We also set a label configuration object 
68451  * where we set the field name of the store field to be renderer as text for the label. The labels will also be displayed rotated. 
68452  * We set `contrast` to `true` to flip the color of the label if it is to similar to the background color. Finally, we set the font family 
68453  * and size through the `font` parameter. 
68454  * 
68455  * @xtype pie
68456  *
68457  */
68458 Ext.define('Ext.chart.series.Pie', {
68459
68460     /* Begin Definitions */
68461
68462     alternateClassName: ['Ext.chart.PieSeries', 'Ext.chart.PieChart'],
68463
68464     extend: 'Ext.chart.series.Series',
68465
68466     /* End Definitions */
68467
68468     type: "pie",
68469     
68470     alias: 'series.pie',
68471
68472     rad: Math.PI / 180,
68473
68474     /**
68475      * @cfg {Number} highlightDuration
68476      * The duration for the pie slice highlight effect.
68477      */
68478     highlightDuration: 150,
68479
68480     /**
68481      * @cfg {String} angleField
68482      * The store record field name to be used for the pie angles.
68483      * The values bound to this field name must be positive real numbers.
68484      * This parameter is required.
68485      */
68486     angleField: false,
68487
68488     /**
68489      * @cfg {String} lengthField
68490      * The store record field name to be used for the pie slice lengths.
68491      * The values bound to this field name must be positive real numbers.
68492      * This parameter is optional.
68493      */
68494     lengthField: false,
68495
68496     /**
68497      * @cfg {Boolean|Number} donut
68498      * Whether to set the pie chart as donut chart.
68499      * Default's false. Can be set to a particular percentage to set the radius
68500      * of the donut chart.
68501      */
68502     donut: false,
68503
68504     /**
68505      * @cfg {Boolean} showInLegend
68506      * Whether to add the pie chart elements as legend items. Default's false.
68507      */
68508     showInLegend: false,
68509
68510     /**
68511      * @cfg {Array} colorSet
68512      * An array of color values which will be used, in order, as the pie slice fill colors.
68513      */
68514     
68515     /**
68516      * @cfg {Object} style
68517      * An object containing styles for overriding series styles from Theming.
68518      */
68519     style: {},
68520     
68521     constructor: function(config) {
68522         this.callParent(arguments);
68523         var me = this,
68524             chart = me.chart,
68525             surface = chart.surface,
68526             store = chart.store,
68527             shadow = chart.shadow, i, l, cfg;
68528         Ext.applyIf(me, {
68529             highlightCfg: {
68530                 segment: {
68531                     margin: 20
68532                 }
68533             }
68534         });
68535         Ext.apply(me, config, {            
68536             shadowAttributes: [{
68537                 "stroke-width": 6,
68538                 "stroke-opacity": 1,
68539                 stroke: 'rgb(200, 200, 200)',
68540                 translate: {
68541                     x: 1.2,
68542                     y: 2
68543                 }
68544             },
68545             {
68546                 "stroke-width": 4,
68547                 "stroke-opacity": 1,
68548                 stroke: 'rgb(150, 150, 150)',
68549                 translate: {
68550                     x: 0.9,
68551                     y: 1.5
68552                 }
68553             },
68554             {
68555                 "stroke-width": 2,
68556                 "stroke-opacity": 1,
68557                 stroke: 'rgb(100, 100, 100)',
68558                 translate: {
68559                     x: 0.6,
68560                     y: 1
68561                 }
68562             }]
68563         });
68564         me.group = surface.getGroup(me.seriesId);
68565         if (shadow) {
68566             for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
68567                 me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
68568             }
68569         }
68570         surface.customAttributes.segment = function(opt) {
68571             return me.getSegment(opt);
68572         };
68573     },
68574     
68575     //@private updates some onbefore render parameters.
68576     initialize: function() {
68577         var me = this,
68578             store = me.chart.substore || me.chart.store;
68579         //Add yFields to be used in Legend.js
68580         me.yField = [];
68581         if (me.label.field) {
68582             store.each(function(rec) {
68583                 me.yField.push(rec.get(me.label.field));
68584             });
68585         }
68586     },
68587
68588     // @private returns an object with properties for a PieSlice.
68589     getSegment: function(opt) {
68590         var me = this,
68591             rad = me.rad,
68592             cos = Math.cos,
68593             sin = Math.sin,
68594             abs = Math.abs,
68595             x = me.centerX,
68596             y = me.centerY,
68597             x1 = 0, x2 = 0, x3 = 0, x4 = 0,
68598             y1 = 0, y2 = 0, y3 = 0, y4 = 0,
68599             delta = 1e-2,
68600             r = opt.endRho - opt.startRho,
68601             startAngle = opt.startAngle,
68602             endAngle = opt.endAngle,
68603             midAngle = (startAngle + endAngle) / 2 * rad,
68604             margin = opt.margin || 0,
68605             flag = abs(endAngle - startAngle) > 180,
68606             a1 = Math.min(startAngle, endAngle) * rad,
68607             a2 = Math.max(startAngle, endAngle) * rad,
68608             singleSlice = false;
68609
68610         x += margin * cos(midAngle);
68611         y += margin * sin(midAngle);
68612
68613         x1 = x + opt.startRho * cos(a1);
68614         y1 = y + opt.startRho * sin(a1);
68615
68616         x2 = x + opt.endRho * cos(a1);
68617         y2 = y + opt.endRho * sin(a1);
68618
68619         x3 = x + opt.startRho * cos(a2);
68620         y3 = y + opt.startRho * sin(a2);
68621
68622         x4 = x + opt.endRho * cos(a2);
68623         y4 = y + opt.endRho * sin(a2);
68624
68625         if (abs(x1 - x3) <= delta && abs(y1 - y3) <= delta) {
68626             singleSlice = true;
68627         }
68628         //Solves mysterious clipping bug with IE
68629         if (singleSlice) {
68630             return {
68631                 path: [
68632                 ["M", x1, y1],
68633                 ["L", x2, y2],
68634                 ["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
68635                 ["Z"]]
68636             };
68637         } else {
68638             return {
68639                 path: [
68640                 ["M", x1, y1],
68641                 ["L", x2, y2],
68642                 ["A", opt.endRho, opt.endRho, 0, +flag, 1, x4, y4],
68643                 ["L", x3, y3],
68644                 ["A", opt.startRho, opt.startRho, 0, +flag, 0, x1, y1],
68645                 ["Z"]]
68646             };
68647         }
68648     },
68649
68650     // @private utility function to calculate the middle point of a pie slice.
68651     calcMiddle: function(item) {
68652         var me = this,
68653             rad = me.rad,
68654             slice = item.slice,
68655             x = me.centerX,
68656             y = me.centerY,
68657             startAngle = slice.startAngle,
68658             endAngle = slice.endAngle,
68659             donut = +me.donut,
68660             a1 = Math.min(startAngle, endAngle) * rad,
68661             a2 = Math.max(startAngle, endAngle) * rad,
68662             midAngle = -(a1 + (a2 - a1) / 2),
68663             xm = x + (item.endRho + item.startRho) / 2 * Math.cos(midAngle),
68664             ym = y - (item.endRho + item.startRho) / 2 * Math.sin(midAngle);
68665
68666         item.middle = {
68667             x: xm,
68668             y: ym
68669         };
68670     },
68671
68672     /**
68673      * Draws the series for the current chart.
68674      */
68675     drawSeries: function() {
68676         var me = this,
68677             store = me.chart.substore || me.chart.store,
68678             group = me.group,
68679             animate = me.chart.animate,
68680             field = me.angleField || me.field || me.xField,
68681             lenField = [].concat(me.lengthField),
68682             totalLenField = 0,
68683             colors = me.colorSet,
68684             chart = me.chart,
68685             surface = chart.surface,
68686             chartBBox = chart.chartBBox,
68687             enableShadows = chart.shadow,
68688             shadowGroups = me.shadowGroups,
68689             shadowAttributes = me.shadowAttributes,
68690             lnsh = shadowGroups.length,
68691             rad = me.rad,
68692             layers = lenField.length,
68693             rhoAcum = 0,
68694             donut = +me.donut,
68695             layerTotals = [],
68696             values = {},
68697             fieldLength,
68698             items = [],
68699             passed = false,
68700             totalField = 0,
68701             maxLenField = 0,
68702             cut = 9,
68703             defcut = true,
68704             angle = 0,
68705             seriesStyle = me.seriesStyle,
68706             seriesLabelStyle = me.seriesLabelStyle,
68707             colorArrayStyle = me.colorArrayStyle,
68708             colorArrayLength = colorArrayStyle && colorArrayStyle.length || 0,
68709             gutterX = chart.maxGutter[0],
68710             gutterY = chart.maxGutter[1],
68711             rendererAttributes,
68712             shadowGroup,
68713             shadowAttr,
68714             shadows,
68715             shadow,
68716             shindex,
68717             centerX,
68718             centerY,
68719             deltaRho,
68720             first = 0,
68721             slice,
68722             slices,
68723             sprite,
68724             value,
68725             item,
68726             lenValue,
68727             ln,
68728             record,
68729             i,
68730             j,
68731             startAngle,
68732             endAngle,
68733             middleAngle,
68734             sliceLength,
68735             path,
68736             p,
68737             spriteOptions, bbox;
68738         
68739         Ext.apply(seriesStyle, me.style || {});
68740
68741         me.setBBox();
68742         bbox = me.bbox;
68743
68744         //override theme colors
68745         if (me.colorSet) {
68746             colorArrayStyle = me.colorSet;
68747             colorArrayLength = colorArrayStyle.length;
68748         }
68749         
68750         //if not store or store is empty then there's nothing to draw
68751         if (!store || !store.getCount()) {
68752             return;
68753         }
68754         
68755         me.unHighlightItem();
68756         me.cleanHighlights();
68757
68758         centerX = me.centerX = chartBBox.x + (chartBBox.width / 2);
68759         centerY = me.centerY = chartBBox.y + (chartBBox.height / 2);
68760         me.radius = Math.min(centerX - chartBBox.x, centerY - chartBBox.y);
68761         me.slices = slices = [];
68762         me.items = items = [];
68763
68764         store.each(function(record, i) {
68765             if (this.__excludes && this.__excludes[i]) {
68766                 //hidden series
68767                 return;
68768             }
68769             totalField += +record.get(field);
68770             if (lenField[0]) {
68771                 for (j = 0, totalLenField = 0; j < layers; j++) {
68772                     totalLenField += +record.get(lenField[j]);
68773                 }
68774                 layerTotals[i] = totalLenField;
68775                 maxLenField = Math.max(maxLenField, totalLenField);
68776             }
68777         }, this);
68778
68779         store.each(function(record, i) {
68780             if (this.__excludes && this.__excludes[i]) {
68781                 //hidden series
68782                 return;
68783             } 
68784             value = record.get(field);
68785             middleAngle = angle - 360 * value / totalField / 2;
68786             // TODO - Put up an empty circle
68787             if (isNaN(middleAngle)) {
68788                 middleAngle = 360;
68789                 value = 1;
68790                 totalField = 1;
68791             }
68792             // First slice
68793             if (!i || first == 0) {
68794                 angle = 360 - middleAngle;
68795                 me.firstAngle = angle;
68796                 middleAngle = angle - 360 * value / totalField / 2;
68797             }
68798             endAngle = angle - 360 * value / totalField;
68799             slice = {
68800                 series: me,
68801                 value: value,
68802                 startAngle: angle,
68803                 endAngle: endAngle,
68804                 storeItem: record
68805             };
68806             if (lenField[0]) {
68807                 lenValue = layerTotals[i];
68808                 slice.rho = me.radius * (lenValue / maxLenField);
68809             } else {
68810                 slice.rho = me.radius;
68811             }
68812             slices[i] = slice;
68813             if((slice.startAngle % 360) == (slice.endAngle % 360)) {
68814                 slice.startAngle -= 0.0001;
68815             }
68816             angle = endAngle;
68817             first++;
68818         }, me);
68819         
68820         //do all shadows first.
68821         if (enableShadows) {
68822             for (i = 0, ln = slices.length; i < ln; i++) {
68823                 if (this.__excludes && this.__excludes[i]) {
68824                     //hidden series
68825                     continue;
68826                 }
68827                 slice = slices[i];
68828                 slice.shadowAttrs = [];
68829                 for (j = 0, rhoAcum = 0, shadows = []; j < layers; j++) {
68830                     sprite = group.getAt(i * layers + j);
68831                     deltaRho = lenField[j] ? store.getAt(i).get(lenField[j]) / layerTotals[i] * slice.rho: slice.rho;
68832                     //set pie slice properties
68833                     rendererAttributes = {
68834                         segment: {
68835                             startAngle: slice.startAngle,
68836                             endAngle: slice.endAngle,
68837                             margin: 0,
68838                             rho: slice.rho,
68839                             startRho: rhoAcum + (deltaRho * donut / 100),
68840                             endRho: rhoAcum + deltaRho
68841                         }
68842                     };
68843                     //create shadows
68844                     for (shindex = 0, shadows = []; shindex < lnsh; shindex++) {
68845                         shadowAttr = shadowAttributes[shindex];
68846                         shadow = shadowGroups[shindex].getAt(i);
68847                         if (!shadow) {
68848                             shadow = chart.surface.add(Ext.apply({},
68849                             {
68850                                 type: 'path',
68851                                 group: shadowGroups[shindex],
68852                                 strokeLinejoin: "round"
68853                             },
68854                             rendererAttributes, shadowAttr));
68855                         }
68856                         if (animate) {
68857                             rendererAttributes = me.renderer(shadow, store.getAt(i), Ext.apply({},
68858                             rendererAttributes, shadowAttr), i, store);
68859                             me.onAnimate(shadow, {
68860                                 to: rendererAttributes
68861                             });
68862                         } else {
68863                             rendererAttributes = me.renderer(shadow, store.getAt(i), Ext.apply(shadowAttr, {
68864                                 hidden: false
68865                             }), i, store);
68866                             shadow.setAttributes(rendererAttributes, true);
68867                         }
68868                         shadows.push(shadow);
68869                     }
68870                     slice.shadowAttrs[j] = shadows;
68871                 }
68872             }
68873         }
68874         //do pie slices after.
68875         for (i = 0, ln = slices.length; i < ln; i++) {
68876             if (this.__excludes && this.__excludes[i]) {
68877                 //hidden series
68878                 continue;
68879             }
68880             slice = slices[i];
68881             for (j = 0, rhoAcum = 0; j < layers; j++) {
68882                 sprite = group.getAt(i * layers + j);
68883                 deltaRho = lenField[j] ? store.getAt(i).get(lenField[j]) / layerTotals[i] * slice.rho: slice.rho;
68884                 //set pie slice properties
68885                 rendererAttributes = Ext.apply({
68886                     segment: {
68887                         startAngle: slice.startAngle,
68888                         endAngle: slice.endAngle,
68889                         margin: 0,
68890                         rho: slice.rho,
68891                         startRho: rhoAcum + (deltaRho * donut / 100),
68892                         endRho: rhoAcum + deltaRho
68893                     } 
68894                 }, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[(layers > 1? j : i) % colorArrayLength] } || {}));
68895                 item = Ext.apply({},
68896                 rendererAttributes.segment, {
68897                     slice: slice,
68898                     series: me,
68899                     storeItem: slice.storeItem,
68900                     index: i
68901                 });
68902                 me.calcMiddle(item);
68903                 if (enableShadows) {
68904                     item.shadows = slice.shadowAttrs[j];
68905                 }
68906                 items[i] = item;
68907                 // Create a new sprite if needed (no height)
68908                 if (!sprite) {
68909                     spriteOptions = Ext.apply({
68910                         type: "path",
68911                         group: group,
68912                         middle: item.middle
68913                     }, Ext.apply(seriesStyle, colorArrayStyle && { fill: colorArrayStyle[(layers > 1? j : i) % colorArrayLength] } || {}));
68914                     sprite = surface.add(Ext.apply(spriteOptions, rendererAttributes));
68915                 }
68916                 slice.sprite = slice.sprite || [];
68917                 item.sprite = sprite;
68918                 slice.sprite.push(sprite);
68919                 slice.point = [item.middle.x, item.middle.y];
68920                 if (animate) {
68921                     rendererAttributes = me.renderer(sprite, store.getAt(i), rendererAttributes, i, store);
68922                     sprite._to = rendererAttributes;
68923                     sprite._animating = true;
68924                     me.onAnimate(sprite, {
68925                         to: rendererAttributes,
68926                         listeners: {
68927                             afteranimate: {
68928                                 fn: function() {
68929                                     this._animating = false;
68930                                 },
68931                                 scope: sprite
68932                             }
68933                         }
68934                     });
68935                 } else {
68936                     rendererAttributes = me.renderer(sprite, store.getAt(i), Ext.apply(rendererAttributes, {
68937                         hidden: false
68938                     }), i, store);
68939                     sprite.setAttributes(rendererAttributes, true);
68940                 }
68941                 rhoAcum += deltaRho;
68942             }
68943         }
68944         
68945         // Hide unused bars
68946         ln = group.getCount();
68947         for (i = 0; i < ln; i++) {
68948             if (!slices[(i / layers) >> 0] && group.getAt(i)) {
68949                 group.getAt(i).hide(true);
68950             }
68951         }
68952         if (enableShadows) {
68953             lnsh = shadowGroups.length;
68954             for (shindex = 0; shindex < ln; shindex++) {
68955                 if (!slices[(shindex / layers) >> 0]) {
68956                     for (j = 0; j < lnsh; j++) {
68957                         if (shadowGroups[j].getAt(shindex)) {
68958                             shadowGroups[j].getAt(shindex).hide(true);
68959                         }
68960                     }
68961                 }
68962             }
68963         }
68964         me.renderLabels();
68965         me.renderCallouts();
68966     },
68967
68968     // @private callback for when creating a label sprite.
68969     onCreateLabel: function(storeItem, item, i, display) {
68970         var me = this,
68971             group = me.labelsGroup,
68972             config = me.label,
68973             centerX = me.centerX,
68974             centerY = me.centerY,
68975             middle = item.middle,
68976             endLabelStyle = Ext.apply(me.seriesLabelStyle || {}, config || {});
68977         
68978         return me.chart.surface.add(Ext.apply({
68979             'type': 'text',
68980             'text-anchor': 'middle',
68981             'group': group,
68982             'x': middle.x,
68983             'y': middle.y
68984         }, endLabelStyle));
68985     },
68986
68987     // @private callback for when placing a label sprite.
68988     onPlaceLabel: function(label, storeItem, item, i, display, animate, index) {
68989         var me = this,
68990             chart = me.chart,
68991             resizing = chart.resizing,
68992             config = me.label,
68993             format = config.renderer,
68994             field = [].concat(config.field),
68995             centerX = me.centerX,
68996             centerY = me.centerY,
68997             middle = item.middle,
68998             opt = {
68999                 x: middle.x,
69000                 y: middle.y
69001             },
69002             x = middle.x - centerX,
69003             y = middle.y - centerY,
69004             from = {},
69005             rho = 1,
69006             theta = Math.atan2(y, x || 1),
69007             dg = theta * 180 / Math.PI,
69008             prevDg;
69009         
69010         function fixAngle(a) {
69011             if (a < 0) a += 360;
69012             return a % 360;
69013         }
69014
69015         label.setAttributes({
69016             text: format(storeItem.get(field[index]))
69017         }, true);
69018
69019         switch (display) {
69020         case 'outside':
69021             rho = Math.sqrt(x * x + y * y) * 2;
69022             //update positions
69023             opt.x = rho * Math.cos(theta) + centerX;
69024             opt.y = rho * Math.sin(theta) + centerY;
69025             break;
69026
69027         case 'rotate':
69028             dg = fixAngle(dg);
69029             dg = (dg > 90 && dg < 270) ? dg + 180: dg;
69030
69031             prevDg = label.attr.rotation.degrees;
69032             if (prevDg != null && Math.abs(prevDg - dg) > 180) {
69033                 if (dg > prevDg) {
69034                     dg -= 360;
69035                 } else {
69036                     dg += 360;
69037                 }
69038                 dg = dg % 360;
69039             } else {
69040                 dg = fixAngle(dg);
69041             }
69042             //update rotation angle
69043             opt.rotate = {
69044                 degrees: dg,
69045                 x: opt.x,
69046                 y: opt.y
69047             };
69048             break;
69049
69050         default:
69051             break;
69052         }
69053         //ensure the object has zero translation
69054         opt.translate = {
69055             x: 0, y: 0    
69056         };
69057         if (animate && !resizing && (display != 'rotate' || prevDg != null)) {
69058             me.onAnimate(label, {
69059                 to: opt
69060             });
69061         } else {
69062             label.setAttributes(opt, true);
69063         }
69064         label._from = from;
69065     },
69066
69067     // @private callback for when placing a callout sprite.
69068     onPlaceCallout: function(callout, storeItem, item, i, display, animate, index) {
69069         var me = this,
69070             chart = me.chart,
69071             resizing = chart.resizing,
69072             config = me.callouts,
69073             centerX = me.centerX,
69074             centerY = me.centerY,
69075             middle = item.middle,
69076             opt = {
69077                 x: middle.x,
69078                 y: middle.y
69079             },
69080             x = middle.x - centerX,
69081             y = middle.y - centerY,
69082             rho = 1,
69083             rhoCenter,
69084             theta = Math.atan2(y, x || 1),
69085             bbox = callout.label.getBBox(),
69086             offsetFromViz = 20,
69087             offsetToSide = 10,
69088             offsetBox = 10,
69089             p;
69090
69091         //should be able to config this.
69092         rho = item.endRho + offsetFromViz;
69093         rhoCenter = (item.endRho + item.startRho) / 2 + (item.endRho - item.startRho) / 3;
69094         //update positions
69095         opt.x = rho * Math.cos(theta) + centerX;
69096         opt.y = rho * Math.sin(theta) + centerY;
69097
69098         x = rhoCenter * Math.cos(theta);
69099         y = rhoCenter * Math.sin(theta);
69100
69101         if (chart.animate) {
69102             //set the line from the middle of the pie to the box.
69103             me.onAnimate(callout.lines, {
69104                 to: {
69105                     path: ["M", x + centerX, y + centerY, "L", opt.x, opt.y, "Z", "M", opt.x, opt.y, "l", x > 0 ? offsetToSide: -offsetToSide, 0, "z"]
69106                 }
69107             });
69108             //set box position
69109             me.onAnimate(callout.box, {
69110                 to: {
69111                     x: opt.x + (x > 0 ? offsetToSide: -(offsetToSide + bbox.width + 2 * offsetBox)),
69112                     y: opt.y + (y > 0 ? ( - bbox.height - offsetBox / 2) : ( - bbox.height - offsetBox / 2)),
69113                     width: bbox.width + 2 * offsetBox,
69114                     height: bbox.height + 2 * offsetBox
69115                 }
69116             });
69117             //set text position
69118             me.onAnimate(callout.label, {
69119                 to: {
69120                     x: opt.x + (x > 0 ? (offsetToSide + offsetBox) : -(offsetToSide + bbox.width + offsetBox)),
69121                     y: opt.y + (y > 0 ? -bbox.height / 4: -bbox.height / 4)
69122                 }
69123             });
69124         } else {
69125             //set the line from the middle of the pie to the box.
69126             callout.lines.setAttributes({
69127                 path: ["M", x + centerX, y + centerY, "L", opt.x, opt.y, "Z", "M", opt.x, opt.y, "l", x > 0 ? offsetToSide: -offsetToSide, 0, "z"]
69128             },
69129             true);
69130             //set box position
69131             callout.box.setAttributes({
69132                 x: opt.x + (x > 0 ? offsetToSide: -(offsetToSide + bbox.width + 2 * offsetBox)),
69133                 y: opt.y + (y > 0 ? ( - bbox.height - offsetBox / 2) : ( - bbox.height - offsetBox / 2)),
69134                 width: bbox.width + 2 * offsetBox,
69135                 height: bbox.height + 2 * offsetBox
69136             },
69137             true);
69138             //set text position
69139             callout.label.setAttributes({
69140                 x: opt.x + (x > 0 ? (offsetToSide + offsetBox) : -(offsetToSide + bbox.width + offsetBox)),
69141                 y: opt.y + (y > 0 ? -bbox.height / 4: -bbox.height / 4)
69142             },
69143             true);
69144         }
69145         for (p in callout) {
69146             callout[p].show(true);
69147         }
69148     },
69149
69150     // @private handles sprite animation for the series.
69151     onAnimate: function(sprite, attr) {
69152         sprite.show();
69153         return this.callParent(arguments);
69154     },
69155
69156     isItemInPoint: function(x, y, item, i) {
69157         var me = this,
69158             cx = me.centerX,
69159             cy = me.centerY,
69160             abs = Math.abs,
69161             dx = abs(x - cx),
69162             dy = abs(y - cy),
69163             startAngle = item.startAngle,
69164             endAngle = item.endAngle,
69165             rho = Math.sqrt(dx * dx + dy * dy),
69166             angle = Math.atan2(y - cy, x - cx) / me.rad + 360;
69167         
69168         // normalize to the same range of angles created by drawSeries
69169         if (angle > me.firstAngle) {
69170             angle -= 360;
69171         }
69172         return (angle <= startAngle && angle > endAngle
69173                 && rho >= item.startRho && rho <= item.endRho);
69174     },
69175     
69176     // @private hides all elements in the series.
69177     hideAll: function() {
69178         var i, l, shadow, shadows, sh, lsh, sprite;
69179         if (!isNaN(this._index)) {
69180             this.__excludes = this.__excludes || [];
69181             this.__excludes[this._index] = true;
69182             sprite = this.slices[this._index].sprite;
69183             for (sh = 0, lsh = sprite.length; sh < lsh; sh++) {
69184                 sprite[sh].setAttributes({
69185                     hidden: true
69186                 }, true);
69187             }
69188             if (this.slices[this._index].shadowAttrs) {
69189                 for (i = 0, shadows = this.slices[this._index].shadowAttrs, l = shadows.length; i < l; i++) {
69190                     shadow = shadows[i];
69191                     for (sh = 0, lsh = shadow.length; sh < lsh; sh++) {
69192                         shadow[sh].setAttributes({
69193                             hidden: true
69194                         }, true);
69195                     }
69196                 }
69197             }
69198             this.drawSeries();
69199         }
69200     },
69201     
69202     // @private shows all elements in the series.
69203     showAll: function() {
69204         if (!isNaN(this._index)) {
69205             this.__excludes[this._index] = false;
69206             this.drawSeries();
69207         }
69208     },
69209
69210     /**
69211      * Highlight the specified item. If no item is provided the whole series will be highlighted.
69212      * @param item {Object} Info about the item; same format as returned by #getItemForPoint
69213      */
69214     highlightItem: function(item) {
69215         var me = this,
69216             rad = me.rad;
69217         item = item || this.items[this._index];
69218         
69219         //TODO(nico): sometimes in IE itemmouseover is triggered
69220         //twice without triggering itemmouseout in between. This
69221         //fixes the highlighting bug. Eventually, events should be
69222         //changed to trigger one itemmouseout between two itemmouseovers.
69223         this.unHighlightItem();
69224         
69225         if (!item || item.sprite && item.sprite._animating) {
69226             return;
69227         }
69228         me.callParent([item]);
69229         if (!me.highlight) {
69230             return;
69231         }
69232         if ('segment' in me.highlightCfg) {
69233             var highlightSegment = me.highlightCfg.segment,
69234                 animate = me.chart.animate,
69235                 attrs, i, shadows, shadow, ln, to, itemHighlightSegment, prop;
69236             //animate labels
69237             if (me.labelsGroup) {
69238                 var group = me.labelsGroup,
69239                     display = me.label.display,
69240                     label = group.getAt(item.index),
69241                     middle = (item.startAngle + item.endAngle) / 2 * rad,
69242                     r = highlightSegment.margin || 0,
69243                     x = r * Math.cos(middle),
69244                     y = r * Math.sin(middle);
69245
69246                 //TODO(nico): rounding to 1e-10
69247                 //gives the right translation. Translation
69248                 //was buggy for very small numbers. In this
69249                 //case we're not looking to translate to very small
69250                 //numbers but not to translate at all.
69251                 if (Math.abs(x) < 1e-10) {
69252                     x = 0;
69253                 }
69254                 if (Math.abs(y) < 1e-10) {
69255                     y = 0;
69256                 }
69257                 
69258                 if (animate) {
69259                     label.stopAnimation();
69260                     label.animate({
69261                         to: {
69262                             translate: {
69263                                 x: x,
69264                                 y: y
69265                             }
69266                         },
69267                         duration: me.highlightDuration
69268                     });
69269                 }
69270                 else {
69271                     label.setAttributes({
69272                         translate: {
69273                             x: x,
69274                             y: y
69275                         }
69276                     }, true);
69277                 }
69278             }
69279             //animate shadows
69280             if (me.chart.shadow && item.shadows) {
69281                 i = 0;
69282                 shadows = item.shadows;
69283                 ln = shadows.length;
69284                 for (; i < ln; i++) {
69285                     shadow = shadows[i];
69286                     to = {};
69287                     itemHighlightSegment = item.sprite._from.segment;
69288                     for (prop in itemHighlightSegment) {
69289                         if (! (prop in highlightSegment)) {
69290                             to[prop] = itemHighlightSegment[prop];
69291                         }
69292                     }
69293                     attrs = {
69294                         segment: Ext.applyIf(to, me.highlightCfg.segment)
69295                     };
69296                     if (animate) {
69297                         shadow.stopAnimation();
69298                         shadow.animate({
69299                             to: attrs,
69300                             duration: me.highlightDuration
69301                         });
69302                     }
69303                     else {
69304                         shadow.setAttributes(attrs, true);
69305                     }
69306                 }
69307             }
69308         }
69309     },
69310
69311     /**
69312      * un-highlights the specified item. If no item is provided it will un-highlight the entire series.
69313      * @param item {Object} Info about the item; same format as returned by #getItemForPoint
69314      */
69315     unHighlightItem: function() {
69316         var me = this;
69317         if (!me.highlight) {
69318             return;
69319         }
69320
69321         if (('segment' in me.highlightCfg) && me.items) {
69322             var items = me.items,
69323                 animate = me.chart.animate,
69324                 shadowsEnabled = !!me.chart.shadow,
69325                 group = me.labelsGroup,
69326                 len = items.length,
69327                 i = 0,
69328                 j = 0,
69329                 display = me.label.display,
69330                 shadowLen, p, to, ihs, hs, sprite, shadows, shadow, item, label, attrs;
69331
69332             for (; i < len; i++) {
69333                 item = items[i];
69334                 if (!item) {
69335                     continue;
69336                 }
69337                 sprite = item.sprite;
69338                 if (sprite && sprite._highlighted) {
69339                     //animate labels
69340                     if (group) {
69341                         label = group.getAt(item.index);
69342                         attrs = Ext.apply({
69343                             translate: {
69344                                 x: 0,
69345                                 y: 0
69346                             }
69347                         },
69348                         display == 'rotate' ? {
69349                             rotate: {
69350                                 x: label.attr.x,
69351                                 y: label.attr.y,
69352                                 degrees: label.attr.rotation.degrees
69353                             }
69354                         }: {});
69355                         if (animate) {
69356                             label.stopAnimation();
69357                             label.animate({
69358                                 to: attrs,
69359                                 duration: me.highlightDuration
69360                             });
69361                         }
69362                         else {
69363                             label.setAttributes(attrs, true);
69364                         }
69365                     }
69366                     if (shadowsEnabled) {
69367                         shadows = item.shadows;
69368                         shadowLen = shadows.length;
69369                         for (; j < shadowLen; j++) {
69370                             to = {};
69371                             ihs = item.sprite._to.segment;
69372                             hs = item.sprite._from.segment;
69373                             Ext.apply(to, hs);
69374                             for (p in ihs) {
69375                                 if (! (p in hs)) {
69376                                     to[p] = ihs[p];
69377                                 }
69378                             }
69379                             shadow = shadows[j];
69380                             if (animate) {
69381                                 shadow.stopAnimation();
69382                                 shadow.animate({
69383                                     to: {
69384                                         segment: to
69385                                     },
69386                                     duration: me.highlightDuration
69387                                 });
69388                             }
69389                             else {
69390                                 shadow.setAttributes({ segment: to }, true);
69391                             }
69392                         }
69393                     }
69394                 }
69395             }
69396         }
69397         me.callParent(arguments);
69398     },
69399     
69400     /**
69401      * Returns the color of the series (to be displayed as color for the series legend item).
69402      * @param item {Object} Info about the item; same format as returned by #getItemForPoint
69403      */
69404     getLegendColor: function(index) {
69405         var me = this;
69406         return me.colorArrayStyle[index % me.colorArrayStyle.length];
69407     }
69408 });
69409
69410
69411 /**
69412  * @class Ext.chart.series.Radar
69413  * @extends Ext.chart.series.Series
69414  * 
69415  * Creates a Radar Chart. A Radar Chart is a useful visualization technique for comparing different quantitative values for 
69416  * a constrained number of categories.
69417  * As with all other series, the Radar series must be appended in the *series* Chart array configuration. See the Chart 
69418  * documentation for more information. A typical configuration object for the radar series could be:
69419  * 
69420  {@img Ext.chart.series.Radar/Ext.chart.series.Radar.png Ext.chart.series.Radar chart series}  
69421   <pre><code>
69422     var store = Ext.create('Ext.data.JsonStore', {
69423         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
69424         data: [
69425             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
69426             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
69427             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
69428             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
69429             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}                                                
69430         ]
69431     });
69432     
69433     Ext.create('Ext.chart.Chart', {
69434         renderTo: Ext.getBody(),
69435         width: 500,
69436         height: 300,
69437         animate: true,
69438         theme:'Category2',
69439         store: store,
69440         axes: [{
69441             type: 'Radial',
69442             position: 'radial',
69443             label: {
69444                 display: true
69445             }
69446         }],
69447         series: [{
69448             type: 'radar',
69449             xField: 'name',
69450             yField: 'data3',
69451             showInLegend: true,
69452             showMarkers: true,
69453             markerConfig: {
69454                 radius: 5,
69455                 size: 5           
69456             },
69457             style: {
69458                 'stroke-width': 2,
69459                 fill: 'none'
69460             }
69461         },{
69462             type: 'radar',
69463             xField: 'name',
69464             yField: 'data2',
69465             showMarkers: true,
69466             showInLegend: true,
69467             markerConfig: {
69468                 radius: 5,
69469                 size: 5
69470             },
69471             style: {
69472                 'stroke-width': 2,
69473                 fill: 'none'
69474             }
69475         },{
69476             type: 'radar',
69477             xField: 'name',
69478             yField: 'data5',
69479             showMarkers: true,
69480             showInLegend: true,
69481             markerConfig: {
69482                 radius: 5,
69483                 size: 5
69484             },
69485             style: {
69486                 'stroke-width': 2,
69487                 fill: 'none'
69488             }
69489         }]    
69490     });
69491    </code></pre>
69492  * 
69493  * In this configuration we add three series to the chart. Each of these series is bound to the same categories field, `name` but bound to different properties for each category,
69494  * `data1`, `data2` and `data3` respectively. All series display markers by having `showMarkers` enabled. The configuration for the markers of each series can be set by adding properties onto 
69495  * the markerConfig object. Finally we override some theme styling properties by adding properties to the `style` object.
69496  * 
69497  * @xtype radar
69498  * 
69499  */
69500 Ext.define('Ext.chart.series.Radar', {
69501
69502     /* Begin Definitions */
69503
69504     extend: 'Ext.chart.series.Series',
69505
69506     requires: ['Ext.chart.Shape', 'Ext.fx.Anim'],
69507
69508     /* End Definitions */
69509
69510     type: "radar",
69511     alias: 'series.radar',
69512
69513     
69514     rad: Math.PI / 180,
69515
69516     showInLegend: false,
69517
69518     /**
69519      * @cfg {Object} style
69520      * An object containing styles for overriding series styles from Theming.
69521      */
69522     style: {},
69523     
69524     constructor: function(config) {
69525         this.callParent(arguments);
69526         var me = this,
69527             surface = me.chart.surface, i, l;
69528         me.group = surface.getGroup(me.seriesId);
69529         if (me.showMarkers) {
69530             me.markerGroup = surface.getGroup(me.seriesId + '-markers');
69531         }
69532     },
69533
69534     /**
69535      * Draws the series for the current chart.
69536      */
69537     drawSeries: function() {
69538         var me = this,
69539             store = me.chart.substore || me.chart.store,
69540             group = me.group,
69541             sprite,
69542             chart = me.chart,
69543             animate = chart.animate,
69544             field = me.field || me.yField,
69545             surface = chart.surface,
69546             chartBBox = chart.chartBBox,
69547             rendererAttributes,
69548             centerX, centerY,
69549             items,
69550             radius,
69551             maxValue = 0,
69552             fields = [],
69553             max = Math.max,
69554             cos = Math.cos,
69555             sin = Math.sin,
69556             pi2 = Math.PI * 2,
69557             l = store.getCount(),
69558             startPath, path, x, y, rho,
69559             i, nfields,
69560             seriesStyle = me.seriesStyle,
69561             seriesLabelStyle = me.seriesLabelStyle,
69562             first = chart.resizing || !me.radar,
69563             axis = chart.axes && chart.axes.get(0),
69564             aggregate = !(axis && axis.maximum);
69565         
69566         me.setBBox();
69567
69568         maxValue = aggregate? 0 : (axis.maximum || 0);
69569         
69570         Ext.apply(seriesStyle, me.style || {});
69571         
69572         //if the store is empty then there's nothing to draw
69573         if (!store || !store.getCount()) {
69574             return;
69575         }
69576         
69577         me.unHighlightItem();
69578         me.cleanHighlights();
69579
69580         centerX = me.centerX = chartBBox.x + (chartBBox.width / 2);
69581         centerY = me.centerY = chartBBox.y + (chartBBox.height / 2);
69582         me.radius = radius = Math.min(chartBBox.width, chartBBox.height) /2;
69583         me.items = items = [];
69584
69585         if (aggregate) {
69586             //get all renderer fields
69587             chart.series.each(function(series) {
69588                 fields.push(series.yField);
69589             });
69590             //get maxValue to interpolate
69591             store.each(function(record, i) {
69592                 for (i = 0, nfields = fields.length; i < nfields; i++) {
69593                     maxValue = max(+record.get(fields[i]), maxValue);
69594                 }
69595             });
69596         }
69597         //ensure non-zero value.
69598         maxValue = maxValue || 1;
69599         //create path and items
69600         startPath = []; path = [];
69601         store.each(function(record, i) {
69602             rho = radius * record.get(field) / maxValue;
69603             x = rho * cos(i / l * pi2);
69604             y = rho * sin(i / l * pi2);
69605             if (i == 0) {
69606                 path.push('M', x + centerX, y + centerY);
69607                 startPath.push('M', 0.01 * x + centerX, 0.01 * y + centerY);
69608             } else {
69609                 path.push('L', x + centerX, y + centerY);
69610                 startPath.push('L', 0.01 * x + centerX, 0.01 * y + centerY);
69611             }
69612             items.push({
69613                 sprite: false, //TODO(nico): add markers
69614                 point: [centerX + x, centerY + y],
69615                 series: me
69616             });
69617         });
69618         path.push('Z');
69619         //create path sprite
69620         if (!me.radar) {
69621             me.radar = surface.add(Ext.apply({
69622                 type: 'path',
69623                 group: group,
69624                 path: startPath
69625             }, seriesStyle || {}));
69626         }
69627         //reset on resizing
69628         if (chart.resizing) {
69629             me.radar.setAttributes({
69630                 path: startPath
69631             }, true);
69632         }
69633         //render/animate
69634         if (chart.animate) {
69635             me.onAnimate(me.radar, {
69636                 to: Ext.apply({
69637                     path: path
69638                 }, seriesStyle || {})
69639             });
69640         } else {
69641             me.radar.setAttributes(Ext.apply({
69642                 path: path
69643             }, seriesStyle || {}), true);
69644         }
69645         //render markers, labels and callouts
69646         if (me.showMarkers) {
69647             me.drawMarkers();
69648         }
69649         me.renderLabels();
69650         me.renderCallouts();
69651     },
69652     
69653     // @private draws the markers for the lines (if any).
69654     drawMarkers: function() {
69655         var me = this,
69656             chart = me.chart,
69657             surface = chart.surface,
69658             markerStyle = Ext.apply({}, me.markerStyle || {}),
69659             endMarkerStyle = Ext.apply(markerStyle, me.markerConfig),
69660             items = me.items, 
69661             type = endMarkerStyle.type,
69662             markerGroup = me.markerGroup,
69663             centerX = me.centerX,
69664             centerY = me.centerY,
69665             item, i, l, marker;
69666         
69667         delete endMarkerStyle.type;
69668         
69669         for (i = 0, l = items.length; i < l; i++) {
69670             item = items[i];
69671             marker = markerGroup.getAt(i);
69672             if (!marker) {
69673                 marker = Ext.chart.Shape[type](surface, Ext.apply({
69674                     group: markerGroup,
69675                     x: 0,
69676                     y: 0,
69677                     translate: {
69678                         x: centerX,
69679                         y: centerY
69680                     }
69681                 }, endMarkerStyle));
69682             }
69683             else {
69684                 marker.show();
69685             }
69686             if (chart.resizing) {
69687                 marker.setAttributes({
69688                     x: 0,
69689                     y: 0,
69690                     translate: {
69691                         x: centerX,
69692                         y: centerY
69693                     }
69694                 }, true);
69695             }
69696             marker._to = {
69697                 translate: {
69698                     x: item.point[0],
69699                     y: item.point[1]
69700                 }
69701             };
69702             //render/animate
69703             if (chart.animate) {
69704                 me.onAnimate(marker, {
69705                     to: marker._to
69706                 });
69707             }
69708             else {
69709                 marker.setAttributes(Ext.apply(marker._to, endMarkerStyle || {}), true);
69710             }
69711         }
69712     },
69713     
69714     isItemInPoint: function(x, y, item) {
69715         var point,
69716             tolerance = 10,
69717             abs = Math.abs;
69718         point = item.point;
69719         return (abs(point[0] - x) <= tolerance &&
69720                 abs(point[1] - y) <= tolerance);
69721     },
69722
69723     // @private callback for when creating a label sprite.
69724     onCreateLabel: function(storeItem, item, i, display) {
69725         var me = this,
69726             group = me.labelsGroup,
69727             config = me.label,
69728             centerX = me.centerX,
69729             centerY = me.centerY,
69730             point = item.point,
69731             endLabelStyle = Ext.apply(me.seriesLabelStyle || {}, config);
69732         
69733         return me.chart.surface.add(Ext.apply({
69734             'type': 'text',
69735             'text-anchor': 'middle',
69736             'group': group,
69737             'x': centerX,
69738             'y': centerY
69739         }, config || {}));
69740     },
69741
69742     // @private callback for when placing a label sprite.
69743     onPlaceLabel: function(label, storeItem, item, i, display, animate) {
69744         var me = this,
69745             chart = me.chart,
69746             resizing = chart.resizing,
69747             config = me.label,
69748             format = config.renderer,
69749             field = config.field,
69750             centerX = me.centerX,
69751             centerY = me.centerY,
69752             opt = {
69753                 x: item.point[0],
69754                 y: item.point[1]
69755             },
69756             x = opt.x - centerX,
69757             y = opt.y - centerY;
69758
69759         label.setAttributes({
69760             text: format(storeItem.get(field)),
69761             hidden: true
69762         },
69763         true);
69764         
69765         if (resizing) {
69766             label.setAttributes({
69767                 x: centerX,
69768                 y: centerY
69769             }, true);
69770         }
69771         
69772         if (animate) {
69773             label.show(true);
69774             me.onAnimate(label, {
69775                 to: opt
69776             });
69777         } else {
69778             label.setAttributes(opt, true);
69779             label.show(true);
69780         }
69781     },
69782
69783     // @private for toggling (show/hide) series. 
69784     toggleAll: function(show) {
69785         var me = this,
69786             i, ln, shadow, shadows;
69787         if (!show) {
69788             Ext.chart.series.Radar.superclass.hideAll.call(me);
69789         }
69790         else {
69791             Ext.chart.series.Radar.superclass.showAll.call(me);
69792         }
69793         if (me.radar) {
69794             me.radar.setAttributes({
69795                 hidden: !show
69796             }, true);
69797             //hide shadows too
69798             if (me.radar.shadows) {
69799                 for (i = 0, shadows = me.radar.shadows, ln = shadows.length; i < ln; i++) {
69800                     shadow = shadows[i];
69801                     shadow.setAttributes({
69802                         hidden: !show
69803                     }, true);
69804                 }
69805             }
69806         }
69807     },
69808     
69809     // @private hide all elements in the series.
69810     hideAll: function() {
69811         this.toggleAll(false);
69812         this.hideMarkers(0);
69813     },
69814     
69815     // @private show all elements in the series.
69816     showAll: function() {
69817         this.toggleAll(true);
69818     },
69819     
69820     // @private hide all markers that belong to `markerGroup`
69821     hideMarkers: function(index) {
69822         var me = this,
69823             count = me.markerGroup && me.markerGroup.getCount() || 0,
69824             i = index || 0;
69825         for (; i < count; i++) {
69826             me.markerGroup.getAt(i).hide(true);
69827         }
69828     }
69829 });
69830
69831
69832 /**
69833  * @class Ext.chart.series.Scatter
69834  * @extends Ext.chart.series.Cartesian
69835  * 
69836  * Creates a Scatter Chart. The scatter plot is useful when trying to display more than two variables in the same visualization. 
69837  * These variables can be mapped into x, y coordinates and also to an element's radius/size, color, etc.
69838  * As with all other series, the Scatter Series must be appended in the *series* Chart array configuration. See the Chart 
69839  * documentation for more information on creating charts. A typical configuration object for the scatter could be:
69840  *
69841 {@img Ext.chart.series.Scatter/Ext.chart.series.Scatter.png Ext.chart.series.Scatter chart series}  
69842   <pre><code>
69843     var store = Ext.create('Ext.data.JsonStore', {
69844         fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
69845         data: [
69846             {'name':'metric one', 'data1':10, 'data2':12, 'data3':14, 'data4':8, 'data5':13},
69847             {'name':'metric two', 'data1':7, 'data2':8, 'data3':16, 'data4':10, 'data5':3},
69848             {'name':'metric three', 'data1':5, 'data2':2, 'data3':14, 'data4':12, 'data5':7},
69849             {'name':'metric four', 'data1':2, 'data2':14, 'data3':6, 'data4':1, 'data5':23},
69850             {'name':'metric five', 'data1':27, 'data2':38, 'data3':36, 'data4':13, 'data5':33}                                                
69851         ]
69852     });
69853     
69854     Ext.create('Ext.chart.Chart', {
69855         renderTo: Ext.getBody(),
69856         width: 500,
69857         height: 300,
69858         animate: true,
69859         theme:'Category2',
69860         store: store,
69861         axes: [{
69862             type: 'Numeric',
69863             position: 'bottom',
69864             fields: ['data1', 'data2', 'data3'],
69865             title: 'Sample Values',
69866             grid: true,
69867             minimum: 0
69868         }, {
69869             type: 'Category',
69870             position: 'left',
69871             fields: ['name'],
69872             title: 'Sample Metrics'
69873         }],
69874         series: [{
69875             type: 'scatter',
69876             markerConfig: {
69877                 radius: 5,
69878                 size: 5
69879             },
69880             axis: 'left',
69881             xField: 'name',
69882             yField: 'data2'
69883         }, {
69884             type: 'scatter',
69885             markerConfig: {
69886                 radius: 5,
69887                 size: 5
69888             },
69889             axis: 'left',
69890             xField: 'name',
69891             yField: 'data3'
69892         }]   
69893     });
69894    </code></pre>
69895  
69896  * 
69897  * In this configuration we add three different categories of scatter series. Each of them is bound to a different field of the same data store, 
69898  * `data1`, `data2` and `data3` respectively. All x-fields for the series must be the same field, in this case `name`. 
69899  * Each scatter series has a different styling configuration for markers, specified by the `markerConfig` object. Finally we set the left axis as 
69900  * axis to show the current values of the elements.
69901  * 
69902  * @xtype scatter
69903  * 
69904  */
69905 Ext.define('Ext.chart.series.Scatter', {
69906
69907     /* Begin Definitions */
69908
69909     extend: 'Ext.chart.series.Cartesian',
69910
69911     requires: ['Ext.chart.axis.Axis', 'Ext.chart.Shape', 'Ext.fx.Anim'],
69912
69913     /* End Definitions */
69914
69915     type: 'scatter',
69916     alias: 'series.scatter',
69917
69918     /**
69919      * @cfg {Object} markerConfig
69920      * The display style for the scatter series markers.
69921      */
69922     
69923     /**
69924      * @cfg {Object} style 
69925      * Append styling properties to this object for it to override theme properties.
69926      */
69927
69928     constructor: function(config) {
69929         this.callParent(arguments);
69930         var me = this,
69931             shadow = me.chart.shadow,
69932             surface = me.chart.surface, i, l;
69933         Ext.apply(me, config, {
69934             style: {},
69935             markerConfig: {},
69936             shadowAttributes: [{
69937                 "stroke-width": 6,
69938                 "stroke-opacity": 0.05,
69939                 stroke: 'rgb(0, 0, 0)'
69940             }, {
69941                 "stroke-width": 4,
69942                 "stroke-opacity": 0.1,
69943                 stroke: 'rgb(0, 0, 0)'
69944             }, {
69945                 "stroke-width": 2,
69946                 "stroke-opacity": 0.15,
69947                 stroke: 'rgb(0, 0, 0)'
69948             }]
69949         });
69950         me.group = surface.getGroup(me.seriesId);
69951         if (shadow) {
69952             for (i = 0, l = me.shadowAttributes.length; i < l; i++) {
69953                 me.shadowGroups.push(surface.getGroup(me.seriesId + '-shadows' + i));
69954             }
69955         }
69956     },
69957
69958     // @private Get chart and data boundaries
69959     getBounds: function() {
69960         var me = this,
69961             chart = me.chart,
69962             store = chart.substore || chart.store,
69963             axes = [].concat(me.axis),
69964             bbox, xScale, yScale, ln, minX, minY, maxX, maxY, i, axis, ends;
69965
69966         me.setBBox();
69967         bbox = me.bbox;
69968
69969         for (i = 0, ln = axes.length; i < ln; i++) { 
69970             axis = chart.axes.get(axes[i]);
69971             if (axis) {
69972                 ends = axis.calcEnds();
69973                 if (axis.position == 'top' || axis.position == 'bottom') {
69974                     minX = ends.from;
69975                     maxX = ends.to;
69976                 }
69977                 else {
69978                     minY = ends.from;
69979                     maxY = ends.to;
69980                 }
69981             }
69982         }
69983         // If a field was specified without a corresponding axis, create one to get bounds
69984         if (me.xField && !Ext.isNumber(minX)) {
69985             axis = Ext.create('Ext.chart.axis.Axis', {
69986                 chart: chart,
69987                 fields: [].concat(me.xField)
69988             }).calcEnds();
69989             minX = axis.from;
69990             maxX = axis.to;
69991         }
69992         if (me.yField && !Ext.isNumber(minY)) {
69993             axis = Ext.create('Ext.chart.axis.Axis', {
69994                 chart: chart,
69995                 fields: [].concat(me.yField)
69996             }).calcEnds();
69997             minY = axis.from;
69998             maxY = axis.to;
69999         }
70000
70001         if (isNaN(minX)) {
70002             minX = 0;
70003             maxX = store.getCount() - 1;
70004             xScale = bbox.width / (store.getCount() - 1);
70005         }
70006         else {
70007             xScale = bbox.width / (maxX - minX);
70008         }
70009
70010         if (isNaN(minY)) {
70011             minY = 0;
70012             maxY = store.getCount() - 1;
70013             yScale = bbox.height / (store.getCount() - 1);
70014         } 
70015         else {
70016             yScale = bbox.height / (maxY - minY);
70017         }
70018
70019         return {
70020             bbox: bbox,
70021             minX: minX,
70022             minY: minY,
70023             xScale: xScale,
70024             yScale: yScale
70025         };
70026     },
70027
70028     // @private Build an array of paths for the chart
70029     getPaths: function() {
70030         var me = this,
70031             chart = me.chart,
70032             enableShadows = chart.shadow,
70033             store = chart.substore || chart.store,
70034             group = me.group,
70035             bounds = me.bounds = me.getBounds(),
70036             bbox = me.bbox,
70037             xScale = bounds.xScale,
70038             yScale = bounds.yScale,
70039             minX = bounds.minX,
70040             minY = bounds.minY,
70041             boxX = bbox.x,
70042             boxY = bbox.y,
70043             boxHeight = bbox.height,
70044             items = me.items = [],
70045             attrs = [],
70046             x, y, xValue, yValue, sprite;
70047
70048         store.each(function(record, i) {
70049             xValue = record.get(me.xField);
70050             yValue = record.get(me.yField);
70051             //skip undefined values
70052             if (typeof yValue == 'undefined' || (typeof yValue == 'string' && !yValue)) {
70053                 if (Ext.isDefined(Ext.global.console)) {
70054                     Ext.global.console.warn("[Ext.chart.series.Scatter]  Skipping a store element with an undefined value at ", record, xValue, yValue);
70055                 }
70056                 return;
70057             }
70058             // Ensure a value
70059             if (typeof xValue == 'string' || typeof xValue == 'object') {
70060                 xValue = i;
70061             }
70062             if (typeof yValue == 'string' || typeof yValue == 'object') {
70063                 yValue = i;
70064             }
70065             x = boxX + (xValue - minX) * xScale;
70066             y = boxY + boxHeight - (yValue - minY) * yScale;
70067             attrs.push({
70068                 x: x,
70069                 y: y
70070             });
70071
70072             me.items.push({
70073                 series: me,
70074                 value: [xValue, yValue],
70075                 point: [x, y],
70076                 storeItem: record
70077             });
70078
70079             // When resizing, reset before animating
70080             if (chart.animate && chart.resizing) {
70081                 sprite = group.getAt(i);
70082                 if (sprite) {
70083                     me.resetPoint(sprite);
70084                     if (enableShadows) {
70085                         me.resetShadow(sprite);
70086                     }
70087                 }
70088             }
70089         });
70090         return attrs;
70091     },
70092
70093     // @private translate point to the center
70094     resetPoint: function(sprite) {
70095         var bbox = this.bbox;
70096         sprite.setAttributes({
70097             translate: {
70098                 x: (bbox.x + bbox.width) / 2,
70099                 y: (bbox.y + bbox.height) / 2
70100             }
70101         }, true);
70102     },
70103
70104     // @private translate shadows of a sprite to the center
70105     resetShadow: function(sprite) {
70106         var me = this,
70107             shadows = sprite.shadows,
70108             shadowAttributes = me.shadowAttributes,
70109             ln = me.shadowGroups.length,
70110             bbox = me.bbox,
70111             i, attr;
70112         for (i = 0; i < ln; i++) {
70113             attr = Ext.apply({}, shadowAttributes[i]);
70114             if (attr.translate) {
70115                 attr.translate.x += (bbox.x + bbox.width) / 2;
70116                 attr.translate.y += (bbox.y + bbox.height) / 2;
70117             }
70118             else {
70119                 attr.translate = {
70120                     x: (bbox.x + bbox.width) / 2,
70121                     y: (bbox.y + bbox.height) / 2
70122                 };
70123             }
70124             shadows[i].setAttributes(attr, true);
70125         }
70126     },
70127
70128     // @private create a new point
70129     createPoint: function(attr, type) {
70130         var me = this,
70131             chart = me.chart,
70132             group = me.group,
70133             bbox = me.bbox;
70134
70135         return Ext.chart.Shape[type](chart.surface, Ext.apply({}, {
70136             x: 0,
70137             y: 0,
70138             group: group,
70139             translate: {
70140                 x: (bbox.x + bbox.width) / 2,
70141                 y: (bbox.y + bbox.height) / 2
70142             }
70143         }, attr));
70144     },
70145
70146     // @private create a new set of shadows for a sprite
70147     createShadow: function(sprite, endMarkerStyle, type) {
70148         var me = this,
70149             chart = me.chart,
70150             shadowGroups = me.shadowGroups,
70151             shadowAttributes = me.shadowAttributes,
70152             lnsh = shadowGroups.length,
70153             bbox = me.bbox,
70154             i, shadow, shadows, attr;
70155
70156         sprite.shadows = shadows = [];
70157
70158         for (i = 0; i < lnsh; i++) {
70159             attr = Ext.apply({}, shadowAttributes[i]);
70160             if (attr.translate) {
70161                 attr.translate.x += (bbox.x + bbox.width) / 2;
70162                 attr.translate.y += (bbox.y + bbox.height) / 2;
70163             }
70164             else {
70165                 Ext.apply(attr, {
70166                     translate: {
70167                         x: (bbox.x + bbox.width) / 2,
70168                         y: (bbox.y + bbox.height) / 2
70169                     }
70170                 });
70171             }
70172             Ext.apply(attr, endMarkerStyle);
70173             shadow = Ext.chart.Shape[type](chart.surface, Ext.apply({}, {
70174                 x: 0,
70175                 y: 0,
70176                 group: shadowGroups[i]
70177             }, attr));
70178             shadows.push(shadow);
70179         }
70180     },
70181
70182     /**
70183      * Draws the series for the current chart.
70184      */
70185     drawSeries: function() {
70186         var me = this,
70187             chart = me.chart,
70188             store = chart.substore || chart.store,
70189             group = me.group,
70190             enableShadows = chart.shadow,
70191             shadowGroups = me.shadowGroups,
70192             shadowAttributes = me.shadowAttributes,
70193             lnsh = shadowGroups.length,
70194             sprite, attrs, attr, ln, i, endMarkerStyle, shindex, type, shadows,
70195             rendererAttributes, shadowAttribute;
70196
70197         endMarkerStyle = Ext.apply(me.markerStyle, me.markerConfig);
70198         type = endMarkerStyle.type;
70199         delete endMarkerStyle.type;
70200
70201         //if the store is empty then there's nothing to be rendered
70202         if (!store || !store.getCount()) {
70203             return;
70204         }
70205
70206         me.unHighlightItem();
70207         me.cleanHighlights();
70208
70209         attrs = me.getPaths();
70210         ln = attrs.length;
70211         for (i = 0; i < ln; i++) {
70212             attr = attrs[i];
70213             sprite = group.getAt(i);
70214             Ext.apply(attr, endMarkerStyle);
70215
70216             // Create a new sprite if needed (no height)
70217             if (!sprite) {
70218                 sprite = me.createPoint(attr, type);
70219                 if (enableShadows) {
70220                     me.createShadow(sprite, endMarkerStyle, type);
70221                 }
70222             }
70223
70224             shadows = sprite.shadows;
70225             if (chart.animate) {
70226                 rendererAttributes = me.renderer(sprite, store.getAt(i), { translate: attr }, i, store);
70227                 sprite._to = rendererAttributes;
70228                 me.onAnimate(sprite, {
70229                     to: rendererAttributes
70230                 });
70231                 //animate shadows
70232                 for (shindex = 0; shindex < lnsh; shindex++) {
70233                     shadowAttribute = Ext.apply({}, shadowAttributes[shindex]);
70234                     rendererAttributes = me.renderer(shadows[shindex], store.getAt(i), Ext.apply({}, { 
70235                         translate: {
70236                             x: attr.x + (shadowAttribute.translate? shadowAttribute.translate.x : 0),
70237                             y: attr.y + (shadowAttribute.translate? shadowAttribute.translate.y : 0)
70238                         } 
70239                     }, shadowAttribute), i, store);
70240                     me.onAnimate(shadows[shindex], { to: rendererAttributes });
70241                 }
70242             }
70243             else {
70244                 rendererAttributes = me.renderer(sprite, store.getAt(i), Ext.apply({ translate: attr }, { hidden: false }), i, store);
70245                 sprite.setAttributes(rendererAttributes, true);
70246                 //update shadows
70247                 for (shindex = 0; shindex < lnsh; shindex++) {
70248                     shadowAttribute = shadowAttributes[shindex];
70249                     rendererAttributes = me.renderer(shadows[shindex], store.getAt(i), Ext.apply({ 
70250                         x: attr.x,
70251                         y: attr.y
70252                     }, shadowAttribute), i, store);
70253                     shadows[shindex].setAttributes(rendererAttributes, true);
70254                 }
70255             }
70256             me.items[i].sprite = sprite;
70257         }
70258
70259         // Hide unused sprites
70260         ln = group.getCount();
70261         for (i = attrs.length; i < ln; i++) {
70262             group.getAt(i).hide(true);
70263         }
70264         me.renderLabels();
70265         me.renderCallouts();
70266     },
70267     
70268     // @private callback for when creating a label sprite.
70269     onCreateLabel: function(storeItem, item, i, display) {
70270         var me = this,
70271             group = me.labelsGroup,
70272             config = me.label,
70273             endLabelStyle = Ext.apply({}, config, me.seriesLabelStyle),
70274             bbox = me.bbox;
70275         
70276         return me.chart.surface.add(Ext.apply({
70277             type: 'text',
70278             group: group,
70279             x: item.point[0],
70280             y: bbox.y + bbox.height / 2
70281         }, endLabelStyle));
70282     },
70283     
70284     // @private callback for when placing a label sprite.
70285     onPlaceLabel: function(label, storeItem, item, i, display, animate) {
70286         var me = this,
70287             chart = me.chart,
70288             resizing = chart.resizing,
70289             config = me.label,
70290             format = config.renderer,
70291             field = config.field,
70292             bbox = me.bbox,
70293             x = item.point[0],
70294             y = item.point[1],
70295             radius = item.sprite.attr.radius,
70296             bb, width, height, anim;
70297         
70298         label.setAttributes({
70299             text: format(storeItem.get(field)),
70300             hidden: true
70301         }, true);
70302         
70303         if (display == 'rotate') {
70304             label.setAttributes({
70305                 'text-anchor': 'start',
70306                 'rotation': {
70307                     x: x,
70308                     y: y,
70309                     degrees: -45
70310                 }
70311             }, true);
70312             //correct label position to fit into the box
70313             bb = label.getBBox();
70314             width = bb.width;
70315             height = bb.height;
70316             x = x < bbox.x? bbox.x : x;
70317             x = (x + width > bbox.x + bbox.width)? (x - (x + width - bbox.x - bbox.width)) : x;
70318             y = (y - height < bbox.y)? bbox.y + height : y;
70319         
70320         } else if (display == 'under' || display == 'over') {
70321             //TODO(nicolas): find out why width/height values in circle bounding boxes are undefined.
70322             bb = item.sprite.getBBox();
70323             bb.width = bb.width || (radius * 2);
70324             bb.height = bb.height || (radius * 2);
70325             y = y + (display == 'over'? -bb.height : bb.height);
70326             //correct label position to fit into the box
70327             bb = label.getBBox();
70328             width = bb.width/2;
70329             height = bb.height/2;
70330             x = x - width < bbox.x ? bbox.x + width : x;
70331             x = (x + width > bbox.x + bbox.width) ? (x - (x + width - bbox.x - bbox.width)) : x;
70332             y = y - height < bbox.y? bbox.y + height : y;
70333             y = (y + height > bbox.y + bbox.height) ? (y - (y + height - bbox.y - bbox.height)) : y;
70334         }
70335
70336         if (!chart.animate) {
70337             label.setAttributes({
70338                 x: x,
70339                 y: y
70340             }, true);
70341             label.show(true);
70342         }
70343         else {
70344             if (resizing) {
70345                 anim = item.sprite.getActiveAnimation();
70346                 if (anim) {
70347                     anim.on('afteranimate', function() {
70348                         label.setAttributes({
70349                             x: x,
70350                             y: y
70351                         }, true);
70352                         label.show(true);
70353                     });   
70354                 }
70355                 else {
70356                     label.show(true);
70357                 }
70358             }
70359             else {
70360                 me.onAnimate(label, {
70361                     to: {
70362                         x: x,
70363                         y: y
70364                     }
70365                 });
70366             }
70367         }
70368     },
70369     
70370     // @private callback for when placing a callout sprite.    
70371     onPlaceCallout: function(callout, storeItem, item, i, display, animate, index) {
70372         var me = this,
70373             chart = me.chart,
70374             surface = chart.surface,
70375             resizing = chart.resizing,
70376             config = me.callouts,
70377             items = me.items,
70378             cur = item.point,
70379             normal,
70380             bbox = callout.label.getBBox(),
70381             offsetFromViz = 30,
70382             offsetToSide = 10,
70383             offsetBox = 3,
70384             boxx, boxy, boxw, boxh,
70385             p, clipRect = me.bbox,
70386             x, y;
70387     
70388         //position
70389         normal = [Math.cos(Math.PI /4), -Math.sin(Math.PI /4)];
70390         x = cur[0] + normal[0] * offsetFromViz;
70391         y = cur[1] + normal[1] * offsetFromViz;
70392         
70393         //box position and dimensions
70394         boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
70395         boxy = y - bbox.height /2 - offsetBox;
70396         boxw = bbox.width + 2 * offsetBox;
70397         boxh = bbox.height + 2 * offsetBox;
70398         
70399         //now check if we're out of bounds and invert the normal vector correspondingly
70400         //this may add new overlaps between labels (but labels won't be out of bounds).
70401         if (boxx < clipRect[0] || (boxx + boxw) > (clipRect[0] + clipRect[2])) {
70402             normal[0] *= -1;
70403         }
70404         if (boxy < clipRect[1] || (boxy + boxh) > (clipRect[1] + clipRect[3])) {
70405             normal[1] *= -1;
70406         }
70407     
70408         //update positions
70409         x = cur[0] + normal[0] * offsetFromViz;
70410         y = cur[1] + normal[1] * offsetFromViz;
70411         
70412         //update box position and dimensions
70413         boxx = x + (normal[0] > 0? 0 : -(bbox.width + 2 * offsetBox));
70414         boxy = y - bbox.height /2 - offsetBox;
70415         boxw = bbox.width + 2 * offsetBox;
70416         boxh = bbox.height + 2 * offsetBox;
70417         
70418         if (chart.animate) {
70419             //set the line from the middle of the pie to the box.
70420             me.onAnimate(callout.lines, {
70421                 to: {
70422                     path: ["M", cur[0], cur[1], "L", x, y, "Z"]
70423                 }
70424             }, true);
70425             //set box position
70426             me.onAnimate(callout.box, {
70427                 to: {
70428                     x: boxx,
70429                     y: boxy,
70430                     width: boxw,
70431                     height: boxh
70432                 }
70433             }, true);
70434             //set text position
70435             me.onAnimate(callout.label, {
70436                 to: {
70437                     x: x + (normal[0] > 0? offsetBox : -(bbox.width + offsetBox)),
70438                     y: y
70439                 }
70440             }, true);
70441         } else {
70442             //set the line from the middle of the pie to the box.
70443             callout.lines.setAttributes({
70444                 path: ["M", cur[0], cur[1], "L", x, y, "Z"]
70445             }, true);
70446             //set box position
70447             callout.box.setAttributes({
70448                 x: boxx,
70449                 y: boxy,
70450                 width: boxw,
70451                 height: boxh
70452             }, true);
70453             //set text position
70454             callout.label.setAttributes({
70455                 x: x + (normal[0] > 0? offsetBox : -(bbox.width + offsetBox)),
70456                 y: y
70457             }, true);
70458         }
70459         for (p in callout) {
70460             callout[p].show(true);
70461         }
70462     },
70463
70464     // @private handles sprite animation for the series.
70465     onAnimate: function(sprite, attr) {
70466         sprite.show();
70467         return this.callParent(arguments);
70468     },
70469
70470     isItemInPoint: function(x, y, item) {
70471         var point,
70472             tolerance = 10,
70473             abs = Math.abs;
70474
70475         function dist(point) {
70476             var dx = abs(point[0] - x),
70477                 dy = abs(point[1] - y);
70478             return Math.sqrt(dx * dx + dy * dy);
70479         }
70480         point = item.point;
70481         return (point[0] - tolerance <= x && point[0] + tolerance >= x &&
70482             point[1] - tolerance <= y && point[1] + tolerance >= y);
70483     }
70484 });
70485
70486
70487 /**
70488  * @class Ext.chart.theme.Base
70489  * Provides default colors for non-specified things. Should be sub-classed when creating new themes.
70490  * @ignore
70491  */
70492 Ext.define('Ext.chart.theme.Base', {
70493
70494     /* Begin Definitions */
70495
70496     requires: ['Ext.chart.theme.Theme'],
70497
70498     /* End Definitions */
70499
70500     constructor: function(config) {
70501         Ext.chart.theme.call(this, config, {
70502             background: false,
70503             axis: {
70504                 stroke: '#444',
70505                 'stroke-width': 1
70506             },
70507             axisLabelTop: {
70508                 fill: '#444',
70509                 font: '12px Arial, Helvetica, sans-serif',
70510                 spacing: 2,
70511                 padding: 5,
70512                 renderer: function(v) { return v; }
70513             },
70514             axisLabelRight: {
70515                 fill: '#444',
70516                 font: '12px Arial, Helvetica, sans-serif',
70517                 spacing: 2,
70518                 padding: 5,
70519                 renderer: function(v) { return v; }
70520             },
70521             axisLabelBottom: {
70522                 fill: '#444',
70523                 font: '12px Arial, Helvetica, sans-serif',
70524                 spacing: 2,
70525                 padding: 5,
70526                 renderer: function(v) { return v; }
70527             },
70528             axisLabelLeft: {
70529                 fill: '#444',
70530                 font: '12px Arial, Helvetica, sans-serif',
70531                 spacing: 2,
70532                 padding: 5,
70533                 renderer: function(v) { return v; }
70534             },
70535             axisTitleTop: {
70536                 font: 'bold 18px Arial',
70537                 fill: '#444'
70538             },
70539             axisTitleRight: {
70540                 font: 'bold 18px Arial',
70541                 fill: '#444',
70542                 rotate: {
70543                     x:0, y:0,
70544                     degrees: 270
70545                 }
70546             },
70547             axisTitleBottom: {
70548                 font: 'bold 18px Arial',
70549                 fill: '#444'
70550             },
70551             axisTitleLeft: {
70552                 font: 'bold 18px Arial',
70553                 fill: '#444',
70554                 rotate: {
70555                     x:0, y:0,
70556                     degrees: 270
70557                 }
70558             },
70559             series: {
70560                 'stroke-width': 0
70561             },
70562             seriesLabel: {
70563                 font: '12px Arial',
70564                 fill: '#333'
70565             },
70566             marker: {
70567                 stroke: '#555',
70568                 fill: '#000',
70569                 radius: 3,
70570                 size: 3
70571             },
70572             colors: [ "#94ae0a", "#115fa6","#a61120", "#ff8809", "#ffd13e", "#a61187", "#24ad9a", "#7c7474", "#a66111"],
70573             seriesThemes: [{
70574                 fill: "#115fa6"
70575             }, {
70576                 fill: "#94ae0a"
70577             }, {
70578                 fill: "#a61120"
70579             }, {
70580                 fill: "#ff8809"
70581             }, {
70582                 fill: "#ffd13e"
70583             }, {
70584                 fill: "#a61187"
70585             }, {
70586                 fill: "#24ad9a"
70587             }, {
70588                 fill: "#7c7474"
70589             }, {
70590                 fill: "#a66111"
70591             }],
70592             markerThemes: [{
70593                 fill: "#115fa6",
70594                 type: 'circle' 
70595             }, {
70596                 fill: "#94ae0a",
70597                 type: 'cross'
70598             }, {
70599                 fill: "#a61120",
70600                 type: 'plus'
70601             }]
70602         });
70603     }
70604 }, function() {
70605     var palette = ['#b1da5a', '#4ce0e7', '#e84b67', '#da5abd', '#4d7fe6', '#fec935'],
70606         names = ['Green', 'Sky', 'Red', 'Purple', 'Blue', 'Yellow'],
70607         i = 0, j = 0, l = palette.length, themes = Ext.chart.theme,
70608         categories = [['#f0a50a', '#c20024', '#2044ba', '#810065', '#7eae29'],
70609                       ['#6d9824', '#87146e', '#2a9196', '#d39006', '#1e40ac'],
70610                       ['#fbbc29', '#ce2e4e', '#7e0062', '#158b90', '#57880e'],
70611                       ['#ef5773', '#fcbd2a', '#4f770d', '#1d3eaa', '#9b001f'],
70612                       ['#7eae29', '#fdbe2a', '#910019', '#27b4bc', '#d74dbc'],
70613                       ['#44dce1', '#0b2592', '#996e05', '#7fb325', '#b821a1']],
70614         cats = categories.length;
70615     
70616     //Create themes from base colors
70617     for (; i < l; i++) {
70618         themes[names[i]] = (function(color) {
70619             return Ext.extend(themes.Base, {
70620                 constructor: function(config) {
70621                     themes.Base.prototype.constructor.call(this, Ext.apply({
70622                         baseColor: color
70623                     }, config));
70624                 }
70625             });
70626         })(palette[i]);
70627     }
70628     
70629     //Create theme from color array
70630     for (i = 0; i < cats; i++) {
70631         themes['Category' + (i + 1)] = (function(category) {
70632             return Ext.extend(themes.Base, {
70633                 constructor: function(config) {
70634                     themes.Base.prototype.constructor.call(this, Ext.apply({
70635                         colors: category
70636                     }, config));
70637                 }
70638             });
70639         })(categories[i]);
70640     }
70641 });
70642
70643 /**
70644  * @author Ed Spencer
70645  * @class Ext.data.ArrayStore
70646  * @extends Ext.data.Store
70647  * @ignore
70648  *
70649  * <p>Small helper class to make creating {@link Ext.data.Store}s from Array data easier.
70650  * An ArrayStore will be automatically configured with a {@link Ext.data.reader.Array}.</p>
70651  *
70652  * <p>A store configuration would be something like:</p>
70653 <pre><code>
70654 var store = new Ext.data.ArrayStore({
70655     // store configs
70656     autoDestroy: true,
70657     storeId: 'myStore',
70658     // reader configs
70659     idIndex: 0,
70660     fields: [
70661        'company',
70662        {name: 'price', type: 'float'},
70663        {name: 'change', type: 'float'},
70664        {name: 'pctChange', type: 'float'},
70665        {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
70666     ]
70667 });
70668 </code></pre>
70669  * <p>This store is configured to consume a returned object of the form:
70670 <pre><code>
70671 var myData = [
70672     ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
70673     ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
70674     ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
70675     ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'],
70676     ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am']
70677 ];
70678 </code></pre>
70679 *
70680  * <p>An object literal of this form could also be used as the {@link #data} config option.</p>
70681  *
70682  * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
70683  * <b>{@link Ext.data.reader.Array ArrayReader}</b>.</p>
70684  *
70685  * @constructor
70686  * @param {Object} config
70687  * @xtype arraystore
70688  */
70689 Ext.define('Ext.data.ArrayStore', {
70690     extend: 'Ext.data.Store',
70691     alias: 'store.array',
70692     uses: ['Ext.data.reader.Array'],
70693
70694     /**
70695      * @cfg {Ext.data.DataReader} reader @hide
70696      */
70697     constructor: function(config) {
70698         config = config || {};
70699
70700         Ext.applyIf(config, {
70701             proxy: {
70702                 type: 'memory',
70703                 reader: 'array'
70704             }
70705         });
70706
70707         this.callParent([config]);
70708     },
70709
70710     loadData: function(data, append) {
70711         if (this.expandData === true) {
70712             var r = [],
70713                 i = 0,
70714                 ln = data.length;
70715
70716             for (; i < ln; i++) {
70717                 r[r.length] = [data[i]];
70718             }
70719
70720             data = r;
70721         }
70722
70723         this.callParent([data, append]);
70724     }
70725 }, function() {
70726     // backwards compat
70727     Ext.data.SimpleStore = Ext.data.ArrayStore;
70728     // Ext.reg('simplestore', Ext.data.SimpleStore);
70729 });
70730
70731 /**
70732  * @author Ed Spencer
70733  * @class Ext.data.Batch
70734  * 
70735  * <p>Provides a mechanism to run one or more {@link Ext.data.Operation operations} in a given order. Fires the 'operationcomplete' event
70736  * after the completion of each Operation, and the 'complete' event when all Operations have been successfully executed. Fires an 'exception'
70737  * event if any of the Operations encounter an exception.</p>
70738  * 
70739  * <p>Usually these are only used internally by {@link Ext.data.proxy.Proxy} classes</p>
70740  * 
70741  * @constructor
70742  * @param {Object} config Optional config object
70743  */
70744 Ext.define('Ext.data.Batch', {
70745     mixins: {
70746         observable: 'Ext.util.Observable'
70747     },
70748     
70749     /**
70750      * True to immediately start processing the batch as soon as it is constructed (defaults to false)
70751      * @property autoStart
70752      * @type Boolean
70753      */
70754     autoStart: false,
70755     
70756     /**
70757      * The index of the current operation being executed
70758      * @property current
70759      * @type Number
70760      */
70761     current: -1,
70762     
70763     /**
70764      * The total number of operations in this batch. Read only
70765      * @property total
70766      * @type Number
70767      */
70768     total: 0,
70769     
70770     /**
70771      * True if the batch is currently running
70772      * @property isRunning
70773      * @type Boolean
70774      */
70775     isRunning: false,
70776     
70777     /**
70778      * True if this batch has been executed completely
70779      * @property isComplete
70780      * @type Boolean
70781      */
70782     isComplete: false,
70783     
70784     /**
70785      * True if this batch has encountered an exception. This is cleared at the start of each operation
70786      * @property hasException
70787      * @type Boolean
70788      */
70789     hasException: false,
70790     
70791     /**
70792      * True to automatically pause the execution of the batch if any operation encounters an exception (defaults to true)
70793      * @property pauseOnException
70794      * @type Boolean
70795      */
70796     pauseOnException: true,
70797     
70798     constructor: function(config) {   
70799         var me = this;
70800                      
70801         me.addEvents(
70802           /**
70803            * @event complete
70804            * Fired when all operations of this batch have been completed
70805            * @param {Ext.data.Batch} batch The batch object
70806            * @param {Object} operation The last operation that was executed
70807            */
70808           'complete',
70809           
70810           /**
70811            * @event exception
70812            * Fired when a operation encountered an exception
70813            * @param {Ext.data.Batch} batch The batch object
70814            * @param {Object} operation The operation that encountered the exception
70815            */
70816           'exception',
70817           
70818           /**
70819            * @event operationcomplete
70820            * Fired when each operation of the batch completes
70821            * @param {Ext.data.Batch} batch The batch object
70822            * @param {Object} operation The operation that just completed
70823            */
70824           'operationcomplete'
70825         );
70826         
70827         me.mixins.observable.constructor.call(me, config);
70828         
70829         /**
70830          * Ordered array of operations that will be executed by this batch
70831          * @property operations
70832          * @type Array
70833          */
70834         me.operations = [];
70835     },
70836     
70837     /**
70838      * Adds a new operation to this batch
70839      * @param {Object} operation The {@link Ext.data.Operation Operation} object
70840      */
70841     add: function(operation) {
70842         this.total++;
70843         
70844         operation.setBatch(this);
70845         
70846         this.operations.push(operation);
70847     },
70848     
70849     /**
70850      * Kicks off the execution of the batch, continuing from the next operation if the previous
70851      * operation encountered an exception, or if execution was paused
70852      */
70853     start: function() {
70854         this.hasException = false;
70855         this.isRunning = true;
70856         
70857         this.runNextOperation();
70858     },
70859     
70860     /**
70861      * @private
70862      * Runs the next operation, relative to this.current.
70863      */
70864     runNextOperation: function() {
70865         this.runOperation(this.current + 1);
70866     },
70867     
70868     /**
70869      * Pauses execution of the batch, but does not cancel the current operation
70870      */
70871     pause: function() {
70872         this.isRunning = false;
70873     },
70874     
70875     /**
70876      * Executes a operation by its numeric index
70877      * @param {Number} index The operation index to run
70878      */
70879     runOperation: function(index) {
70880         var me = this,
70881             operations = me.operations,
70882             operation  = operations[index],
70883             onProxyReturn;
70884         
70885         if (operation === undefined) {
70886             me.isRunning  = false;
70887             me.isComplete = true;
70888             me.fireEvent('complete', me, operations[operations.length - 1]);
70889         } else {
70890             me.current = index;
70891             
70892             onProxyReturn = function(operation) {
70893                 var hasException = operation.hasException();
70894                 
70895                 if (hasException) {
70896                     me.hasException = true;
70897                     me.fireEvent('exception', me, operation);
70898                 } else {
70899                     me.fireEvent('operationcomplete', me, operation);
70900                 }
70901
70902                 if (hasException && me.pauseOnException) {
70903                     me.pause();
70904                 } else {
70905                     operation.setCompleted();
70906                     me.runNextOperation();
70907                 }
70908             };
70909             
70910             operation.setStarted();
70911             
70912             me.proxy[operation.action](operation, onProxyReturn, me);
70913         }
70914     }
70915 });
70916 /**
70917  * @author Ed Spencer
70918  * @class Ext.data.BelongsToAssociation
70919  * @extends Ext.data.Association
70920  *
70921  * <p>Represents a many to one association with another model. The owner model is expected to have
70922  * a foreign key which references the primary key of the associated model:</p>
70923  *
70924 <pre><code>
70925 Ext.define('Category', {
70926     extend: 'Ext.data.Model',
70927     fields: [
70928         {name: 'id',   type: 'int'},
70929         {name: 'name', type: 'string'}
70930     ]
70931 });
70932
70933 Ext.define('Product', {
70934     extend: 'Ext.data.Model',
70935     fields: [
70936         {name: 'id',          type: 'int'},
70937         {name: 'category_id', type: 'int'},
70938         {name: 'name',        type: 'string'}
70939     ],
70940     // we can use the belongsTo shortcut on the model to create a belongsTo association
70941     belongsTo: {type: 'belongsTo', model: 'Category'}
70942 });
70943 </code></pre>
70944  * <p>In the example above we have created models for Products and Categories, and linked them together
70945  * by saying that each Product belongs to a Category. This automatically links each Product to a Category
70946  * based on the Product's category_id, and provides new functions on the Product model:</p>
70947  *
70948  * <p><u>Generated getter function</u></p>
70949  *
70950  * <p>The first function that is added to the owner model is a getter function:</p>
70951  *
70952 <pre><code>
70953 var product = new Product({
70954     id: 100,
70955     category_id: 20,
70956     name: 'Sneakers'
70957 });
70958
70959 product.getCategory(function(category, operation) {
70960     //do something with the category object
70961     alert(category.get('id')); //alerts 20
70962 }, this);
70963 </code></pre>
70964 *
70965  * <p>The getCategory function was created on the Product model when we defined the association. This uses the
70966  * Category's configured {@link Ext.data.proxy.Proxy proxy} to load the Category asynchronously, calling the provided
70967  * callback when it has loaded.</p>
70968  *
70969  * <p>The new getCategory function will also accept an object containing success, failure and callback properties
70970  * - callback will always be called, success will only be called if the associated model was loaded successfully
70971  * and failure will only be called if the associatied model could not be loaded:</p>
70972  *
70973 <pre><code>
70974 product.getCategory({
70975     callback: function(category, operation) {}, //a function that will always be called
70976     success : function(category, operation) {}, //a function that will only be called if the load succeeded
70977     failure : function(category, operation) {}, //a function that will only be called if the load did not succeed
70978     scope   : this //optionally pass in a scope object to execute the callbacks in
70979 });
70980 </code></pre>
70981  *
70982  * <p>In each case above the callbacks are called with two arguments - the associated model instance and the
70983  * {@link Ext.data.Operation operation} object that was executed to load that instance. The Operation object is
70984  * useful when the instance could not be loaded.</p>
70985  *
70986  * <p><u>Generated setter function</u></p>
70987  *
70988  * <p>The second generated function sets the associated model instance - if only a single argument is passed to
70989  * the setter then the following two calls are identical:</p>
70990  *
70991 <pre><code>
70992 //this call
70993 product.setCategory(10);
70994
70995 //is equivalent to this call:
70996 product.set('category_id', 10);
70997 </code></pre>
70998  * <p>If we pass in a second argument, the model will be automatically saved and the second argument passed to
70999  * the owner model's {@link Ext.data.Model#save save} method:</p>
71000 <pre><code>
71001 product.setCategory(10, function(product, operation) {
71002     //the product has been saved
71003     alert(product.get('category_id')); //now alerts 10
71004 });
71005
71006 //alternative syntax:
71007 product.setCategory(10, {
71008     callback: function(product, operation), //a function that will always be called
71009     success : function(product, operation), //a function that will only be called if the load succeeded
71010     failure : function(product, operation), //a function that will only be called if the load did not succeed
71011     scope   : this //optionally pass in a scope object to execute the callbacks in
71012 })
71013 </code></pre>
71014 *
71015  * <p><u>Customisation</u></p>
71016  *
71017  * <p>Associations reflect on the models they are linking to automatically set up properties such as the
71018  * {@link #primaryKey} and {@link #foreignKey}. These can alternatively be specified:</p>
71019  *
71020 <pre><code>
71021 Ext.define('Product', {
71022     fields: [...],
71023
71024     associations: [
71025         {type: 'belongsTo', model: 'Category', primaryKey: 'unique_id', foreignKey: 'cat_id'}
71026     ]
71027 });
71028  </code></pre>
71029  *
71030  * <p>Here we replaced the default primary key (defaults to 'id') and foreign key (calculated as 'category_id')
71031  * with our own settings. Usually this will not be needed.</p>
71032  */
71033 Ext.define('Ext.data.BelongsToAssociation', {
71034     extend: 'Ext.data.Association',
71035
71036     alias: 'association.belongsto',
71037
71038     /**
71039      * @cfg {String} foreignKey The name of the foreign key on the owner model that links it to the associated
71040      * model. Defaults to the lowercased name of the associated model plus "_id", e.g. an association with a
71041      * model called Product would set up a product_id foreign key.
71042      * <pre><code>
71043 Ext.define('Order', {
71044     extend: 'Ext.data.Model',
71045     fields: ['id', 'date'],
71046     hasMany: 'Product'
71047 });
71048
71049 Ext.define('Product', {
71050     extend: 'Ext.data.Model',
71051     fields: ['id', 'name', 'order_id'], // refers to the id of the order that this product belongs to
71052     belongsTo: 'Group'
71053 });
71054 var product = new Product({
71055     id: 1,
71056     name: 'Product 1',
71057     order_id: 22
71058 }, 1);
71059 product.getOrder(); // Will make a call to the server asking for order_id 22
71060
71061      * </code></pre>
71062      */
71063
71064     /**
71065      * @cfg {String} getterName The name of the getter function that will be added to the local model's prototype.
71066      * Defaults to 'get' + the name of the foreign model, e.g. getCategory
71067      */
71068
71069     /**
71070      * @cfg {String} setterName The name of the setter function that will be added to the local model's prototype.
71071      * Defaults to 'set' + the name of the foreign model, e.g. setCategory
71072      */
71073     
71074     /**
71075      * @cfg {String} type The type configuration can be used when creating associations using a configuration object.
71076      * Use 'belongsTo' to create a HasManyAssocation
71077      * <pre><code>
71078 associations: [{
71079     type: 'belongsTo',
71080     model: 'User'
71081 }]
71082      * </code></pre>
71083      */
71084
71085     constructor: function(config) {
71086         this.callParent(arguments);
71087
71088         var me             = this,
71089             ownerProto     = me.ownerModel.prototype,
71090             associatedName = me.associatedName,
71091             getterName     = me.getterName || 'get' + associatedName,
71092             setterName     = me.setterName || 'set' + associatedName;
71093
71094         Ext.applyIf(me, {
71095             name        : associatedName,
71096             foreignKey  : associatedName.toLowerCase() + "_id",
71097             instanceName: associatedName + 'BelongsToInstance',
71098             associationKey: associatedName.toLowerCase()
71099         });
71100
71101         ownerProto[getterName] = me.createGetter();
71102         ownerProto[setterName] = me.createSetter();
71103     },
71104
71105     /**
71106      * @private
71107      * Returns a setter function to be placed on the owner model's prototype
71108      * @return {Function} The setter function
71109      */
71110     createSetter: function() {
71111         var me              = this,
71112             ownerModel      = me.ownerModel,
71113             associatedModel = me.associatedModel,
71114             foreignKey      = me.foreignKey,
71115             primaryKey      = me.primaryKey;
71116
71117         //'this' refers to the Model instance inside this function
71118         return function(value, options, scope) {
71119             this.set(foreignKey, value);
71120
71121             if (typeof options == 'function') {
71122                 options = {
71123                     callback: options,
71124                     scope: scope || this
71125                 };
71126             }
71127
71128             if (Ext.isObject(options)) {
71129                 return this.save(options);
71130             }
71131         };
71132     },
71133
71134     /**
71135      * @private
71136      * Returns a getter function to be placed on the owner model's prototype. We cache the loaded instance
71137      * the first time it is loaded so that subsequent calls to the getter always receive the same reference.
71138      * @return {Function} The getter function
71139      */
71140     createGetter: function() {
71141         var me              = this,
71142             ownerModel      = me.ownerModel,
71143             associatedName  = me.associatedName,
71144             associatedModel = me.associatedModel,
71145             foreignKey      = me.foreignKey,
71146             primaryKey      = me.primaryKey,
71147             instanceName    = me.instanceName;
71148
71149         //'this' refers to the Model instance inside this function
71150         return function(options, scope) {
71151             options = options || {};
71152
71153             var foreignKeyId = this.get(foreignKey),
71154                 instance, callbackFn;
71155
71156             if (this[instanceName] === undefined) {
71157                 instance = Ext.ModelManager.create({}, associatedName);
71158                 instance.set(primaryKey, foreignKeyId);
71159
71160                 if (typeof options == 'function') {
71161                     options = {
71162                         callback: options,
71163                         scope: scope || this
71164                     };
71165                 }
71166
71167                 associatedModel.load(foreignKeyId, options);
71168             } else {
71169                 instance = this[instanceName];
71170
71171                 //TODO: We're duplicating the callback invokation code that the instance.load() call above
71172                 //makes here - ought to be able to normalize this - perhaps by caching at the Model.load layer
71173                 //instead of the association layer.
71174                 if (typeof options == 'function') {
71175                     options.call(scope || this, instance);
71176                 }
71177
71178                 if (options.success) {
71179                     options.success.call(scope || this, instance);
71180                 }
71181
71182                 if (options.callback) {
71183                     options.callback.call(scope || this, instance);
71184                 }
71185
71186                 return instance;
71187             }
71188         };
71189     },
71190
71191     /**
71192      * Read associated data
71193      * @private
71194      * @param {Ext.data.Model} record The record we're writing to
71195      * @param {Ext.data.reader.Reader} reader The reader for the associated model
71196      * @param {Object} associationData The raw associated data
71197      */
71198     read: function(record, reader, associationData){
71199         record[this.instanceName] = reader.read([associationData]).records[0];
71200     }
71201 });
71202
71203 /**
71204  * @class Ext.data.BufferStore
71205  * @extends Ext.data.Store
71206  * @ignore
71207  */
71208 Ext.define('Ext.data.BufferStore', {
71209     extend: 'Ext.data.Store',
71210     alias: 'store.buffer',
71211     sortOnLoad: false,
71212     filterOnLoad: false,
71213     
71214     constructor: function() {
71215         Ext.Error.raise('The BufferStore class has been deprecated. Instead, specify the buffered config option on Ext.data.Store');
71216     }
71217 });
71218 /**
71219  * @class Ext.direct.Manager
71220  * <p><b><u>Overview</u></b></p>
71221  *
71222  * <p>Ext.Direct aims to streamline communication between the client and server
71223  * by providing a single interface that reduces the amount of common code
71224  * typically required to validate data and handle returned data packets
71225  * (reading data, error conditions, etc).</p>
71226  *
71227  * <p>The Ext.direct namespace includes several classes for a closer integration
71228  * with the server-side. The Ext.data namespace also includes classes for working
71229  * with Ext.data.Stores which are backed by data from an Ext.Direct method.</p>
71230  *
71231  * <p><b><u>Specification</u></b></p>
71232  *
71233  * <p>For additional information consult the
71234  * <a href="http://sencha.com/products/extjs/extdirect">Ext.Direct Specification</a>.</p>
71235  *
71236  * <p><b><u>Providers</u></b></p>
71237  *
71238  * <p>Ext.Direct uses a provider architecture, where one or more providers are
71239  * used to transport data to and from the server. There are several providers
71240  * that exist in the core at the moment:</p><div class="mdetail-params"><ul>
71241  *
71242  * <li>{@link Ext.direct.JsonProvider JsonProvider} for simple JSON operations</li>
71243  * <li>{@link Ext.direct.PollingProvider PollingProvider} for repeated requests</li>
71244  * <li>{@link Ext.direct.RemotingProvider RemotingProvider} exposes server side
71245  * on the client.</li>
71246  * </ul></div>
71247  *
71248  * <p>A provider does not need to be invoked directly, providers are added via
71249  * {@link Ext.direct.Manager}.{@link Ext.direct.Manager#add add}.</p>
71250  *
71251  * <p><b><u>Router</u></b></p>
71252  *
71253  * <p>Ext.Direct utilizes a "router" on the server to direct requests from the client
71254  * to the appropriate server-side method. Because the Ext.Direct API is completely
71255  * platform-agnostic, you could completely swap out a Java based server solution
71256  * and replace it with one that uses C# without changing the client side JavaScript
71257  * at all.</p>
71258  *
71259  * <p><b><u>Server side events</u></b></p>
71260  *
71261  * <p>Custom events from the server may be handled by the client by adding
71262  * listeners, for example:</p>
71263  * <pre><code>
71264 {"type":"event","name":"message","data":"Successfully polled at: 11:19:30 am"}
71265
71266 // add a handler for a 'message' event sent by the server
71267 Ext.direct.Manager.on('message', function(e){
71268     out.append(String.format('&lt;p>&lt;i>{0}&lt;/i>&lt;/p>', e.data));
71269             out.el.scrollTo('t', 100000, true);
71270 });
71271  * </code></pre>
71272  * @singleton
71273  */
71274
71275 Ext.define('Ext.direct.Manager', {
71276     
71277     /* Begin Definitions */
71278     singleton: true,
71279    
71280     mixins: {
71281         observable: 'Ext.util.Observable'
71282     },
71283     
71284     requires: ['Ext.util.MixedCollection'],
71285     
71286     statics: {
71287         exceptions: {
71288             TRANSPORT: 'xhr',
71289             PARSE: 'parse',
71290             LOGIN: 'login',
71291             SERVER: 'exception'
71292         }
71293     },
71294     
71295     /* End Definitions */
71296    
71297     constructor: function(){
71298         var me = this;
71299        
71300         me.addEvents(
71301             /**
71302              * @event event
71303              * Fires after an event.
71304              * @param {event} e The Ext.direct.Event type that occurred.
71305              * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
71306              */
71307             'event',
71308             /**
71309              * @event exception
71310              * Fires after an event exception.
71311              * @param {event} e The Ext.direct.Event type that occurred.
71312              */
71313             'exception'
71314         );
71315         me.transactions = Ext.create('Ext.util.MixedCollection');
71316         me.providers = Ext.create('Ext.util.MixedCollection');
71317         
71318         me.mixins.observable.constructor.call(me);
71319     },
71320     
71321     /**
71322      * Adds an Ext.Direct Provider and creates the proxy or stub methods to execute server-side methods.
71323      * If the provider is not already connected, it will auto-connect.
71324      * <pre><code>
71325 var pollProv = new Ext.direct.PollingProvider({
71326     url: 'php/poll2.php'
71327 });
71328
71329 Ext.direct.Manager.addProvider({
71330     "type":"remoting",       // create a {@link Ext.direct.RemotingProvider}
71331     "url":"php\/router.php", // url to connect to the Ext.Direct server-side router.
71332     "actions":{              // each property within the actions object represents a Class
71333         "TestAction":[       // array of methods within each server side Class
71334         {
71335             "name":"doEcho", // name of method
71336             "len":1
71337         },{
71338             "name":"multiply",
71339             "len":1
71340         },{
71341             "name":"doForm",
71342             "formHandler":true, // handle form on server with Ext.Direct.Transaction
71343             "len":1
71344         }]
71345     },
71346     "namespace":"myApplication",// namespace to create the Remoting Provider in
71347 },{
71348     type: 'polling', // create a {@link Ext.direct.PollingProvider}
71349     url:  'php/poll.php'
71350 }, pollProv); // reference to previously created instance
71351      * </code></pre>
71352      * @param {Object/Array} provider Accepts either an Array of Provider descriptions (an instance
71353      * or config object for a Provider) or any number of Provider descriptions as arguments.  Each
71354      * Provider description instructs Ext.Direct how to create client-side stub methods.
71355      */
71356     addProvider : function(provider){
71357         var me = this,
71358             args = arguments,
71359             i = 0,
71360             len;
71361             
71362         if (args.length > 1) {
71363             for (len = args.length; i < len; ++i) {
71364                 me.addProvider(args[i]);
71365             }
71366             return;
71367         }
71368
71369         // if provider has not already been instantiated
71370         if (!provider.isProvider) {
71371             provider = Ext.create('direct.' + provider.type + 'provider', provider);
71372         }
71373         me.providers.add(provider);
71374         provider.on('data', me.onProviderData, me);
71375
71376
71377         if (!provider.isConnected()) {
71378             provider.connect();
71379         }
71380
71381         return provider;
71382     },
71383     
71384     /**
71385      * Retrieve a {@link Ext.direct.Provider provider} by the
71386      * <b><tt>{@link Ext.direct.Provider#id id}</tt></b> specified when the provider is
71387      * {@link #addProvider added}.
71388      * @param {String/Ext.data.Provider} id The id of the provider, or the provider instance.
71389      */
71390     getProvider : function(id){
71391         return id.isProvider ? id : this.providers.get(id);
71392     },
71393     
71394     /**
71395      * Removes the provider.
71396      * @param {String/Ext.direct.Provider} provider The provider instance or the id of the provider.
71397      * @return {Ext.direct.Provider} The provider, null if not found.
71398      */
71399     removeProvider : function(provider){
71400         var me = this,
71401             providers = me.providers,
71402             provider = provider.isProvider ? provider : providers.get(provider);
71403             
71404         if (provider) {
71405             provider.un('data', me.onProviderData, me);
71406             providers.remove(provider);
71407             return provider;
71408         }
71409         return null;
71410     },
71411     
71412     /**
71413      * Add a transaction to the manager.
71414      * @private
71415      * @param {Ext.direct.Transaction} transaction The transaction to add
71416      * @return {Ext.direct.Transaction} transaction
71417      */
71418     addTransaction: function(transaction){
71419         this.transactions.add(transaction);
71420         return transaction;
71421     },
71422
71423     /**
71424      * Remove a transaction from the manager.
71425      * @private
71426      * @param {String/Ext.direct.Transaction} transaction The transaction/id of transaction to remove
71427      * @return {Ext.direct.Transaction} transaction
71428      */
71429     removeTransaction: function(transaction){
71430         transaction = this.getTransaction(transaction);
71431         this.transactions.remove(transaction);
71432         return transaction;
71433     },
71434
71435     /**
71436      * Gets a transaction
71437      * @private
71438      * @param {String/Ext.direct.Transaction} transaction The transaction/id of transaction to get
71439      * @return {Ext.direct.Transaction}
71440      */
71441     getTransaction: function(transaction){
71442         return transaction.isTransaction ? transaction : this.transactions.get(transaction);
71443     },
71444     
71445     onProviderData : function(provider, event){
71446         var me = this,
71447             i = 0,
71448             len;
71449             
71450         if (Ext.isArray(event)) {
71451             for (len = event.length; i < len; ++i) {
71452                 me.onProviderData(provider, event[i]);
71453             }
71454             return;
71455         }
71456         if (event.name && event.name != 'event' && event.name != 'exception') {
71457             me.fireEvent(event.name, event);
71458         } else if (event.type == 'exception') {
71459             me.fireEvent('exception', event);
71460         }
71461         me.fireEvent('event', event, provider);
71462     }
71463 }, function(){
71464     // Backwards compatibility
71465     Ext.Direct = Ext.direct.Manager;
71466 });
71467
71468 /**
71469  * @class Ext.data.proxy.Direct
71470  * @extends Ext.data.proxy.Server
71471  * 
71472  * This class is used to send requests to the server using {@link Ext.direct}. When a request is made,
71473  * the transport mechanism is handed off to the appropriate {@link Ext.direct.RemotingProvider Provider}
71474  * to complete the call.
71475  * 
71476  * ## Specifying the function
71477  * This proxy expects a Direct remoting method to be passed in order to be able to complete requests.
71478  * This can be done by specifying the {@link #directFn} configuration. This will use the same direct
71479  * method for all requests. Alternatively, you can provide an {@link #api} configuration. This
71480  * allows you to specify a different remoting method for each CRUD action.
71481  * 
71482  * ## Paramaters
71483  * This proxy provides options to help configure which parameters will be sent to the server.
71484  * By specifying the {@link #paramsAsHash} option, it will send an object literal containing each
71485  * of the passed parameters. The {@link #paramOrder} option can be used to specify the order in which
71486  * the remoting method parameters are passed.
71487  * 
71488  * ## Example Usage
71489  * 
71490  *     Ext.define('User', {
71491  *         extend: 'Ext.data.Model',
71492  *         fields: ['firstName', 'lastName'],
71493  *         proxy: {
71494  *             type: 'direct',
71495  *             directFn: MyApp.getUsers,
71496  *             paramOrder: 'id' // Tells the proxy to pass the id as the first parameter to the remoting method.
71497  *         }
71498  *     });
71499  *     User.load(1);
71500  */
71501 Ext.define('Ext.data.proxy.Direct', {
71502     /* Begin Definitions */
71503     
71504     extend: 'Ext.data.proxy.Server',
71505     alternateClassName: 'Ext.data.DirectProxy',
71506     
71507     alias: 'proxy.direct',
71508     
71509     requires: ['Ext.direct.Manager'],
71510     
71511     /* End Definitions */
71512    
71513    /**
71514      * @cfg {Array/String} paramOrder Defaults to <tt>undefined</tt>. A list of params to be executed
71515      * server side.  Specify the params in the order in which they must be executed on the server-side
71516      * as either (1) an Array of String values, or (2) a String of params delimited by either whitespace,
71517      * comma, or pipe. For example,
71518      * any of the following would be acceptable:<pre><code>
71519 paramOrder: ['param1','param2','param3']
71520 paramOrder: 'param1 param2 param3'
71521 paramOrder: 'param1,param2,param3'
71522 paramOrder: 'param1|param2|param'
71523      </code></pre>
71524      */
71525     paramOrder: undefined,
71526
71527     /**
71528      * @cfg {Boolean} paramsAsHash
71529      * Send parameters as a collection of named arguments (defaults to <tt>true</tt>). Providing a
71530      * <tt>{@link #paramOrder}</tt> nullifies this configuration.
71531      */
71532     paramsAsHash: true,
71533
71534     /**
71535      * @cfg {Function} directFn
71536      * Function to call when executing a request.  directFn is a simple alternative to defining the api configuration-parameter
71537      * for Store's which will not implement a full CRUD api.
71538      */
71539     directFn : undefined,
71540     
71541     /**
71542      * @cfg {Object} api The same as {@link Ext.data.proxy.Server#api}, however instead of providing urls, you should provide a direct
71543      * function call.
71544      */
71545     
71546     /**
71547      * @cfg {Object} extraParams Extra parameters that will be included on every read request. Individual requests with params
71548      * of the same name will override these params when they are in conflict.
71549      */
71550     
71551     // private
71552     paramOrderRe: /[\s,|]/,
71553     
71554     constructor: function(config){
71555         var me = this;
71556         
71557         Ext.apply(me, config);
71558         if (Ext.isString(me.paramOrder)) {
71559             me.paramOrder = me.paramOrder.split(me.paramOrderRe);
71560         }
71561         me.callParent(arguments);
71562     },
71563     
71564     doRequest: function(operation, callback, scope) {
71565         var me = this,
71566             writer = me.getWriter(),
71567             request = me.buildRequest(operation, callback, scope),
71568             fn = me.api[request.action]  || me.directFn,
71569             args = [],
71570             params = request.params,
71571             paramOrder = me.paramOrder,
71572             method,
71573             i = 0,
71574             len;
71575             
71576         if (!fn) {
71577             Ext.Error.raise('No direct function specified for this proxy');
71578         }
71579             
71580         if (operation.allowWrite()) {
71581             request = writer.write(request);
71582         }
71583         
71584         if (operation.action == 'read') {
71585             // We need to pass params
71586             method = fn.directCfg.method;
71587             
71588             if (method.ordered) {
71589                 if (method.len > 0) {
71590                     if (paramOrder) {
71591                         for (len = paramOrder.length; i < len; ++i) {
71592                             args.push(params[paramOrder[i]]);
71593                         }
71594                     } else if (me.paramsAsHash) {
71595                         args.push(params);
71596                     }
71597                 }
71598             } else {
71599                 args.push(params);
71600             }
71601         } else {
71602             args.push(request.jsonData);
71603         }
71604         
71605         Ext.apply(request, {
71606             args: args,
71607             directFn: fn
71608         });
71609         args.push(me.createRequestCallback(request, operation, callback, scope), me);
71610         fn.apply(window, args);
71611     },
71612     
71613     /*
71614      * Inherit docs. We don't apply any encoding here because
71615      * all of the direct requests go out as jsonData
71616      */
71617     applyEncoding: function(value){
71618         return value;
71619     },
71620     
71621     createRequestCallback: function(request, operation, callback, scope){
71622         var me = this;
71623         
71624         return function(data, event){
71625             me.processResponse(event.status, operation, request, event, callback, scope);
71626         };
71627     },
71628     
71629     // inherit docs
71630     extractResponseData: function(response){
71631         return Ext.isDefined(response.result) ? response.result : response.data;
71632     },
71633     
71634     // inherit docs
71635     setException: function(operation, response) {
71636         operation.setException(response.message);
71637     },
71638     
71639     // inherit docs
71640     buildUrl: function(){
71641         return '';
71642     }
71643 });
71644
71645 /**
71646  * @class Ext.data.DirectStore
71647  * @extends Ext.data.Store
71648  * <p>Small helper class to create an {@link Ext.data.Store} configured with an
71649  * {@link Ext.data.proxy.Direct} and {@link Ext.data.reader.Json} to make interacting
71650  * with an {@link Ext.Direct} Server-side {@link Ext.direct.Provider Provider} easier.
71651  * To create a different proxy/reader combination create a basic {@link Ext.data.Store}
71652  * configured as needed.</p>
71653  *
71654  * <p><b>*Note:</b> Although they are not listed, this class inherits all of the config options of:</p>
71655  * <div><ul class="mdetail-params">
71656  * <li><b>{@link Ext.data.Store Store}</b></li>
71657  * <div class="sub-desc"><ul class="mdetail-params">
71658  *
71659  * </ul></div>
71660  * <li><b>{@link Ext.data.reader.Json JsonReader}</b></li>
71661  * <div class="sub-desc"><ul class="mdetail-params">
71662  * <li><tt><b>{@link Ext.data.reader.Json#root root}</b></tt></li>
71663  * <li><tt><b>{@link Ext.data.reader.Json#idProperty idProperty}</b></tt></li>
71664  * <li><tt><b>{@link Ext.data.reader.Json#totalProperty totalProperty}</b></tt></li>
71665  * </ul></div>
71666  *
71667  * <li><b>{@link Ext.data.proxy.Direct DirectProxy}</b></li>
71668  * <div class="sub-desc"><ul class="mdetail-params">
71669  * <li><tt><b>{@link Ext.data.proxy.Direct#directFn directFn}</b></tt></li>
71670  * <li><tt><b>{@link Ext.data.proxy.Direct#paramOrder paramOrder}</b></tt></li>
71671  * <li><tt><b>{@link Ext.data.proxy.Direct#paramsAsHash paramsAsHash}</b></tt></li>
71672  * </ul></div>
71673  * </ul></div>
71674  *
71675  * @constructor
71676  * @param {Object} config
71677  */
71678
71679 Ext.define('Ext.data.DirectStore', {
71680     /* Begin Definitions */
71681     
71682     extend: 'Ext.data.Store',
71683     
71684     alias: 'store.direct',
71685     
71686     requires: ['Ext.data.proxy.Direct'],
71687    
71688     /* End Definitions */
71689    
71690    constructor : function(config){
71691         config = Ext.apply({}, config);
71692         if (!config.proxy) {
71693             var proxy = {
71694                 type: 'direct',
71695                 reader: {
71696                     type: 'json'
71697                 }
71698             };
71699             Ext.copyTo(proxy, config, 'paramOrder,paramsAsHash,directFn,api,simpleSortMode');
71700             Ext.copyTo(proxy.reader, config, 'totalProperty,root,idProperty');
71701             config.proxy = proxy;
71702         }
71703         this.callParent([config]);
71704     }    
71705 });
71706
71707 /**
71708  * @class Ext.util.Inflector
71709  * @extends Object
71710  * <p>General purpose inflector class that {@link #pluralize pluralizes}, {@link #singularize singularizes} and 
71711  * {@link #ordinalize ordinalizes} words. Sample usage:</p>
71712  * 
71713 <pre><code>
71714 //turning singular words into plurals
71715 Ext.util.Inflector.pluralize('word'); //'words'
71716 Ext.util.Inflector.pluralize('person'); //'people'
71717 Ext.util.Inflector.pluralize('sheep'); //'sheep'
71718
71719 //turning plurals into singulars
71720 Ext.util.Inflector.singularize('words'); //'word'
71721 Ext.util.Inflector.singularize('people'); //'person'
71722 Ext.util.Inflector.singularize('sheep'); //'sheep'
71723
71724 //ordinalizing numbers
71725 Ext.util.Inflector.ordinalize(11); //"11th"
71726 Ext.util.Inflector.ordinalize(21); //"21th"
71727 Ext.util.Inflector.ordinalize(1043); //"1043rd"
71728 </code></pre>
71729  * 
71730  * <p><u>Customization</u></p>
71731  * 
71732  * <p>The Inflector comes with a default set of US English pluralization rules. These can be augmented with additional
71733  * rules if the default rules do not meet your application's requirements, or swapped out entirely for other languages.
71734  * Here is how we might add a rule that pluralizes "ox" to "oxen":</p>
71735  * 
71736 <pre><code>
71737 Ext.util.Inflector.plural(/^(ox)$/i, "$1en");
71738 </code></pre>
71739  * 
71740  * <p>Each rule consists of two items - a regular expression that matches one or more rules, and a replacement string.
71741  * In this case, the regular expression will only match the string "ox", and will replace that match with "oxen". 
71742  * Here's how we could add the inverse rule:</p>
71743  * 
71744 <pre><code>
71745 Ext.util.Inflector.singular(/^(ox)en$/i, "$1");
71746 </code></pre>
71747  * 
71748  * <p>Note that the ox/oxen rules are present by default.</p>
71749  * 
71750  * @singleton
71751  */
71752
71753 Ext.define('Ext.util.Inflector', {
71754
71755     /* Begin Definitions */
71756
71757     singleton: true,
71758
71759     /* End Definitions */
71760
71761     /**
71762      * @private
71763      * The registered plural tuples. Each item in the array should contain two items - the first must be a regular
71764      * expression that matchers the singular form of a word, the second must be a String that replaces the matched
71765      * part of the regular expression. This is managed by the {@link #plural} method.
71766      * @property plurals
71767      * @type Array
71768      */
71769     plurals: [
71770         [(/(quiz)$/i),                "$1zes"  ],
71771         [(/^(ox)$/i),                 "$1en"   ],
71772         [(/([m|l])ouse$/i),           "$1ice"  ],
71773         [(/(matr|vert|ind)ix|ex$/i),  "$1ices" ],
71774         [(/(x|ch|ss|sh)$/i),          "$1es"   ],
71775         [(/([^aeiouy]|qu)y$/i),       "$1ies"  ],
71776         [(/(hive)$/i),                "$1s"    ],
71777         [(/(?:([^f])fe|([lr])f)$/i),  "$1$2ves"],
71778         [(/sis$/i),                   "ses"    ],
71779         [(/([ti])um$/i),              "$1a"    ],
71780         [(/(buffal|tomat|potat)o$/i), "$1oes"  ],
71781         [(/(bu)s$/i),                 "$1ses"  ],
71782         [(/(alias|status|sex)$/i),    "$1es"   ],
71783         [(/(octop|vir)us$/i),         "$1i"    ],
71784         [(/(ax|test)is$/i),           "$1es"   ],
71785         [(/^person$/),                "people" ],
71786         [(/^man$/),                   "men"    ],
71787         [(/^(child)$/),               "$1ren"  ],
71788         [(/s$/i),                     "s"      ],
71789         [(/$/),                       "s"      ]
71790     ],
71791     
71792     /**
71793      * @private
71794      * The set of registered singular matchers. Each item in the array should contain two items - the first must be a 
71795      * regular expression that matches the plural form of a word, the second must be a String that replaces the 
71796      * matched part of the regular expression. This is managed by the {@link #singular} method.
71797      * @property singulars
71798      * @type Array
71799      */
71800     singulars: [
71801       [(/(quiz)zes$/i),                                                    "$1"     ],
71802       [(/(matr)ices$/i),                                                   "$1ix"   ],
71803       [(/(vert|ind)ices$/i),                                               "$1ex"   ],
71804       [(/^(ox)en/i),                                                       "$1"     ],
71805       [(/(alias|status)es$/i),                                             "$1"     ],
71806       [(/(octop|vir)i$/i),                                                 "$1us"   ],
71807       [(/(cris|ax|test)es$/i),                                             "$1is"   ],
71808       [(/(shoe)s$/i),                                                      "$1"     ],
71809       [(/(o)es$/i),                                                        "$1"     ],
71810       [(/(bus)es$/i),                                                      "$1"     ],
71811       [(/([m|l])ice$/i),                                                   "$1ouse" ],
71812       [(/(x|ch|ss|sh)es$/i),                                               "$1"     ],
71813       [(/(m)ovies$/i),                                                     "$1ovie" ],
71814       [(/(s)eries$/i),                                                     "$1eries"],
71815       [(/([^aeiouy]|qu)ies$/i),                                            "$1y"    ],
71816       [(/([lr])ves$/i),                                                    "$1f"    ],
71817       [(/(tive)s$/i),                                                      "$1"     ],
71818       [(/(hive)s$/i),                                                      "$1"     ],
71819       [(/([^f])ves$/i),                                                    "$1fe"   ],
71820       [(/(^analy)ses$/i),                                                  "$1sis"  ],
71821       [(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i), "$1$2sis"],
71822       [(/([ti])a$/i),                                                      "$1um"   ],
71823       [(/(n)ews$/i),                                                       "$1ews"  ],
71824       [(/people$/i),                                                       "person" ],
71825       [(/s$/i),                                                            ""       ]
71826     ],
71827     
71828     /**
71829      * @private
71830      * The registered uncountable words
71831      * @property uncountable
71832      * @type Array
71833      */
71834      uncountable: [
71835         "sheep",
71836         "fish",
71837         "series",
71838         "species",
71839         "money",
71840         "rice",
71841         "information",
71842         "equipment",
71843         "grass",
71844         "mud",
71845         "offspring",
71846         "deer",
71847         "means"
71848     ],
71849     
71850     /**
71851      * Adds a new singularization rule to the Inflector. See the intro docs for more information
71852      * @param {RegExp} matcher The matcher regex
71853      * @param {String} replacer The replacement string, which can reference matches from the matcher argument
71854      */
71855     singular: function(matcher, replacer) {
71856         this.singulars.unshift([matcher, replacer]);
71857     },
71858     
71859     /**
71860      * Adds a new pluralization rule to the Inflector. See the intro docs for more information
71861      * @param {RegExp} matcher The matcher regex
71862      * @param {String} replacer The replacement string, which can reference matches from the matcher argument
71863      */
71864     plural: function(matcher, replacer) {
71865         this.plurals.unshift([matcher, replacer]);
71866     },
71867     
71868     /**
71869      * Removes all registered singularization rules
71870      */
71871     clearSingulars: function() {
71872         this.singulars = [];
71873     },
71874     
71875     /**
71876      * Removes all registered pluralization rules
71877      */
71878     clearPlurals: function() {
71879         this.plurals = [];
71880     },
71881     
71882     /**
71883      * Returns true if the given word is transnumeral (the word is its own singular and plural form - e.g. sheep, fish)
71884      * @param {String} word The word to test
71885      * @return {Boolean} True if the word is transnumeral
71886      */
71887     isTransnumeral: function(word) {
71888         return Ext.Array.indexOf(this.uncountable, word) != -1;
71889     },
71890
71891     /**
71892      * Returns the pluralized form of a word (e.g. Ext.util.Inflector.pluralize('word') returns 'words')
71893      * @param {String} word The word to pluralize
71894      * @return {String} The pluralized form of the word
71895      */
71896     pluralize: function(word) {
71897         if (this.isTransnumeral(word)) {
71898             return word;
71899         }
71900
71901         var plurals = this.plurals,
71902             length  = plurals.length,
71903             tuple, regex, i;
71904         
71905         for (i = 0; i < length; i++) {
71906             tuple = plurals[i];
71907             regex = tuple[0];
71908             
71909             if (regex == word || (regex.test && regex.test(word))) {
71910                 return word.replace(regex, tuple[1]);
71911             }
71912         }
71913         
71914         return word;
71915     },
71916     
71917     /**
71918      * Returns the singularized form of a word (e.g. Ext.util.Inflector.singularize('words') returns 'word')
71919      * @param {String} word The word to singularize
71920      * @return {String} The singularized form of the word
71921      */
71922     singularize: function(word) {
71923         if (this.isTransnumeral(word)) {
71924             return word;
71925         }
71926
71927         var singulars = this.singulars,
71928             length    = singulars.length,
71929             tuple, regex, i;
71930         
71931         for (i = 0; i < length; i++) {
71932             tuple = singulars[i];
71933             regex = tuple[0];
71934             
71935             if (regex == word || (regex.test && regex.test(word))) {
71936                 return word.replace(regex, tuple[1]);
71937             }
71938         }
71939         
71940         return word;
71941     },
71942     
71943     /**
71944      * Returns the correct {@link Ext.data.Model Model} name for a given string. Mostly used internally by the data 
71945      * package
71946      * @param {String} word The word to classify
71947      * @return {String} The classified version of the word
71948      */
71949     classify: function(word) {
71950         return Ext.String.capitalize(this.singularize(word));
71951     },
71952     
71953     /**
71954      * Ordinalizes a given number by adding a prefix such as 'st', 'nd', 'rd' or 'th' based on the last digit of the 
71955      * number. 21 -> 21st, 22 -> 22nd, 23 -> 23rd, 24 -> 24th etc
71956      * @param {Number} number The number to ordinalize
71957      * @return {String} The ordinalized number
71958      */
71959     ordinalize: function(number) {
71960         var parsed = parseInt(number, 10),
71961             mod10  = parsed % 10,
71962             mod100 = parsed % 100;
71963         
71964         //11 through 13 are a special case
71965         if (11 <= mod100 && mod100 <= 13) {
71966             return number + "th";
71967         } else {
71968             switch(mod10) {
71969                 case 1 : return number + "st";
71970                 case 2 : return number + "nd";
71971                 case 3 : return number + "rd";
71972                 default: return number + "th";
71973             }
71974         }
71975     }
71976 }, function() {
71977     //aside from the rules above, there are a number of words that have irregular pluralization so we add them here
71978     var irregulars = {
71979             alumnus: 'alumni',
71980             cactus : 'cacti',
71981             focus  : 'foci',
71982             nucleus: 'nuclei',
71983             radius: 'radii',
71984             stimulus: 'stimuli',
71985             ellipsis: 'ellipses',
71986             paralysis: 'paralyses',
71987             oasis: 'oases',
71988             appendix: 'appendices',
71989             index: 'indexes',
71990             beau: 'beaux',
71991             bureau: 'bureaux',
71992             tableau: 'tableaux',
71993             woman: 'women',
71994             child: 'children',
71995             man: 'men',
71996             corpus:     'corpora',
71997             criterion: 'criteria',
71998             curriculum: 'curricula',
71999             genus: 'genera',
72000             memorandum: 'memoranda',
72001             phenomenon: 'phenomena',
72002             foot: 'feet',
72003             goose: 'geese',
72004             tooth: 'teeth',
72005             antenna: 'antennae',
72006             formula: 'formulae',
72007             nebula: 'nebulae',
72008             vertebra: 'vertebrae',
72009             vita: 'vitae'
72010         },
72011         singular;
72012     
72013     for (singular in irregulars) {
72014         this.plural(singular, irregulars[singular]);
72015         this.singular(irregulars[singular], singular);
72016     }
72017 });
72018 /**
72019  * @author Ed Spencer
72020  * @class Ext.data.HasManyAssociation
72021  * @extends Ext.data.Association
72022  * 
72023  * <p>Represents a one-to-many relationship between two models. Usually created indirectly via a model definition:</p>
72024  * 
72025 <pre><code>
72026 Ext.define('Product', {
72027     extend: 'Ext.data.Model',
72028     fields: [
72029         {name: 'id',      type: 'int'},
72030         {name: 'user_id', type: 'int'},
72031         {name: 'name',    type: 'string'}
72032     ]
72033 });
72034
72035 Ext.define('User', {
72036     extend: 'Ext.data.Model',
72037     fields: [
72038         {name: 'id',   type: 'int'},
72039         {name: 'name', type: 'string'}
72040     ],
72041     // we can use the hasMany shortcut on the model to create a hasMany association
72042     hasMany: {model: 'Product', name: 'products'}
72043 });
72044 </pre></code>
72045
72046  * <p>Above we created Product and User models, and linked them by saying that a User hasMany Products. This gives
72047  * us a new function on every User instance, in this case the function is called 'products' because that is the name
72048  * we specified in the association configuration above.</p>
72049  * 
72050  * <p>This new function returns a specialized {@link Ext.data.Store Store} which is automatically filtered to load
72051  * only Products for the given model instance:</p>
72052  * 
72053 <pre><code>
72054 //first, we load up a User with id of 1
72055 var user = Ext.ModelManager.create({id: 1, name: 'Ed'}, 'User');
72056
72057 //the user.products function was created automatically by the association and returns a {@link Ext.data.Store Store}
72058 //the created store is automatically scoped to the set of Products for the User with id of 1
72059 var products = user.products();
72060
72061 //we still have all of the usual Store functions, for example it's easy to add a Product for this User
72062 products.add({
72063     name: 'Another Product'
72064 });
72065
72066 //saves the changes to the store - this automatically sets the new Product's user_id to 1 before saving
72067 products.sync();
72068 </code></pre>
72069  * 
72070  * <p>The new Store is only instantiated the first time you call products() to conserve memory and processing time,
72071  * though calling products() a second time returns the same store instance.</p>
72072  * 
72073  * <p><u>Custom filtering</u></p>
72074  * 
72075  * <p>The Store is automatically furnished with a filter - by default this filter tells the store to only return
72076  * records where the associated model's foreign key matches the owner model's primary key. For example, if a User
72077  * with ID = 100 hasMany Products, the filter loads only Products with user_id == 100.</p>
72078  * 
72079  * <p>Sometimes we want to filter by another field - for example in the case of a Twitter search application we may
72080  * have models for Search and Tweet:</p>
72081  * 
72082 <pre><code>
72083 Ext.define('Search', {
72084     extend: 'Ext.data.Model',
72085     fields: [
72086         'id', 'query'
72087     ],
72088
72089     hasMany: {
72090         model: 'Tweet',
72091         name : 'tweets',
72092         filterProperty: 'query'
72093     }
72094 });
72095
72096 Ext.define('Tweet', {
72097     extend: 'Ext.data.Model',
72098     fields: [
72099         'id', 'text', 'from_user'
72100     ]
72101 });
72102
72103 //returns a Store filtered by the filterProperty
72104 var store = new Search({query: 'Sencha Touch'}).tweets();
72105 </code></pre>
72106  * 
72107  * <p>The tweets association above is filtered by the query property by setting the {@link #filterProperty}, and is
72108  * equivalent to this:</p>
72109  * 
72110 <pre><code>
72111 var store = new Ext.data.Store({
72112     model: 'Tweet',
72113     filters: [
72114         {
72115             property: 'query',
72116             value   : 'Sencha Touch'
72117         }
72118     ]
72119 });
72120 </code></pre>
72121  */
72122 Ext.define('Ext.data.HasManyAssociation', {
72123     extend: 'Ext.data.Association',
72124     requires: ['Ext.util.Inflector'],
72125
72126     alias: 'association.hasmany',
72127
72128     /**
72129      * @cfg {String} foreignKey The name of the foreign key on the associated model that links it to the owner
72130      * model. Defaults to the lowercased name of the owner model plus "_id", e.g. an association with a where a
72131      * model called Group hasMany Users would create 'group_id' as the foreign key. When the remote store is loaded,
72132      * the store is automatically filtered so that only records with a matching foreign key are included in the 
72133      * resulting child store. This can be overridden by specifying the {@link #filterProperty}.
72134      * <pre><code>
72135 Ext.define('Group', {
72136     extend: 'Ext.data.Model',
72137     fields: ['id', 'name'],
72138     hasMany: 'User'
72139 });
72140
72141 Ext.define('User', {
72142     extend: 'Ext.data.Model',
72143     fields: ['id', 'name', 'group_id'], // refers to the id of the group that this user belongs to
72144     belongsTo: 'Group'
72145 });
72146      * </code></pre>
72147      */
72148     
72149     /**
72150      * @cfg {String} name The name of the function to create on the owner model to retrieve the child store.
72151      * If not specified, the pluralized name of the child model is used.
72152      * <pre><code>
72153 // This will create a users() method on any Group model instance
72154 Ext.define('Group', {
72155     extend: 'Ext.data.Model',
72156     fields: ['id', 'name'],
72157     hasMany: 'User'
72158 });
72159 var group = new Group();
72160 console.log(group.users());
72161
72162 // The method to retrieve the users will now be getUserList
72163 Ext.define('Group', {
72164     extend: 'Ext.data.Model',
72165     fields: ['id', 'name'],
72166     hasMany: {model: 'User', name: 'getUserList'}
72167 });
72168 var group = new Group();
72169 console.log(group.getUserList());
72170      * </code></pre>
72171      */
72172     
72173     /**
72174      * @cfg {Object} storeConfig Optional configuration object that will be passed to the generated Store. Defaults to 
72175      * undefined.
72176      */
72177     
72178     /**
72179      * @cfg {String} filterProperty Optionally overrides the default filter that is set up on the associated Store. If
72180      * this is not set, a filter is automatically created which filters the association based on the configured 
72181      * {@link #foreignKey}. See intro docs for more details. Defaults to undefined
72182      */
72183     
72184     /**
72185      * @cfg {Boolean} autoLoad True to automatically load the related store from a remote source when instantiated.
72186      * Defaults to <tt>false</tt>.
72187      */
72188     
72189     /**
72190      * @cfg {String} type The type configuration can be used when creating associations using a configuration object.
72191      * Use 'hasMany' to create a HasManyAssocation
72192      * <pre><code>
72193 associations: [{
72194     type: 'hasMany',
72195     model: 'User'
72196 }]
72197      * </code></pre>
72198      */
72199     
72200     constructor: function(config) {
72201         var me = this,
72202             ownerProto,
72203             name;
72204             
72205         me.callParent(arguments);
72206         
72207         me.name = me.name || Ext.util.Inflector.pluralize(me.associatedName.toLowerCase());
72208         
72209         ownerProto = me.ownerModel.prototype;
72210         name = me.name;
72211         
72212         Ext.applyIf(me, {
72213             storeName : name + "Store",
72214             foreignKey: me.ownerName.toLowerCase() + "_id"
72215         });
72216         
72217         ownerProto[name] = me.createStore();
72218     },
72219     
72220     /**
72221      * @private
72222      * Creates a function that returns an Ext.data.Store which is configured to load a set of data filtered
72223      * by the owner model's primary key - e.g. in a hasMany association where Group hasMany Users, this function
72224      * returns a Store configured to return the filtered set of a single Group's Users.
72225      * @return {Function} The store-generating function
72226      */
72227     createStore: function() {
72228         var that            = this,
72229             associatedModel = that.associatedModel,
72230             storeName       = that.storeName,
72231             foreignKey      = that.foreignKey,
72232             primaryKey      = that.primaryKey,
72233             filterProperty  = that.filterProperty,
72234             autoLoad        = that.autoLoad,
72235             storeConfig     = that.storeConfig || {};
72236         
72237         return function() {
72238             var me = this,
72239                 config, filter,
72240                 modelDefaults = {};
72241                 
72242             if (me[storeName] === undefined) {
72243                 if (filterProperty) {
72244                     filter = {
72245                         property  : filterProperty,
72246                         value     : me.get(filterProperty),
72247                         exactMatch: true
72248                     };
72249                 } else {
72250                     filter = {
72251                         property  : foreignKey,
72252                         value     : me.get(primaryKey),
72253                         exactMatch: true
72254                     };
72255                 }
72256                 
72257                 modelDefaults[foreignKey] = me.get(primaryKey);
72258                 
72259                 config = Ext.apply({}, storeConfig, {
72260                     model        : associatedModel,
72261                     filters      : [filter],
72262                     remoteFilter : false,
72263                     modelDefaults: modelDefaults
72264                 });
72265                 
72266                 me[storeName] = Ext.create('Ext.data.Store', config);
72267                 if (autoLoad) {
72268                     me[storeName].load();
72269                 }
72270             }
72271             
72272             return me[storeName];
72273         };
72274     },
72275     
72276     /**
72277      * Read associated data
72278      * @private
72279      * @param {Ext.data.Model} record The record we're writing to
72280      * @param {Ext.data.reader.Reader} reader The reader for the associated model
72281      * @param {Object} associationData The raw associated data
72282      */
72283     read: function(record, reader, associationData){
72284         var store = record[this.name](),
72285             inverse;
72286     
72287         store.add(reader.read(associationData).records);
72288     
72289         //now that we've added the related records to the hasMany association, set the inverse belongsTo
72290         //association on each of them if it exists
72291         inverse = this.associatedModel.prototype.associations.findBy(function(assoc){
72292             return assoc.type === 'belongsTo' && assoc.associatedName === record.$className;
72293         });
72294     
72295         //if the inverse association was found, set it now on each record we've just created
72296         if (inverse) {
72297             store.data.each(function(associatedRecord){
72298                 associatedRecord[inverse.instanceName] = record;
72299             });
72300         }
72301     }
72302 });
72303 /**
72304  * @class Ext.data.JsonP
72305  * @singleton
72306  * This class is used to create JSONP requests. JSONP is a mechanism that allows for making
72307  * requests for data cross domain. More information is available here:
72308  * http://en.wikipedia.org/wiki/JSONP
72309  */
72310 Ext.define('Ext.data.JsonP', {
72311     
72312     /* Begin Definitions */
72313     
72314     singleton: true,
72315     
72316     statics: {
72317         requestCount: 0,
72318         requests: {}
72319     },
72320     
72321     /* End Definitions */
72322     
72323     /**
72324      * @property timeout
72325      * @type Number
72326      * A default timeout for any JsonP requests. If the request has not completed in this time the
72327      * failure callback will be fired. The timeout is in ms. Defaults to <tt>30000</tt>.
72328      */
72329     timeout: 30000,
72330     
72331     /**
72332      * @property disableCaching
72333      * @type Boolean
72334      * True to add a unique cache-buster param to requests. Defaults to <tt>true</tt>.
72335      */
72336     disableCaching: true,
72337    
72338     /**
72339      * @property disableCachingParam 
72340      * @type String
72341      * Change the parameter which is sent went disabling caching through a cache buster. Defaults to <tt>'_dc'</tt>.
72342      */
72343     disableCachingParam: '_dc',
72344    
72345     /**
72346      * @property callbackKey
72347      * @type String
72348      * Specifies the GET parameter that will be sent to the server containing the function name to be executed when
72349      * the request completes. Defaults to <tt>callback</tt>. Thus, a common request will be in the form of
72350      * url?callback=Ext.data.JsonP.callback1
72351      */
72352     callbackKey: 'callback',
72353    
72354     /**
72355      * Makes a JSONP request.
72356      * @param {Object} options An object which may contain the following properties. Note that options will
72357      * take priority over any defaults that are specified in the class.
72358      * <ul>
72359      * <li><b>url</b> : String <div class="sub-desc">The URL to request.</div></li>
72360      * <li><b>params</b> : Object (Optional)<div class="sub-desc">An object containing a series of
72361      * key value pairs that will be sent along with the request.</div></li>
72362      * <li><b>timeout</b> : Number (Optional) <div class="sub-desc">See {@link #timeout}</div></li>
72363      * <li><b>callbackKey</b> : String (Optional) <div class="sub-desc">See {@link #callbackKey}</div></li>
72364      * <li><b>disableCaching</b> : Boolean (Optional) <div class="sub-desc">See {@link #disableCaching}</div></li>
72365      * <li><b>disableCachingParam</b> : String (Optional) <div class="sub-desc">See {@link #disableCachingParam}</div></li>
72366      * <li><b>success</b> : Function (Optional) <div class="sub-desc">A function to execute if the request succeeds.</div></li>
72367      * <li><b>failure</b> : Function (Optional) <div class="sub-desc">A function to execute if the request fails.</div></li>
72368      * <li><b>callback</b> : Function (Optional) <div class="sub-desc">A function to execute when the request 
72369      * completes, whether it is a success or failure.</div></li>
72370      * <li><b>scope</b> : Object (Optional)<div class="sub-desc">The scope in
72371      * which to execute the callbacks: The "this" object for the callback function. Defaults to the browser window.</div></li>
72372      * </ul>
72373      * @return {Object} request An object containing the request details.
72374      */
72375     request: function(options){
72376         options = Ext.apply({}, options);
72377        
72378         if (!options.url) {
72379             Ext.Error.raise('A url must be specified for a JSONP request.');
72380         }
72381         
72382         var me = this, 
72383             disableCaching = Ext.isDefined(options.disableCaching) ? options.disableCaching : me.disableCaching, 
72384             cacheParam = options.disableCachingParam || me.disableCachingParam, 
72385             id = ++me.statics().requestCount, 
72386             callbackName = 'callback' + id, 
72387             callbackKey = options.callbackKey || me.callbackKey, 
72388             timeout = Ext.isDefined(options.timeout) ? options.timeout : me.timeout, 
72389             params = Ext.apply({}, options.params), 
72390             url = options.url,
72391             request, 
72392             script;
72393             
72394         params[callbackKey] = 'Ext.data.JsonP.' + callbackName;
72395         if (disableCaching) {
72396             params[cacheParam] = new Date().getTime();
72397         }
72398         
72399         script = me.createScript(url, params);
72400         
72401         me.statics().requests[id] = request = {
72402             url: url,
72403             params: params,
72404             script: script,
72405             id: id,
72406             scope: options.scope,
72407             success: options.success,
72408             failure: options.failure,
72409             callback: options.callback,
72410             callbackName: callbackName
72411         };
72412         
72413         if (timeout > 0) {
72414             request.timeout = setTimeout(Ext.bind(me.handleTimeout, me, [request]), timeout);
72415         }
72416         
72417         me.setupErrorHandling(request);
72418         me[callbackName] = Ext.bind(me.handleResponse, me, [request], true);
72419         Ext.getHead().appendChild(script);
72420         return request;
72421     },
72422     
72423     /**
72424      * Abort a request. If the request parameter is not specified all open requests will
72425      * be aborted.
72426      * @param {Object/String} request (Optional) The request to abort
72427      */
72428     abort: function(request){
72429         var requests = this.statics().requests,
72430             key;
72431             
72432         if (request) {
72433             if (!request.id) {
72434                 request = requests[request];
72435             }
72436             this.abort(request);
72437         } else {
72438             for (key in requests) {
72439                 if (requests.hasOwnProperty(key)) {
72440                     this.abort(requests[key]);
72441                 }
72442             }
72443         }
72444     },
72445     
72446     /**
72447      * Sets up error handling for the script
72448      * @private
72449      * @param {Object} request The request
72450      */
72451     setupErrorHandling: function(request){
72452         request.script.onerror = Ext.bind(this.handleError, this, [request]);
72453     },
72454     
72455     /**
72456      * Handles any aborts when loading the script
72457      * @private
72458      * @param {Object} request The request
72459      */
72460     handleAbort: function(request){
72461         request.errorType = 'abort';
72462         this.handleResponse(null, request);
72463     },
72464     
72465     /**
72466      * Handles any script errors when loading the script
72467      * @private
72468      * @param {Object} request The request
72469      */
72470     handleError: function(request){
72471         request.errorType = 'error';
72472         this.handleResponse(null, request);
72473     },
72474  
72475     /**
72476      * Cleans up anu script handling errors
72477      * @private
72478      * @param {Object} request The request
72479      */
72480     cleanupErrorHandling: function(request){
72481         request.script.onerror = null;
72482     },
72483  
72484     /**
72485      * Handle any script timeouts
72486      * @private
72487      * @param {Object} request The request
72488      */
72489     handleTimeout: function(request){
72490         request.errorType = 'timeout';
72491         this.handleResponse(null, request);
72492     },
72493  
72494     /**
72495      * Handle a successful response
72496      * @private
72497      * @param {Object} result The result from the request
72498      * @param {Object} request The request
72499      */
72500     handleResponse: function(result, request){
72501  
72502         var success = true;
72503  
72504         if (request.timeout) {
72505             clearTimeout(request.timeout);
72506         }
72507         delete this[request.callbackName];
72508         delete this.statics()[request.id];
72509         this.cleanupErrorHandling(request);
72510         Ext.fly(request.script).remove();
72511  
72512         if (request.errorType) {
72513             success = false;
72514             Ext.callback(request.failure, request.scope, [request.errorType]);
72515         } else {
72516             Ext.callback(request.success, request.scope, [result]);
72517         }
72518         Ext.callback(request.callback, request.scope, [success, result, request.errorType]);
72519     },
72520     
72521     /**
72522      * Create the script tag
72523      * @private
72524      * @param {String} url The url of the request
72525      * @param {Object} params Any extra params to be sent
72526      */
72527     createScript: function(url, params) {
72528         var script = document.createElement('script');
72529         script.setAttribute("src", Ext.urlAppend(url, Ext.Object.toQueryString(params)));
72530         script.setAttribute("async", true);
72531         script.setAttribute("type", "text/javascript");
72532         return script;
72533     }
72534 });
72535
72536 /**
72537  * @class Ext.data.JsonPStore
72538  * @extends Ext.data.Store
72539  * @ignore
72540  * @private
72541  * <p><b>NOTE:</b> This class is in need of migration to the new API.</p>
72542  * <p>Small helper class to make creating {@link Ext.data.Store}s from different domain JSON data easier.
72543  * A JsonPStore will be automatically configured with a {@link Ext.data.reader.Json} and a {@link Ext.data.proxy.JsonP JsonPProxy}.</p>
72544  * <p>A store configuration would be something like:<pre><code>
72545 var store = new Ext.data.JsonPStore({
72546     // store configs
72547     autoDestroy: true,
72548     storeId: 'myStore',
72549
72550     // proxy configs
72551     url: 'get-images.php',
72552
72553     // reader configs
72554     root: 'images',
72555     idProperty: 'name',
72556     fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
72557 });
72558  * </code></pre></p>
72559  * <p>This store is configured to consume a returned object of the form:<pre><code>
72560 stcCallback({
72561     images: [
72562         {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
72563         {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
72564     ]
72565 })
72566  * </code></pre>
72567  * <p>Where stcCallback is the callback name passed in the request to the remote domain. See {@link Ext.data.proxy.JsonP JsonPProxy}
72568  * for details of how this works.</p>
72569  * An object literal of this form could also be used as the {@link #data} config option.</p>
72570  * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
72571  * <b>{@link Ext.data.reader.Json JsonReader}</b> and <b>{@link Ext.data.proxy.JsonP JsonPProxy}</b>.</p>
72572  * @constructor
72573  * @param {Object} config
72574  * @xtype jsonpstore
72575  */
72576 Ext.define('Ext.data.JsonPStore', {
72577     extend: 'Ext.data.Store',
72578     alias : 'store.jsonp',
72579
72580     /**
72581      * @cfg {Ext.data.DataReader} reader @hide
72582      */
72583     constructor: function(config) {
72584         this.callParent(Ext.apply(config, {
72585             reader: Ext.create('Ext.data.reader.Json', config),
72586             proxy : Ext.create('Ext.data.proxy.JsonP', config)
72587         }));
72588     }
72589 });
72590
72591 /**
72592  * @class Ext.data.NodeInterface
72593  * This class is meant to be used as a set of methods that are applied to the prototype of a
72594  * Record to decorate it with a Node API. This means that models used in conjunction with a tree
72595  * will have all of the tree related methods available on the model. In general this class will
72596  * not be used directly by the developer.
72597  */
72598 Ext.define('Ext.data.NodeInterface', {
72599     requires: ['Ext.data.Field'],
72600     
72601     statics: {
72602         /**
72603          * This method allows you to decorate a Record's prototype to implement the NodeInterface.
72604          * This adds a set of methods, new events, new properties and new fields on every Record
72605          * with the same Model as the passed Record.
72606          * @param {Ext.data.Record} record The Record you want to decorate the prototype of.
72607          * @static
72608          */
72609         decorate: function(record) {
72610             if (!record.isNode) {
72611                 // Apply the methods and fields to the prototype
72612                 // @TODO: clean this up to use proper class system stuff
72613                 var mgr = Ext.ModelManager,
72614                     modelName = record.modelName,
72615                     modelClass = mgr.getModel(modelName),
72616                     idName = modelClass.prototype.idProperty,
72617                     instances = Ext.Array.filter(mgr.all.getArray(), function(item) {
72618                         return item.modelName == modelName;
72619                     }),
72620                     iln = instances.length,
72621                     newFields = [],
72622                     i, instance, jln, j, newField;
72623
72624                 // Start by adding the NodeInterface methods to the Model's prototype
72625                 modelClass.override(this.getPrototypeBody());
72626                 newFields = this.applyFields(modelClass, [
72627                     {name: idName,      type: 'string',  defaultValue: null},
72628                     {name: 'parentId',  type: 'string',  defaultValue: null},
72629                     {name: 'index',     type: 'int',     defaultValue: null},
72630                     {name: 'depth',     type: 'int',     defaultValue: 0}, 
72631                     {name: 'expanded',  type: 'bool',    defaultValue: false, persist: false},
72632                     {name: 'checked',   type: 'auto',    defaultValue: null},
72633                     {name: 'leaf',      type: 'bool',    defaultValue: false, persist: false},
72634                     {name: 'cls',       type: 'string',  defaultValue: null, persist: false},
72635                     {name: 'iconCls',   type: 'string',  defaultValue: null, persist: false},
72636                     {name: 'root',      type: 'boolean', defaultValue: false, persist: false},
72637                     {name: 'isLast',    type: 'boolean', defaultValue: false, persist: false},
72638                     {name: 'isFirst',   type: 'boolean', defaultValue: false, persist: false},
72639                     {name: 'allowDrop', type: 'boolean', defaultValue: true, persist: false},
72640                     {name: 'allowDrag', type: 'boolean', defaultValue: true, persist: false},
72641                     {name: 'loaded',    type: 'boolean', defaultValue: false, persist: false},
72642                     {name: 'loading',   type: 'boolean', defaultValue: false, persist: false},
72643                     {name: 'href',      type: 'string',  defaultValue: null, persist: false},
72644                     {name: 'hrefTarget',type: 'string',  defaultValue: null, persist: false},
72645                     {name: 'qtip',      type: 'string',  defaultValue: null, persist: false},
72646                     {name: 'qtitle',    type: 'string',  defaultValue: null, persist: false}
72647                 ]);
72648
72649                 jln = newFields.length;
72650                 // Set default values to all instances already out there
72651                 for (i = 0; i < iln; i++) {
72652                     instance = instances[i];
72653                     for (j = 0; j < jln; j++) {
72654                         newField = newFields[j];
72655                         if (instance.get(newField.name) === undefined) {
72656                             instance.data[newField.name] = newField.defaultValue;
72657                         }
72658                     }
72659                 }
72660             }
72661             
72662             Ext.applyIf(record, {
72663                 firstChild: null,
72664                 lastChild: null,
72665                 parentNode: null,
72666                 previousSibling: null,
72667                 nextSibling: null,
72668                 childNodes: []
72669             });
72670             // Commit any fields so the record doesn't show as dirty initially
72671             record.commit(true);
72672             
72673             record.enableBubble([
72674                 /**
72675                  * @event append
72676                  * Fires when a new child node is appended
72677                  * @param {Node} this This node
72678                  * @param {Node} node The newly appended node
72679                  * @param {Number} index The index of the newly appended node
72680                  */
72681                 "append",
72682
72683                 /**
72684                  * @event remove
72685                  * Fires when a child node is removed
72686                  * @param {Node} this This node
72687                  * @param {Node} node The removed node
72688                  */
72689                 "remove",
72690
72691                 /**
72692                  * @event move
72693                  * Fires when this node is moved to a new location in the tree
72694                  * @param {Node} this This node
72695                  * @param {Node} oldParent The old parent of this node
72696                  * @param {Node} newParent The new parent of this node
72697                  * @param {Number} index The index it was moved to
72698                  */
72699                 "move",
72700
72701                 /**
72702                  * @event insert
72703                  * Fires when a new child node is inserted.
72704                  * @param {Node} this This node
72705                  * @param {Node} node The child node inserted
72706                  * @param {Node} refNode The child node the node was inserted before
72707                  */
72708                 "insert",
72709
72710                 /**
72711                  * @event beforeappend
72712                  * Fires before a new child is appended, return false to cancel the append.
72713                  * @param {Node} this This node
72714                  * @param {Node} node The child node to be appended
72715                  */
72716                 "beforeappend",
72717
72718                 /**
72719                  * @event beforeremove
72720                  * Fires before a child is removed, return false to cancel the remove.
72721                  * @param {Node} this This node
72722                  * @param {Node} node The child node to be removed
72723                  */
72724                 "beforeremove",
72725
72726                 /**
72727                  * @event beforemove
72728                  * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
72729                  * @param {Node} this This node
72730                  * @param {Node} oldParent The parent of this node
72731                  * @param {Node} newParent The new parent this node is moving to
72732                  * @param {Number} index The index it is being moved to
72733                  */
72734                 "beforemove",
72735
72736                  /**
72737                   * @event beforeinsert
72738                   * Fires before a new child is inserted, return false to cancel the insert.
72739                   * @param {Node} this This node
72740                   * @param {Node} node The child node to be inserted
72741                   * @param {Node} refNode The child node the node is being inserted before
72742                   */
72743                 "beforeinsert",
72744                 
72745                 /**
72746                  * @event expand
72747                  * Fires when this node is expanded.
72748                  * @param {Node} this The expanding node
72749                  */
72750                 "expand",
72751                 
72752                 /**
72753                  * @event collapse
72754                  * Fires when this node is collapsed.
72755                  * @param {Node} this The collapsing node
72756                  */
72757                 "collapse",
72758                 
72759                 /**
72760                  * @event beforeexpand
72761                  * Fires before this node is expanded.
72762                  * @param {Node} this The expanding node
72763                  */
72764                 "beforeexpand",
72765                 
72766                 /**
72767                  * @event beforecollapse
72768                  * Fires before this node is collapsed.
72769                  * @param {Node} this The collapsing node
72770                  */
72771                 "beforecollapse",
72772                 
72773                 /**
72774                  * @event beforecollapse
72775                  * Fires before this node is collapsed.
72776                  * @param {Node} this The collapsing node
72777                  */
72778                 "sort"
72779             ]);
72780             
72781             return record;
72782         },
72783         
72784         applyFields: function(modelClass, addFields) {
72785             var modelPrototype = modelClass.prototype,
72786                 fields = modelPrototype.fields,
72787                 keys = fields.keys,
72788                 ln = addFields.length,
72789                 addField, i, name,
72790                 newFields = [];
72791                 
72792             for (i = 0; i < ln; i++) {
72793                 addField = addFields[i];
72794                 if (!Ext.Array.contains(keys, addField.name)) {
72795                     addField = Ext.create('data.field', addField);
72796                     
72797                     newFields.push(addField);
72798                     fields.add(addField);
72799                 }
72800             }
72801             
72802             return newFields;
72803         },
72804         
72805         getPrototypeBody: function() {
72806             return {
72807                 isNode: true,
72808
72809                 /**
72810                  * Ensures that the passed object is an instance of a Record with the NodeInterface applied
72811                  * @return {Boolean}
72812                  */
72813                 createNode: function(node) {
72814                     if (Ext.isObject(node) && !node.isModel) {
72815                         node = Ext.ModelManager.create(node, this.modelName);
72816                     }
72817                     // Make sure the node implements the node interface
72818                     return Ext.data.NodeInterface.decorate(node);
72819                 },
72820                 
72821                 /**
72822                  * Returns true if this node is a leaf
72823                  * @return {Boolean}
72824                  */
72825                 isLeaf : function() {
72826                     return this.get('leaf') === true;
72827                 },
72828
72829                 /**
72830                  * Sets the first child of this node
72831                  * @private
72832                  * @param {Ext.data.NodeInterface} node
72833                  */
72834                 setFirstChild : function(node) {
72835                     this.firstChild = node;
72836                 },
72837
72838                 /**
72839                  * Sets the last child of this node
72840                  * @private
72841                  * @param {Ext.data.NodeInterface} node
72842                  */
72843                 setLastChild : function(node) {
72844                     this.lastChild = node;
72845                 },
72846
72847                 /**
72848                  * Updates general data of this node like isFirst, isLast, depth. This
72849                  * method is internally called after a node is moved. This shouldn't
72850                  * have to be called by the developer unless they are creating custom
72851                  * Tree plugins.
72852                  * @return {Boolean}
72853                  */
72854                 updateInfo: function(silent) {
72855                     var me = this,
72856                         isRoot = me.isRoot(),
72857                         parentNode = me.parentNode,
72858                         isFirst = (!parentNode ? true : parentNode.firstChild == me),
72859                         isLast = (!parentNode ? true : parentNode.lastChild == me),
72860                         depth = 0,
72861                         parent = me,
72862                         children = me.childNodes,
72863                         len = children.length,
72864                         i = 0;
72865
72866                     while (parent.parentNode) {
72867                         ++depth;
72868                         parent = parent.parentNode;
72869                     }                                            
72870                     
72871                     me.beginEdit();
72872                     me.set({
72873                         isFirst: isFirst,
72874                         isLast: isLast,
72875                         depth: depth,
72876                         index: parentNode ? parentNode.indexOf(me) : 0,
72877                         parentId: parentNode ? parentNode.getId() : null
72878                     });
72879                     me.endEdit(silent);
72880                     if (silent) {
72881                         me.commit();
72882                     }
72883                     
72884                     for (i = 0; i < len; i++) {
72885                         children[i].updateInfo(silent);
72886                     }
72887                 },
72888
72889                 /**
72890                  * Returns true if this node is the last child of its parent
72891                  * @return {Boolean}
72892                  */
72893                 isLast : function() {
72894                    return this.get('isLast');
72895                 },
72896
72897                 /**
72898                  * Returns true if this node is the first child of its parent
72899                  * @return {Boolean}
72900                  */
72901                 isFirst : function() {
72902                    return this.get('isFirst');
72903                 },
72904
72905                 /**
72906                  * Returns true if this node has one or more child nodes, else false.
72907                  * @return {Boolean}
72908                  */
72909                 hasChildNodes : function() {
72910                     return !this.isLeaf() && this.childNodes.length > 0;
72911                 },
72912
72913                 /**
72914                  * Returns true if this node has one or more child nodes, or if the <tt>expandable</tt>
72915                  * node attribute is explicitly specified as true (see {@link #attributes}), otherwise returns false.
72916                  * @return {Boolean}
72917                  */
72918                 isExpandable : function() {
72919                     return this.get('expandable') || this.hasChildNodes();
72920                 },
72921
72922                 /**
72923                  * <p>Insert node(s) as the last child node of this node.</p>
72924                  * <p>If the node was previously a child node of another parent node, it will be removed from that node first.</p>
72925                  * @param {Node/Array} node The node or Array of nodes to append
72926                  * @return {Node} The appended node if single append, or null if an array was passed
72927                  */
72928                 appendChild : function(node, suppressEvents, suppressNodeUpdate) {
72929                     var me = this,
72930                         i, ln,
72931                         index,
72932                         oldParent,
72933                         ps;
72934
72935                     // if passed an array or multiple args do them one by one
72936                     if (Ext.isArray(node)) {
72937                         for (i = 0, ln = node.length; i < ln; i++) {
72938                             me.appendChild(node[i]);
72939                         }
72940                     } else {
72941                         // Make sure it is a record
72942                         node = me.createNode(node);
72943                         
72944                         if (suppressEvents !== true && me.fireEvent("beforeappend", me, node) === false) {
72945                             return false;                         
72946                         }
72947
72948                         index = me.childNodes.length;
72949                         oldParent = node.parentNode;
72950
72951                         // it's a move, make sure we move it cleanly
72952                         if (oldParent) {
72953                             if (suppressEvents !== true && node.fireEvent("beforemove", node, oldParent, me, index) === false) {
72954                                 return false;
72955                             }
72956                             oldParent.removeChild(node, null, false, true);
72957                         }
72958
72959                         index = me.childNodes.length;
72960                         if (index === 0) {
72961                             me.setFirstChild(node);
72962                         }
72963
72964                         me.childNodes.push(node);
72965                         node.parentNode = me;
72966                         node.nextSibling = null;
72967
72968                         me.setLastChild(node);
72969                                                 
72970                         ps = me.childNodes[index - 1];
72971                         if (ps) {
72972                             node.previousSibling = ps;
72973                             ps.nextSibling = node;
72974                             ps.updateInfo(suppressNodeUpdate);
72975                         } else {
72976                             node.previousSibling = null;
72977                         }
72978
72979                         node.updateInfo(suppressNodeUpdate);
72980                         
72981                         // As soon as we append a child to this node, we are loaded
72982                         if (!me.isLoaded()) {
72983                             me.set('loaded', true);                            
72984                         }
72985                         // If this node didnt have any childnodes before, update myself
72986                         else if (me.childNodes.length === 1) {
72987                             me.set('loaded', me.isLoaded());
72988                         }
72989                         
72990                         if (suppressEvents !== true) {
72991                             me.fireEvent("append", me, node, index);
72992
72993                             if (oldParent) {
72994                                 node.fireEvent("move", node, oldParent, me, index);
72995                             }                            
72996                         }
72997
72998                         return node;
72999                     }
73000                 },
73001                 
73002                 /**
73003                  * Returns the bubble target for this node
73004                  * @private
73005                  * @return {Object} The bubble target
73006                  */
73007                 getBubbleTarget: function() {
73008                     return this.parentNode;
73009                 },
73010
73011                 /**
73012                  * Removes a child node from this node.
73013                  * @param {Node} node The node to remove
73014                  * @param {Boolean} destroy <tt>true</tt> to destroy the node upon removal. Defaults to <tt>false</tt>.
73015                  * @return {Node} The removed node
73016                  */
73017                 removeChild : function(node, destroy, suppressEvents, suppressNodeUpdate) {
73018                     var me = this,
73019                         index = me.indexOf(node);
73020                     
73021                     if (index == -1 || (suppressEvents !== true && me.fireEvent("beforeremove", me, node) === false)) {
73022                         return false;
73023                     }
73024
73025                     // remove it from childNodes collection
73026                     me.childNodes.splice(index, 1);
73027
73028                     // update child refs
73029                     if (me.firstChild == node) {
73030                         me.setFirstChild(node.nextSibling);
73031                     }
73032                     if (me.lastChild == node) {
73033                         me.setLastChild(node.previousSibling);
73034                     }
73035                     
73036                     // update siblings
73037                     if (node.previousSibling) {
73038                         node.previousSibling.nextSibling = node.nextSibling;
73039                         node.previousSibling.updateInfo(suppressNodeUpdate);
73040                     }
73041                     if (node.nextSibling) {
73042                         node.nextSibling.previousSibling = node.previousSibling;
73043                         node.nextSibling.updateInfo(suppressNodeUpdate);
73044                     }
73045
73046                     if (suppressEvents !== true) {
73047                         me.fireEvent("remove", me, node);
73048                     }
73049                     
73050                     
73051                     // If this node suddenly doesnt have childnodes anymore, update myself
73052                     if (!me.childNodes.length) {
73053                         me.set('loaded', me.isLoaded());
73054                     }
73055                     
73056                     if (destroy) {
73057                         node.destroy(true);
73058                     } else {
73059                         node.clear();
73060                     }
73061
73062                     return node;
73063                 },
73064
73065                 /**
73066                  * Creates a copy (clone) of this Node.
73067                  * @param {String} id (optional) A new id, defaults to this Node's id. See <code>{@link #id}</code>.
73068                  * @param {Boolean} deep (optional) <p>If passed as <code>true</code>, all child Nodes are recursively copied into the new Node.</p>
73069                  * <p>If omitted or false, the copy will have no child Nodes.</p>
73070                  * @return {Node} A copy of this Node.
73071                  */
73072                 copy: function(newId, deep) {
73073                     var me = this,
73074                         result = me.callOverridden(arguments),
73075                         len = me.childNodes ? me.childNodes.length : 0,
73076                         i;
73077
73078                     // Move child nodes across to the copy if required
73079                     if (deep) {
73080                         for (i = 0; i < len; i++) {
73081                             result.appendChild(me.childNodes[i].copy(true));
73082                         }
73083                     }
73084                     return result;
73085                 },
73086
73087                 /**
73088                  * Clear the node.
73089                  * @private
73090                  * @param {Boolean} destroy True to destroy the node.
73091                  */
73092                 clear : function(destroy) {
73093                     var me = this;
73094                     
73095                     // clear any references from the node
73096                     me.parentNode = me.previousSibling = me.nextSibling = null;
73097                     if (destroy) {
73098                         me.firstChild = me.lastChild = null;
73099                     }
73100                 },
73101
73102                 /**
73103                  * Destroys the node.
73104                  */
73105                 destroy : function(silent) {
73106                     /*
73107                      * Silent is to be used in a number of cases
73108                      * 1) When setRoot is called.
73109                      * 2) When destroy on the tree is called
73110                      * 3) For destroying child nodes on a node
73111                      */
73112                     var me = this;
73113                     
73114                     if (silent === true) {
73115                         me.clear(true);
73116                         Ext.each(me.childNodes, function(n) {
73117                             n.destroy(true);
73118                         });
73119                         me.childNodes = null;
73120                     } else {
73121                         me.remove(true);
73122                     }
73123
73124                     me.callOverridden();
73125                 },
73126
73127                 /**
73128                  * Inserts the first node before the second node in this nodes childNodes collection.
73129                  * @param {Node} node The node to insert
73130                  * @param {Node} refNode The node to insert before (if null the node is appended)
73131                  * @return {Node} The inserted node
73132                  */
73133                 insertBefore : function(node, refNode, suppressEvents) {
73134                     var me = this,
73135                         index     = me.indexOf(refNode),
73136                         oldParent = node.parentNode,
73137                         refIndex  = index,
73138                         ps;
73139                     
73140                     if (!refNode) { // like standard Dom, refNode can be null for append
73141                         return me.appendChild(node);
73142                     }
73143                     
73144                     // nothing to do
73145                     if (node == refNode) {
73146                         return false;
73147                     }
73148
73149                     // Make sure it is a record with the NodeInterface
73150                     node = me.createNode(node);
73151                     
73152                     if (suppressEvents !== true && me.fireEvent("beforeinsert", me, node, refNode) === false) {
73153                         return false;
73154                     }
73155                     
73156                     // when moving internally, indexes will change after remove
73157                     if (oldParent == me && me.indexOf(node) < index) {
73158                         refIndex--;
73159                     }
73160
73161                     // it's a move, make sure we move it cleanly
73162                     if (oldParent) {
73163                         if (suppressEvents !== true && node.fireEvent("beforemove", node, oldParent, me, index, refNode) === false) {
73164                             return false;
73165                         }
73166                         oldParent.removeChild(node);
73167                     }
73168
73169                     if (refIndex === 0) {
73170                         me.setFirstChild(node);
73171                     }
73172
73173                     me.childNodes.splice(refIndex, 0, node);
73174                     node.parentNode = me;
73175                     
73176                     node.nextSibling = refNode;
73177                     refNode.previousSibling = node;
73178                     
73179                     ps = me.childNodes[refIndex - 1];
73180                     if (ps) {
73181                         node.previousSibling = ps;
73182                         ps.nextSibling = node;
73183                         ps.updateInfo();
73184                     } else {
73185                         node.previousSibling = null;
73186                     }
73187                     
73188                     node.updateInfo();
73189                     
73190                     if (!me.isLoaded()) {
73191                         me.set('loaded', true);                            
73192                     }    
73193                     // If this node didnt have any childnodes before, update myself
73194                     else if (me.childNodes.length === 1) {
73195                         me.set('loaded', me.isLoaded());
73196                     }
73197
73198                     if (suppressEvents !== true) {
73199                         me.fireEvent("insert", me, node, refNode);
73200
73201                         if (oldParent) {
73202                             node.fireEvent("move", node, oldParent, me, refIndex, refNode);
73203                         }                        
73204                     }
73205
73206                     return node;
73207                 },
73208                 
73209                 /**
73210                  * Insert a node into this node
73211                  * @param {Number} index The zero-based index to insert the node at
73212                  * @param {Ext.data.Model} node The node to insert
73213                  * @return {Ext.data.Record} The record you just inserted
73214                  */    
73215                 insertChild: function(index, node) {
73216                     var sibling = this.childNodes[index];
73217                     if (sibling) {
73218                         return this.insertBefore(node, sibling);
73219                     }
73220                     else {
73221                         return this.appendChild(node);
73222                     }
73223                 },
73224
73225                 /**
73226                  * Removes this node from its parent
73227                  * @param {Boolean} destroy <tt>true</tt> to destroy the node upon removal. Defaults to <tt>false</tt>.
73228                  * @return {Node} this
73229                  */
73230                 remove : function(destroy, suppressEvents) {
73231                     var parentNode = this.parentNode;
73232
73233                     if (parentNode) {
73234                         parentNode.removeChild(this, destroy, suppressEvents, true);
73235                     }
73236                     return this;
73237                 },
73238
73239                 /**
73240                  * Removes all child nodes from this node.
73241                  * @param {Boolean} destroy <tt>true</tt> to destroy the node upon removal. Defaults to <tt>false</tt>.
73242                  * @return {Node} this
73243                  */
73244                 removeAll : function(destroy, suppressEvents) {
73245                     var cn = this.childNodes,
73246                         n;
73247
73248                     while ((n = cn[0])) {
73249                         this.removeChild(n, destroy, suppressEvents);
73250                     }
73251                     return this;
73252                 },
73253
73254                 /**
73255                  * Returns the child node at the specified index.
73256                  * @param {Number} index
73257                  * @return {Node}
73258                  */
73259                 getChildAt : function(index) {
73260                     return this.childNodes[index];
73261                 },
73262
73263                 /**
73264                  * Replaces one child node in this node with another.
73265                  * @param {Node} newChild The replacement node
73266                  * @param {Node} oldChild The node to replace
73267                  * @return {Node} The replaced node
73268                  */
73269                 replaceChild : function(newChild, oldChild, suppressEvents) {
73270                     var s = oldChild ? oldChild.nextSibling : null;
73271                     
73272                     this.removeChild(oldChild, suppressEvents);
73273                     this.insertBefore(newChild, s, suppressEvents);
73274                     return oldChild;
73275                 },
73276
73277                 /**
73278                  * Returns the index of a child node
73279                  * @param {Node} node
73280                  * @return {Number} The index of the node or -1 if it was not found
73281                  */
73282                 indexOf : function(child) {
73283                     return Ext.Array.indexOf(this.childNodes, child);
73284                 },
73285
73286                 /**
73287                  * Returns depth of this node (the root node has a depth of 0)
73288                  * @return {Number}
73289                  */
73290                 getDepth : function() {
73291                     return this.get('depth');
73292                 },
73293
73294                 /**
73295                  * Bubbles up the tree from this node, calling the specified function with each node. The arguments to the function
73296                  * will be the args provided or the current node. If the function returns false at any point,
73297                  * the bubble is stopped.
73298                  * @param {Function} fn The function to call
73299                  * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current Node.
73300                  * @param {Array} args (optional) The args to call the function with (default to passing the current Node)
73301                  */
73302                 bubble : function(fn, scope, args) {
73303                     var p = this;
73304                     while (p) {
73305                         if (fn.apply(scope || p, args || [p]) === false) {
73306                             break;
73307                         }
73308                         p = p.parentNode;
73309                     }
73310                 },
73311
73312                 cascade: function() {
73313                     if (Ext.isDefined(Ext.global.console)) {
73314                         Ext.global.console.warn('Ext.data.Node: cascade has been deprecated. Please use cascadeBy instead.');
73315                     }
73316                     return this.cascadeBy.apply(this, arguments);
73317                 },
73318
73319                 /**
73320                  * Cascades down the tree from this node, calling the specified function with each node. The arguments to the function
73321                  * will be the args provided or the current node. If the function returns false at any point,
73322                  * the cascade is stopped on that branch.
73323                  * @param {Function} fn The function to call
73324                  * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current Node.
73325                  * @param {Array} args (optional) The args to call the function with (default to passing the current Node)
73326                  */
73327                 cascadeBy : function(fn, scope, args) {
73328                     if (fn.apply(scope || this, args || [this]) !== false) {
73329                         var childNodes = this.childNodes,
73330                             length     = childNodes.length,
73331                             i;
73332
73333                         for (i = 0; i < length; i++) {
73334                             childNodes[i].cascadeBy(fn, scope, args);
73335                         }
73336                     }
73337                 },
73338
73339                 /**
73340                  * Interates the child nodes of this node, calling the specified function with each node. The arguments to the function
73341                  * will be the args provided or the current node. If the function returns false at any point,
73342                  * the iteration stops.
73343                  * @param {Function} fn The function to call
73344                  * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current Node in the iteration.
73345                  * @param {Array} args (optional) The args to call the function with (default to passing the current Node)
73346                  */
73347                 eachChild : function(fn, scope, args) {
73348                     var childNodes = this.childNodes,
73349                         length     = childNodes.length,
73350                         i;
73351
73352                     for (i = 0; i < length; i++) {
73353                         if (fn.apply(scope || this, args || [childNodes[i]]) === false) {
73354                             break;
73355                         }
73356                     }
73357                 },
73358
73359                 /**
73360                  * Finds the first child that has the attribute with the specified value.
73361                  * @param {String} attribute The attribute name
73362                  * @param {Mixed} value The value to search for
73363                  * @param {Boolean} deep (Optional) True to search through nodes deeper than the immediate children
73364                  * @return {Node} The found child or null if none was found
73365                  */
73366                 findChild : function(attribute, value, deep) {
73367                     return this.findChildBy(function() {
73368                         return this.get(attribute) == value;
73369                     }, null, deep);
73370                 },
73371
73372                 /**
73373                  * Finds the first child by a custom function. The child matches if the function passed returns <code>true</code>.
73374                  * @param {Function} fn A function which must return <code>true</code> if the passed Node is the required Node.
73375                  * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Node being tested.
73376                  * @param {Boolean} deep (Optional) True to search through nodes deeper than the immediate children
73377                  * @return {Node} The found child or null if none was found
73378                  */
73379                 findChildBy : function(fn, scope, deep) {
73380                     var cs = this.childNodes,
73381                         len = cs.length,
73382                         i = 0, n, res;
73383
73384                     for (; i < len; i++) {
73385                         n = cs[i];
73386                         if (fn.call(scope || n, n) === true) {
73387                             return n;
73388                         }
73389                         else if (deep) {
73390                             res = n.findChildBy(fn, scope, deep);
73391                             if (res !== null) {
73392                                 return res;
73393                             }
73394                         }
73395                     }
73396
73397                     return null;
73398                 },
73399
73400                 /**
73401                  * Returns true if this node is an ancestor (at any point) of the passed node.
73402                  * @param {Node} node
73403                  * @return {Boolean}
73404                  */
73405                 contains : function(node) {
73406                     return node.isAncestor(this);
73407                 },
73408
73409                 /**
73410                  * Returns true if the passed node is an ancestor (at any point) of this node.
73411                  * @param {Node} node
73412                  * @return {Boolean}
73413                  */
73414                 isAncestor : function(node) {
73415                     var p = this.parentNode;
73416                     while (p) {
73417                         if (p == node) {
73418                             return true;
73419                         }
73420                         p = p.parentNode;
73421                     }
73422                     return false;
73423                 },
73424
73425                 /**
73426                  * Sorts this nodes children using the supplied sort function.
73427                  * @param {Function} fn A function which, when passed two Nodes, returns -1, 0 or 1 depending upon required sort order.
73428                  * @param {Boolean} recursive Whether or not to apply this sort recursively
73429                  * @param {Boolean} suppressEvent Set to true to not fire a sort event.
73430                  */
73431                 sort : function(sortFn, recursive, suppressEvent) {
73432                     var cs  = this.childNodes,
73433                         ln = cs.length,
73434                         i, n;
73435                     
73436                     if (ln > 0) {
73437                         Ext.Array.sort(cs, sortFn);
73438                         for (i = 0; i < ln; i++) {
73439                             n = cs[i];
73440                             n.previousSibling = cs[i-1];
73441                             n.nextSibling = cs[i+1];
73442                         
73443                             if (i === 0) {
73444                                 this.setFirstChild(n);
73445                                 n.updateInfo();
73446                             }
73447                             if (i == ln - 1) {
73448                                 this.setLastChild(n);
73449                                 n.updateInfo();
73450                             }
73451                             if (recursive && !n.isLeaf()) {
73452                                 n.sort(sortFn, true, true);
73453                             }
73454                         }
73455                         
73456                         if (suppressEvent !== true) {
73457                             this.fireEvent('sort', this, cs);
73458                         }
73459                     }
73460                 },
73461                         
73462                 /**
73463                  * Returns true if this node is expaned
73464                  * @return {Boolean}
73465                  */        
73466                 isExpanded: function() {
73467                     return this.get('expanded');
73468                 },
73469                 
73470                 /**
73471                  * Returns true if this node is loaded
73472                  * @return {Boolean}
73473                  */ 
73474                 isLoaded: function() {
73475                     return this.get('loaded');
73476                 },
73477
73478                 /**
73479                  * Returns true if this node is loading
73480                  * @return {Boolean}
73481                  */ 
73482                 isLoading: function() {
73483                     return this.get('loading');
73484                 },
73485                                 
73486                 /**
73487                  * Returns true if this node is the root node
73488                  * @return {Boolean}
73489                  */ 
73490                 isRoot: function() {
73491                     return !this.parentNode;
73492                 },
73493                 
73494                 /**
73495                  * Returns true if this node is visible
73496                  * @return {Boolean}
73497                  */ 
73498                 isVisible: function() {
73499                     var parent = this.parentNode;
73500                     while (parent) {
73501                         if (!parent.isExpanded()) {
73502                             return false;
73503                         }
73504                         parent = parent.parentNode;
73505                     }
73506                     return true;
73507                 },
73508                 
73509                 /**
73510                  * Expand this node.
73511                  * @param {Function} recursive (Optional) True to recursively expand all the children
73512                  * @param {Function} callback (Optional) The function to execute once the expand completes
73513                  * @param {Object} scope (Optional) The scope to run the callback in
73514                  */
73515                 expand: function(recursive, callback, scope) {
73516                     var me = this;
73517
73518                     // all paths must call the callback (eventually) or things like
73519                     // selectPath fail
73520
73521                     // First we start by checking if this node is a parent
73522                     if (!me.isLeaf()) {
73523                         // Now we check if this record is already expanding or expanded
73524                         if (!me.isLoading() && !me.isExpanded()) {
73525                             // The TreeStore actually listens for the beforeexpand method and checks
73526                             // whether we have to asynchronously load the children from the server
73527                             // first. Thats why we pass a callback function to the event that the
73528                             // store can call once it has loaded and parsed all the children.
73529                             me.fireEvent('beforeexpand', me, function(records) {
73530                                 me.set('expanded', true); 
73531                                 me.fireEvent('expand', me, me.childNodes, false);
73532                                 
73533                                 // Call the expandChildren method if recursive was set to true 
73534                                 if (recursive) {
73535                                     me.expandChildren(true, callback, scope);
73536                                 }
73537                                 else {
73538                                     Ext.callback(callback, scope || me, [me.childNodes]);                                
73539                                 }
73540                             }, me);                            
73541                         }
73542                         // If it is is already expanded but we want to recursively expand then call expandChildren
73543                         else if (recursive) {
73544                             me.expandChildren(true, callback, scope);
73545                         }
73546                         else {
73547                             Ext.callback(callback, scope || me, [me.childNodes]);
73548                         }
73549
73550                         // TODO - if the node isLoading, we probably need to defer the
73551                         // callback until it is loaded (e.g., selectPath would need us
73552                         // to not make the callback until the childNodes exist).
73553                     }
73554                     // If it's not then we fire the callback right away
73555                     else {
73556                         Ext.callback(callback, scope || me); // leaf = no childNodes
73557                     }
73558                 },
73559                 
73560                 /**
73561                  * Expand all the children of this node.
73562                  * @param {Function} recursive (Optional) True to recursively expand all the children
73563                  * @param {Function} callback (Optional) The function to execute once all the children are expanded
73564                  * @param {Object} scope (Optional) The scope to run the callback in
73565                  */
73566                 expandChildren: function(recursive, callback, scope) {
73567                     var me = this,
73568                         i = 0,
73569                         nodes = me.childNodes,
73570                         ln = nodes.length,
73571                         node,
73572                         expanding = 0;
73573
73574                     for (; i < ln; ++i) {
73575                         node = nodes[i];
73576                         if (!node.isLeaf() && !node.isExpanded()) {
73577                             expanding++;
73578                             nodes[i].expand(recursive, function () {
73579                                 expanding--;
73580                                 if (callback && !expanding) {
73581                                     Ext.callback(callback, scope || me, me.childNodes); 
73582                                 }
73583                             });                            
73584                         }
73585                     }
73586                     
73587                     if (!expanding && callback) {
73588                         Ext.callback(callback, scope || me, me.childNodes);
73589                     }
73590                 },
73591
73592                 /**
73593                  * Collapse this node.
73594                  * @param {Function} recursive (Optional) True to recursively collapse all the children
73595                  * @param {Function} callback (Optional) The function to execute once the collapse completes
73596                  * @param {Object} scope (Optional) The scope to run the callback in
73597                  */
73598                 collapse: function(recursive, callback, scope) {
73599                     var me = this;
73600
73601                     // First we start by checking if this node is a parent
73602                     if (!me.isLeaf()) {
73603                         // Now we check if this record is already collapsing or collapsed
73604                         if (!me.collapsing && me.isExpanded()) {
73605                             me.fireEvent('beforecollapse', me, function(records) {
73606                                 me.set('expanded', false); 
73607                                 me.fireEvent('collapse', me, me.childNodes, false);
73608                                 
73609                                 // Call the collapseChildren method if recursive was set to true 
73610                                 if (recursive) {
73611                                     me.collapseChildren(true, callback, scope);
73612                                 }
73613                                 else {
73614                                     Ext.callback(callback, scope || me, [me.childNodes]);                                
73615                                 }
73616                             }, me);                            
73617                         }
73618                         // If it is is already collapsed but we want to recursively collapse then call collapseChildren
73619                         else if (recursive) {
73620                             me.collapseChildren(true, callback, scope);
73621                         }
73622                     }
73623                     // If it's not then we fire the callback right away
73624                     else {
73625                         Ext.callback(callback, scope || me, me.childNodes); 
73626                     }
73627                 },
73628                 
73629                 /**
73630                  * Collapse all the children of this node.
73631                  * @param {Function} recursive (Optional) True to recursively collapse all the children
73632                  * @param {Function} callback (Optional) The function to execute once all the children are collapsed
73633                  * @param {Object} scope (Optional) The scope to run the callback in
73634                  */
73635                 collapseChildren: function(recursive, callback, scope) {
73636                     var me = this,
73637                         i = 0,
73638                         nodes = me.childNodes,
73639                         ln = nodes.length,
73640                         node,
73641                         collapsing = 0;
73642
73643                     for (; i < ln; ++i) {
73644                         node = nodes[i];
73645                         if (!node.isLeaf() && node.isExpanded()) {
73646                             collapsing++;
73647                             nodes[i].collapse(recursive, function () {
73648                                 collapsing--;
73649                                 if (callback && !collapsing) {
73650                                     Ext.callback(callback, scope || me, me.childNodes); 
73651                                 }
73652                             });                            
73653                         }
73654                     }
73655                     
73656                     if (!collapsing && callback) {
73657                         Ext.callback(callback, scope || me, me.childNodes);
73658                     }
73659                 }
73660             };
73661         }
73662     }
73663 });
73664 /**
73665  * @class Ext.data.NodeStore
73666  * @extends Ext.data.AbstractStore
73667  * Node Store
73668  * @ignore
73669  */
73670 Ext.define('Ext.data.NodeStore', {
73671     extend: 'Ext.data.Store',
73672     alias: 'store.node',
73673     requires: ['Ext.data.NodeInterface'],
73674     
73675     /**
73676      * @cfg {Ext.data.Record} node The Record you want to bind this Store to. Note that
73677      * this record will be decorated with the Ext.data.NodeInterface if this is not the
73678      * case yet.
73679      */
73680     node: null,
73681     
73682     /**
73683      * @cfg {Boolean} recursive Set this to true if you want this NodeStore to represent
73684      * all the descendents of the node in its flat data collection. This is useful for
73685      * rendering a tree structure to a DataView and is being used internally by
73686      * the TreeView. Any records that are moved, removed, inserted or appended to the
73687      * node at any depth below the node this store is bound to will be automatically
73688      * updated in this Store's internal flat data structure.
73689      */
73690     recursive: false,
73691     
73692     /** 
73693      * @cfg {Boolean} rootVisible <tt>false</tt> to not include the root node in this Stores collection (defaults to <tt>true</tt>)
73694      */    
73695     rootVisible: false,
73696     
73697     constructor: function(config) {
73698         var me = this,
73699             node;
73700             
73701         config = config || {};
73702         Ext.apply(me, config);
73703         
73704         if (Ext.isDefined(me.proxy)) {
73705             Ext.Error.raise("A NodeStore cannot be bound to a proxy. Instead bind it to a record " +
73706                             "decorated with the NodeInterface by setting the node config.");
73707         }
73708
73709         config.proxy = {type: 'proxy'};
73710         me.callParent([config]);
73711
73712         me.addEvents('expand', 'collapse', 'beforeexpand', 'beforecollapse');
73713         
73714         node = me.node;
73715         if (node) {
73716             me.node = null;
73717             me.setNode(node);
73718         }
73719     },
73720     
73721     setNode: function(node) {
73722         var me = this;
73723         
73724         if (me.node && me.node != node) {
73725             // We want to unbind our listeners on the old node
73726             me.mun(me.node, {
73727                 expand: me.onNodeExpand,
73728                 collapse: me.onNodeCollapse,
73729                 append: me.onNodeAppend,
73730                 insert: me.onNodeInsert,
73731                 remove: me.onNodeRemove,
73732                 sort: me.onNodeSort,
73733                 scope: me
73734             });
73735             me.node = null;
73736         }
73737         
73738         if (node) {
73739             Ext.data.NodeInterface.decorate(node);
73740             me.removeAll();
73741             if (me.rootVisible) {
73742                 me.add(node);
73743             }
73744             me.mon(node, {
73745                 expand: me.onNodeExpand,
73746                 collapse: me.onNodeCollapse,
73747                 append: me.onNodeAppend,
73748                 insert: me.onNodeInsert,
73749                 remove: me.onNodeRemove,
73750                 sort: me.onNodeSort,
73751                 scope: me
73752             });
73753             me.node = node;
73754             if (node.isExpanded() && node.isLoaded()) {
73755                 me.onNodeExpand(node, node.childNodes, true);
73756             }
73757         }
73758     },
73759     
73760     onNodeSort: function(node, childNodes) {
73761         var me = this;
73762         
73763         if ((me.indexOf(node) !== -1 || (node === me.node && !me.rootVisible) && node.isExpanded())) {
73764             me.onNodeCollapse(node, childNodes, true);
73765             me.onNodeExpand(node, childNodes, true);
73766         }
73767     },
73768     
73769     onNodeExpand: function(parent, records, suppressEvent) {
73770         var me = this,
73771             insertIndex = me.indexOf(parent) + 1,
73772             ln = records ? records.length : 0,
73773             i, record;
73774             
73775         if (!me.recursive && parent !== me.node) {
73776             return;
73777         }
73778         
73779         if (!me.isVisible(parent)) {
73780             return;
73781         }
73782
73783         if (!suppressEvent && me.fireEvent('beforeexpand', parent, records, insertIndex) === false) {
73784             return;
73785         }
73786         
73787         if (ln) {
73788             me.insert(insertIndex, records);
73789             for (i = 0; i < ln; i++) {
73790                 record = records[i];
73791                 if (record.isExpanded()) {
73792                     if (record.isLoaded()) {
73793                         // Take a shortcut                        
73794                         me.onNodeExpand(record, record.childNodes, true);
73795                     }
73796                     else {
73797                         record.set('expanded', false);
73798                         record.expand();
73799                     }
73800                 }
73801             }
73802         }
73803
73804         if (!suppressEvent) {
73805             me.fireEvent('expand', parent, records);
73806         }
73807     },
73808
73809     onNodeCollapse: function(parent, records, suppressEvent) {
73810         var me = this,
73811             ln = records.length,
73812             collapseIndex = me.indexOf(parent) + 1,
73813             i, record;
73814             
73815         if (!me.recursive && parent !== me.node) {
73816             return;
73817         }
73818         
73819         if (!suppressEvent && me.fireEvent('beforecollapse', parent, records, collapseIndex) === false) {
73820             return;
73821         }
73822
73823         for (i = 0; i < ln; i++) {
73824             record = records[i];
73825             me.remove(record);
73826             if (record.isExpanded()) {
73827                 me.onNodeCollapse(record, record.childNodes, true);
73828             }
73829         }
73830         
73831         if (!suppressEvent) {
73832             me.fireEvent('collapse', parent, records, collapseIndex);
73833         }
73834     },
73835     
73836     onNodeAppend: function(parent, node, index) {
73837         var me = this,
73838             refNode, sibling;
73839
73840         if (me.isVisible(node)) {
73841             if (index === 0) {
73842                 refNode = parent;
73843             } else {
73844                 sibling = node.previousSibling;
73845                 while (sibling.isExpanded() && sibling.lastChild) {
73846                     sibling = sibling.lastChild;
73847                 }
73848                 refNode = sibling;
73849             }
73850             me.insert(me.indexOf(refNode) + 1, node);
73851             if (!node.isLeaf() && node.isExpanded()) {
73852                 if (node.isLoaded()) {
73853                     // Take a shortcut                        
73854                     me.onNodeExpand(node, node.childNodes, true);
73855                 }
73856                 else {
73857                     node.set('expanded', false);
73858                     node.expand();
73859                 }
73860             }
73861         } 
73862     },
73863     
73864     onNodeInsert: function(parent, node, refNode) {
73865         var me = this,
73866             index = this.indexOf(refNode);
73867             
73868         if (index != -1 && me.isVisible(node)) {
73869             me.insert(index, node);
73870             if (!node.isLeaf() && node.isExpanded()) {
73871                 if (node.isLoaded()) {
73872                     // Take a shortcut                        
73873                     me.onNodeExpand(node, node.childNodes, true);
73874                 }
73875                 else {
73876                     node.set('expanded', false);
73877                     node.expand();
73878                 }
73879             }
73880         }
73881     },
73882     
73883     onNodeRemove: function(parent, node, index) {
73884         var me = this;
73885         if (me.indexOf(node) != -1) {
73886             if (!node.isLeaf() && node.isExpanded()) {
73887                 me.onNodeCollapse(node, node.childNodes, true);
73888             }            
73889             me.remove(node);
73890         }
73891     },
73892     
73893     isVisible: function(node) {
73894         var parent = node.parentNode;
73895         while (parent) {
73896             if (parent === this.node && !this.rootVisible && parent.isExpanded()) {
73897                 return true;
73898             }
73899             
73900             if (this.indexOf(parent) === -1 || !parent.isExpanded()) {
73901                 return false;
73902             }
73903             
73904             parent = parent.parentNode;
73905         }
73906         return true;
73907     }
73908 });
73909 /**
73910  * @author Ed Spencer
73911  * @class Ext.data.Request
73912  * @extends Object
73913  * 
73914  * <p>Simple class that represents a Request that will be made by any {@link Ext.data.proxy.Server} subclass.
73915  * All this class does is standardize the representation of a Request as used by any ServerProxy subclass,
73916  * it does not contain any actual logic or perform the request itself.</p>
73917  * 
73918  * @constructor
73919  * @param {Object} config Optional config object
73920  */
73921 Ext.define('Ext.data.Request', {
73922     /**
73923      * @cfg {String} action The name of the action this Request represents. Usually one of 'create', 'read', 'update' or 'destroy'
73924      */
73925     action: undefined,
73926     
73927     /**
73928      * @cfg {Object} params HTTP request params. The Proxy and its Writer have access to and can modify this object.
73929      */
73930     params: undefined,
73931     
73932     /**
73933      * @cfg {String} method The HTTP method to use on this Request (defaults to 'GET'). Should be one of 'GET', 'POST', 'PUT' or 'DELETE'
73934      */
73935     method: 'GET',
73936     
73937     /**
73938      * @cfg {String} url The url to access on this Request
73939      */
73940     url: undefined,
73941
73942     constructor: function(config) {
73943         Ext.apply(this, config);
73944     }
73945 });
73946 /**
73947  * @class Ext.data.Tree
73948  * 
73949  * This class is used as a container for a series of nodes. The nodes themselves maintain
73950  * the relationship between parent/child. The tree itself acts as a manager. It gives functionality
73951  * to retrieve a node by its identifier: {@link #getNodeById}. 
73952  *
73953  * The tree also relays events from any of it's child nodes, allowing them to be handled in a 
73954  * centralized fashion. In general this class is not used directly, rather used internally 
73955  * by other parts of the framework.
73956  *
73957  * @constructor
73958  * @param {Node} root (optional) The root node
73959  */
73960 Ext.define('Ext.data.Tree', {
73961     alias: 'data.tree',
73962     
73963     mixins: {
73964         observable: "Ext.util.Observable"
73965     },
73966
73967     /**
73968      * The root node for this tree
73969      * @type Node
73970      */
73971     root: null,
73972         
73973     constructor: function(root) {
73974         var me = this;
73975         
73976         me.nodeHash = {};
73977
73978         me.mixins.observable.constructor.call(me);
73979                         
73980         if (root) {
73981             me.setRootNode(root);
73982         }
73983     },
73984
73985     /**
73986      * Returns the root node for this tree.
73987      * @return {Ext.data.NodeInterface}
73988      */
73989     getRootNode : function() {
73990         return this.root;
73991     },
73992
73993     /**
73994      * Sets the root node for this tree.
73995      * @param {Ext.data.NodeInterface} node
73996      * @return {Ext.data.NodeInterface} The root node
73997      */
73998     setRootNode : function(node) {
73999         var me = this;
74000         
74001         me.root = node;
74002         Ext.data.NodeInterface.decorate(node);
74003         
74004         if (me.fireEvent('beforeappend', null, node) !== false) {
74005             node.set('root', true);
74006             node.updateInfo();
74007             
74008             me.relayEvents(node, [
74009                 /**
74010                  * @event append
74011                  * Fires when a new child node is appended to a node in this tree.
74012                  * @param {Tree} tree The owner tree
74013                  * @param {Node} parent The parent node
74014                  * @param {Node} node The newly appended node
74015                  * @param {Number} index The index of the newly appended node
74016                  */
74017                 "append",
74018
74019                 /**
74020                  * @event remove
74021                  * Fires when a child node is removed from a node in this tree.
74022                  * @param {Tree} tree The owner tree
74023                  * @param {Node} parent The parent node
74024                  * @param {Node} node The child node removed
74025                  */
74026                 "remove",
74027
74028                 /**
74029                  * @event move
74030                  * Fires when a node is moved to a new location in the tree
74031                  * @param {Tree} tree The owner tree
74032                  * @param {Node} node The node moved
74033                  * @param {Node} oldParent The old parent of this node
74034                  * @param {Node} newParent The new parent of this node
74035                  * @param {Number} index The index it was moved to
74036                  */
74037                 "move",
74038
74039                 /**
74040                  * @event insert
74041                  * Fires when a new child node is inserted in a node in this tree.
74042                  * @param {Tree} tree The owner tree
74043                  * @param {Node} parent The parent node
74044                  * @param {Node} node The child node inserted
74045                  * @param {Node} refNode The child node the node was inserted before
74046                  */
74047                 "insert",
74048
74049                 /**
74050                  * @event beforeappend
74051                  * Fires before a new child is appended to a node in this tree, return false to cancel the append.
74052                  * @param {Tree} tree The owner tree
74053                  * @param {Node} parent The parent node
74054                  * @param {Node} node The child node to be appended
74055                  */
74056                 "beforeappend",
74057
74058                 /**
74059                  * @event beforeremove
74060                  * Fires before a child is removed from a node in this tree, return false to cancel the remove.
74061                  * @param {Tree} tree The owner tree
74062                  * @param {Node} parent The parent node
74063                  * @param {Node} node The child node to be removed
74064                  */
74065                 "beforeremove",
74066
74067                 /**
74068                  * @event beforemove
74069                  * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
74070                  * @param {Tree} tree The owner tree
74071                  * @param {Node} node The node being moved
74072                  * @param {Node} oldParent The parent of the node
74073                  * @param {Node} newParent The new parent the node is moving to
74074                  * @param {Number} index The index it is being moved to
74075                  */
74076                 "beforemove",
74077
74078                 /**
74079                  * @event beforeinsert
74080                  * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
74081                  * @param {Tree} tree The owner tree
74082                  * @param {Node} parent The parent node
74083                  * @param {Node} node The child node to be inserted
74084                  * @param {Node} refNode The child node the node is being inserted before
74085                  */
74086                 "beforeinsert",
74087
74088                  /**
74089                   * @event expand
74090                   * Fires when this node is expanded.
74091                   * @param {Node} this The expanding node
74092                   */
74093                  "expand",
74094
74095                  /**
74096                   * @event collapse
74097                   * Fires when this node is collapsed.
74098                   * @param {Node} this The collapsing node
74099                   */
74100                  "collapse",
74101
74102                  /**
74103                   * @event beforeexpand
74104                   * Fires before this node is expanded.
74105                   * @param {Node} this The expanding node
74106                   */
74107                  "beforeexpand",
74108
74109                  /**
74110                   * @event beforecollapse
74111                   * Fires before this node is collapsed.
74112                   * @param {Node} this The collapsing node
74113                   */
74114                  "beforecollapse" ,
74115
74116                  /**
74117                   * @event rootchange
74118                   * Fires whenever the root node is changed in the tree.
74119                   * @param {Ext.data.Model} root The new root
74120                   */
74121                  "rootchange"
74122             ]);
74123             
74124             node.on({
74125                 scope: me,
74126                 insert: me.onNodeInsert,
74127                 append: me.onNodeAppend,
74128                 remove: me.onNodeRemove
74129             });
74130
74131             me.registerNode(node);        
74132             me.fireEvent('append', null, node);
74133             me.fireEvent('rootchange', node);
74134         }
74135             
74136         return node;
74137     },
74138     
74139     /**
74140      * Flattens all the nodes in the tree into an array.
74141      * @private
74142      * @return {Array} The flattened nodes.
74143      */
74144     flatten: function(){
74145         var nodes = [],
74146             hash = this.nodeHash,
74147             key;
74148             
74149         for (key in hash) {
74150             if (hash.hasOwnProperty(key)) {
74151                 nodes.push(hash[key]);
74152             }
74153         }
74154         return nodes;
74155     },
74156     
74157     /**
74158      * Fired when a node is inserted into the root or one of it's children
74159      * @private
74160      * @param {Ext.data.NodeInterface} parent The parent node
74161      * @param {Ext.data.NodeInterface} node The inserted node
74162      */
74163     onNodeInsert: function(parent, node) {
74164         this.registerNode(node);
74165     },
74166     
74167     /**
74168      * Fired when a node is appended into the root or one of it's children
74169      * @private
74170      * @param {Ext.data.NodeInterface} parent The parent node
74171      * @param {Ext.data.NodeInterface} node The appended node
74172      */
74173     onNodeAppend: function(parent, node) {
74174         this.registerNode(node);
74175     },
74176     
74177     /**
74178      * Fired when a node is removed from the root or one of it's children
74179      * @private
74180      * @param {Ext.data.NodeInterface} parent The parent node
74181      * @param {Ext.data.NodeInterface} node The removed node
74182      */
74183     onNodeRemove: function(parent, node) {
74184         this.unregisterNode(node);
74185     },
74186
74187     /**
74188      * Gets a node in this tree by its id.
74189      * @param {String} id
74190      * @return {Ext.data.NodeInterface} The match node.
74191      */
74192     getNodeById : function(id) {
74193         return this.nodeHash[id];
74194     },
74195
74196     /**
74197      * Registers a node with the tree
74198      * @private
74199      * @param {Ext.data.NodeInterface} The node to register
74200      */
74201     registerNode : function(node) {
74202         this.nodeHash[node.getId() || node.internalId] = node;
74203     },
74204
74205     /**
74206      * Unregisters a node with the tree
74207      * @private
74208      * @param {Ext.data.NodeInterface} The node to unregister
74209      */
74210     unregisterNode : function(node) {
74211         delete this.nodeHash[node.getId() || node.internalId];
74212     },
74213     
74214     /**
74215      * Sorts this tree
74216      * @private
74217      * @param {Function} sorterFn The function to use for sorting
74218      * @param {Boolean} recursive True to perform recursive sorting
74219      */
74220     sort: function(sorterFn, recursive) {
74221         this.getRootNode().sort(sorterFn, recursive);
74222     },
74223     
74224      /**
74225      * Filters this tree
74226      * @private
74227      * @param {Function} sorterFn The function to use for filtering
74228      * @param {Boolean} recursive True to perform recursive filtering
74229      */
74230     filter: function(filters, recursive) {
74231         this.getRootNode().filter(filters, recursive);
74232     }
74233 });
74234 /**
74235  * @class Ext.data.TreeStore
74236  * @extends Ext.data.AbstractStore
74237  * 
74238  * The TreeStore is a store implementation that is backed by by an {@link Ext.data.Tree}.
74239  * It provides convenience methods for loading nodes, as well as the ability to use
74240  * the hierarchical tree structure combined with a store. This class is generally used
74241  * in conjunction with {@link Ext.tree.Panel}. This class also relays many events from
74242  * the Tree for convenience.
74243  * 
74244  * ## Using Models
74245  * If no Model is specified, an implicit model will be created that implements {@link Ext.data.NodeInterface}.
74246  * The standard Tree fields will also be copied onto the Model for maintaining their state.
74247  * 
74248  * ## Reading Nested Data
74249  * For the tree to read nested data, the {@link Ext.data.Reader} must be configured with a root property,
74250  * so the reader can find nested data for each node. If a root is not specified, it will default to
74251  * 'children'.
74252  */
74253 Ext.define('Ext.data.TreeStore', {
74254     extend: 'Ext.data.AbstractStore',
74255     alias: 'store.tree',
74256     requires: ['Ext.data.Tree', 'Ext.data.NodeInterface', 'Ext.data.NodeStore'],
74257
74258     /**
74259      * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing
74260      * child nodes before loading.
74261      */
74262     clearOnLoad : true,
74263
74264     /**
74265      * @cfg {String} nodeParam The name of the parameter sent to the server which contains
74266      * the identifier of the node. Defaults to <tt>'node'</tt>.
74267      */
74268     nodeParam: 'node',
74269
74270     /**
74271      * @cfg {String} defaultRootId
74272      * The default root id. Defaults to 'root'
74273      */
74274     defaultRootId: 'root',
74275     
74276     /**
74277      * @cfg {String} defaultRootProperty
74278      * The root property to specify on the reader if one is not explicitly defined.
74279      */
74280     defaultRootProperty: 'children',
74281
74282     /**
74283      * @cfg {Boolean} folderSort Set to true to automatically prepend a leaf sorter (defaults to <tt>undefined</tt>)
74284      */
74285     folderSort: false,
74286     
74287     constructor: function(config) {
74288         var me = this, 
74289             root,
74290             fields;
74291             
74292         
74293         config = Ext.apply({}, config);
74294         
74295         /**
74296          * If we have no fields declare for the store, add some defaults.
74297          * These will be ignored if a model is explicitly specified.
74298          */
74299         fields = config.fields || me.fields;
74300         if (!fields) {
74301             config.fields = [{name: 'text', type: 'string'}];
74302         }
74303
74304         me.callParent([config]);
74305         
74306         // We create our data tree.
74307         me.tree = Ext.create('Ext.data.Tree');
74308         
74309         me.tree.on({
74310             scope: me,
74311             remove: me.onNodeRemove,
74312             beforeexpand: me.onBeforeNodeExpand,
74313             beforecollapse: me.onBeforeNodeCollapse,
74314             append: me.onNodeAdded,
74315             insert: me.onNodeAdded
74316         });
74317
74318         me.onBeforeSort();
74319                 
74320         root = me.root;
74321         if (root) {
74322             delete me.root;
74323             me.setRootNode(root);            
74324         }
74325
74326         me.relayEvents(me.tree, [
74327             /**
74328              * @event append
74329              * Fires when a new child node is appended to a node in this store's tree.
74330              * @param {Tree} tree The owner tree
74331              * @param {Node} parent The parent node
74332              * @param {Node} node The newly appended node
74333              * @param {Number} index The index of the newly appended node
74334              */
74335             "append",
74336             
74337             /**
74338              * @event remove
74339              * Fires when a child node is removed from a node in this store's tree.
74340              * @param {Tree} tree The owner tree
74341              * @param {Node} parent The parent node
74342              * @param {Node} node The child node removed
74343              */
74344             "remove",
74345             
74346             /**
74347              * @event move
74348              * Fires when a node is moved to a new location in the store's tree
74349              * @param {Tree} tree The owner tree
74350              * @param {Node} node The node moved
74351              * @param {Node} oldParent The old parent of this node
74352              * @param {Node} newParent The new parent of this node
74353              * @param {Number} index The index it was moved to
74354              */
74355             "move",
74356             
74357             /**
74358              * @event insert
74359              * Fires when a new child node is inserted in a node in this store's tree.
74360              * @param {Tree} tree The owner tree
74361              * @param {Node} parent The parent node
74362              * @param {Node} node The child node inserted
74363              * @param {Node} refNode The child node the node was inserted before
74364              */
74365             "insert",
74366             
74367             /**
74368              * @event beforeappend
74369              * Fires before a new child is appended to a node in this store's tree, return false to cancel the append.
74370              * @param {Tree} tree The owner tree
74371              * @param {Node} parent The parent node
74372              * @param {Node} node The child node to be appended
74373              */
74374             "beforeappend",
74375             
74376             /**
74377              * @event beforeremove
74378              * Fires before a child is removed from a node in this store's tree, return false to cancel the remove.
74379              * @param {Tree} tree The owner tree
74380              * @param {Node} parent The parent node
74381              * @param {Node} node The child node to be removed
74382              */
74383             "beforeremove",
74384             
74385             /**
74386              * @event beforemove
74387              * Fires before a node is moved to a new location in the store's tree. Return false to cancel the move.
74388              * @param {Tree} tree The owner tree
74389              * @param {Node} node The node being moved
74390              * @param {Node} oldParent The parent of the node
74391              * @param {Node} newParent The new parent the node is moving to
74392              * @param {Number} index The index it is being moved to
74393              */
74394             "beforemove",
74395             
74396             /**
74397              * @event beforeinsert
74398              * Fires before a new child is inserted in a node in this store's tree, return false to cancel the insert.
74399              * @param {Tree} tree The owner tree
74400              * @param {Node} parent The parent node
74401              * @param {Node} node The child node to be inserted
74402              * @param {Node} refNode The child node the node is being inserted before
74403              */
74404             "beforeinsert",
74405              
74406              /**
74407               * @event expand
74408               * Fires when this node is expanded.
74409               * @param {Node} this The expanding node
74410               */
74411              "expand",
74412              
74413              /**
74414               * @event collapse
74415               * Fires when this node is collapsed.
74416               * @param {Node} this The collapsing node
74417               */
74418              "collapse",
74419              
74420              /**
74421               * @event beforeexpand
74422               * Fires before this node is expanded.
74423               * @param {Node} this The expanding node
74424               */
74425              "beforeexpand",
74426              
74427              /**
74428               * @event beforecollapse
74429               * Fires before this node is collapsed.
74430               * @param {Node} this The collapsing node
74431               */
74432              "beforecollapse",
74433
74434              /**
74435               * @event sort
74436               * Fires when this TreeStore is sorted.
74437               * @param {Node} node The node that is sorted.
74438               */             
74439              "sort",
74440              
74441              /**
74442               * @event rootchange
74443               * Fires whenever the root node is changed in the tree.
74444               * @param {Ext.data.Model} root The new root
74445               */
74446              "rootchange"
74447         ]);
74448         
74449         me.addEvents(
74450             /**
74451              * @event rootchange
74452              * Fires when the root node on this TreeStore is changed.
74453              * @param {Ext.data.TreeStore} store This TreeStore
74454              * @param {Node} The new root node.
74455              */
74456             'rootchange'
74457         );
74458         
74459         if (Ext.isDefined(me.nodeParameter)) {
74460             if (Ext.isDefined(Ext.global.console)) {
74461                 Ext.global.console.warn('Ext.data.TreeStore: nodeParameter has been deprecated. Please use nodeParam instead.');
74462             }
74463             me.nodeParam = me.nodeParameter;
74464             delete me.nodeParameter;
74465         }
74466     },
74467     
74468     // inherit docs
74469     setProxy: function(proxy) {
74470         var reader,
74471             needsRoot;
74472         
74473         if (proxy instanceof Ext.data.proxy.Proxy) {
74474             // proxy instance, check if a root was set
74475             needsRoot = Ext.isEmpty(proxy.getReader().root);
74476         } else if (Ext.isString(proxy)) {
74477             // string type, means a reader can't be set
74478             needsRoot = true;
74479         } else {
74480             // object, check if a reader and a root were specified.
74481             reader = proxy.reader;
74482             needsRoot = !(reader && !Ext.isEmpty(reader.root));
74483         }
74484         proxy = this.callParent(arguments);
74485         if (needsRoot) {
74486             reader = proxy.getReader();
74487             reader.root = this.defaultRootProperty;
74488             // force rebuild
74489             reader.buildExtractors(true);
74490         }
74491     },
74492     
74493     // inherit docs
74494     onBeforeSort: function() {
74495         if (this.folderSort) {
74496             this.sort({
74497                 property: 'leaf',
74498                 direction: 'ASC'
74499             }, 'prepend', false);    
74500         }
74501     },
74502     
74503     /**
74504      * Called before a node is expanded.
74505      * @private
74506      * @param {Ext.data.NodeInterface} node The node being expanded.
74507      * @param {Function} callback The function to run after the expand finishes
74508      * @param {Object} scope The scope in which to run the callback function
74509      */
74510     onBeforeNodeExpand: function(node, callback, scope) {
74511         if (node.isLoaded()) {
74512             Ext.callback(callback, scope || node, [node.childNodes]);
74513         }
74514         else if (node.isLoading()) {
74515             this.on('load', function() {
74516                 Ext.callback(callback, scope || node, [node.childNodes]);
74517             }, this, {single: true});
74518         }
74519         else {
74520             this.read({
74521                 node: node,
74522                 callback: function() {
74523                     Ext.callback(callback, scope || node, [node.childNodes]);
74524                 }
74525             });            
74526         }
74527     },
74528     
74529     //inherit docs
74530     getNewRecords: function() {
74531         return Ext.Array.filter(this.tree.flatten(), this.filterNew);
74532     },
74533
74534     //inherit docs
74535     getUpdatedRecords: function() {
74536         return Ext.Array.filter(this.tree.flatten(), this.filterUpdated);
74537     },
74538     
74539     /**
74540      * Called before a node is collapsed.
74541      * @private
74542      * @param {Ext.data.NodeInterface} node The node being collapsed.
74543      * @param {Function} callback The function to run after the collapse finishes
74544      * @param {Object} scope The scope in which to run the callback function
74545      */
74546     onBeforeNodeCollapse: function(node, callback, scope) {
74547         callback.call(scope || node, node.childNodes);
74548     },
74549     
74550     onNodeRemove: function(parent, node) {
74551         var removed = this.removed;
74552         
74553         if (!node.isReplace && Ext.Array.indexOf(removed, node) == -1) {
74554             removed.push(node);
74555         }
74556     },
74557     
74558     onNodeAdded: function(parent, node) {
74559         var proxy = this.getProxy(),
74560             reader = proxy.getReader(),
74561             data = node.raw || node.data,
74562             dataRoot, children;
74563             
74564         Ext.Array.remove(this.removed, node); 
74565         
74566         if (!node.isLeaf() && !node.isLoaded()) {
74567             dataRoot = reader.getRoot(data);
74568             if (dataRoot) {
74569                 this.fillNode(node, reader.extractData(dataRoot));
74570                 delete data[reader.root];
74571             }
74572         }
74573     },
74574         
74575     /**
74576      * Sets the root node for this store
74577      * @param {Ext.data.Model/Ext.data.NodeInterface} root
74578      * @return {Ext.data.NodeInterface} The new root
74579      */
74580     setRootNode: function(root) {
74581         var me = this;
74582
74583         root = root || {};        
74584         if (!root.isNode) {
74585             // create a default rootNode and create internal data struct.        
74586             Ext.applyIf(root, {
74587                 id: me.defaultRootId,
74588                 text: 'Root',
74589                 allowDrag: false
74590             });
74591             root = Ext.ModelManager.create(root, me.model);
74592         }
74593         Ext.data.NodeInterface.decorate(root);
74594
74595         // Because we have decorated the model with new fields,
74596         // we need to build new extactor functions on the reader.
74597         me.getProxy().getReader().buildExtractors(true);
74598         
74599         // When we add the root to the tree, it will automaticaly get the NodeInterface
74600         me.tree.setRootNode(root);
74601         
74602         // If the user has set expanded: true on the root, we want to call the expand function
74603         if (!root.isLoaded() && root.isExpanded()) {
74604             me.load({
74605                 node: root
74606             });
74607         }
74608         
74609         return root;
74610     },
74611         
74612     /**
74613      * Returns the root node for this tree.
74614      * @return {Ext.data.NodeInterface}
74615      */
74616     getRootNode: function() {
74617         return this.tree.getRootNode();
74618     },
74619
74620     /**
74621      * Returns the record node by id
74622      * @return {Ext.data.NodeInterface}
74623      */
74624     getNodeById: function(id) {
74625         return this.tree.getNodeById(id);
74626     },
74627
74628     /**
74629      * Loads the Store using its configured {@link #proxy}.
74630      * @param {Object} options Optional config object. This is passed into the {@link Ext.data.Operation Operation}
74631      * object that is created and then sent to the proxy's {@link Ext.data.proxy.Proxy#read} function.
74632      * The options can also contain a node, which indicates which node is to be loaded. If not specified, it will
74633      * default to the root node.
74634      */
74635     load: function(options) {
74636         options = options || {};
74637         options.params = options.params || {};
74638         
74639         var me = this,
74640             node = options.node || me.tree.getRootNode(),
74641             root;
74642             
74643         // If there is not a node it means the user hasnt defined a rootnode yet. In this case lets just
74644         // create one for them.
74645         if (!node) {
74646             node = me.setRootNode({
74647                 expanded: true
74648             });
74649         }
74650         
74651         if (me.clearOnLoad) {
74652             node.removeAll();
74653         }
74654         
74655         Ext.applyIf(options, {
74656             node: node
74657         });
74658         options.params[me.nodeParam] = node ? node.getId() : 'root';
74659         
74660         if (node) {
74661             node.set('loading', true);
74662         }
74663         
74664         return me.callParent([options]);
74665     },
74666         
74667
74668     /**
74669      * Fills a node with a series of child records.
74670      * @private
74671      * @param {Ext.data.NodeInterface} node The node to fill
74672      * @param {Array} records The records to add
74673      */
74674     fillNode: function(node, records) {
74675         var me = this,
74676             ln = records ? records.length : 0,
74677             i = 0, sortCollection;
74678
74679         if (ln && me.sortOnLoad && !me.remoteSort && me.sorters && me.sorters.items) {
74680             sortCollection = Ext.create('Ext.util.MixedCollection');
74681             sortCollection.addAll(records);
74682             sortCollection.sort(me.sorters.items);
74683             records = sortCollection.items;
74684         }
74685         
74686         node.set('loaded', true);
74687         for (; i < ln; i++) {
74688             node.appendChild(records[i], undefined, true);
74689         }
74690         
74691         return records;
74692     },
74693
74694     // inherit docs
74695     onProxyLoad: function(operation) {
74696         var me = this,
74697             successful = operation.wasSuccessful(),
74698             records = operation.getRecords(),
74699             node = operation.node;
74700
74701         node.set('loading', false);
74702         if (successful) {
74703             records = me.fillNode(node, records);
74704         }
74705         // deprecate read?
74706         me.fireEvent('read', me, operation.node, records, successful);
74707         me.fireEvent('load', me, operation.node, records, successful);
74708         //this is a callback that would have been passed to the 'read' function and is optional
74709         Ext.callback(operation.callback, operation.scope || me, [records, operation, successful]);
74710     },
74711     
74712     /**
74713      * Create any new records when a write is returned from the server.
74714      * @private
74715      * @param {Array} records The array of new records
74716      * @param {Ext.data.Operation} operation The operation that just completed
74717      * @param {Boolean} success True if the operation was successful
74718      */
74719     onCreateRecords: function(records, operation, success) {
74720         if (success) {
74721             var i = 0,
74722                 length = records.length,
74723                 originalRecords = operation.records,
74724                 parentNode,
74725                 record,
74726                 original,
74727                 index;
74728
74729             /**
74730              * Loop over each record returned from the server. Assume they are
74731              * returned in order of how they were sent. If we find a matching
74732              * record, replace it with the newly created one.
74733              */
74734             for (; i < length; ++i) {
74735                 record = records[i];
74736                 original = originalRecords[i];
74737                 if (original) {
74738                     parentNode = original.parentNode;
74739                     if (parentNode) {
74740                         // prevent being added to the removed cache
74741                         original.isReplace = true;
74742                         parentNode.replaceChild(record, original);
74743                         delete original.isReplace;
74744                     }
74745                     record.phantom = false;
74746                 }
74747             }
74748         }
74749     },
74750
74751     /**
74752      * Update any records when a write is returned from the server.
74753      * @private
74754      * @param {Array} records The array of updated records
74755      * @param {Ext.data.Operation} operation The operation that just completed
74756      * @param {Boolean} success True if the operation was successful
74757      */
74758     onUpdateRecords: function(records, operation, success){
74759         if (success) {
74760             var me = this,
74761                 i = 0,
74762                 length = records.length,
74763                 data = me.data,
74764                 original,
74765                 parentNode,
74766                 record;
74767
74768             for (; i < length; ++i) {
74769                 record = records[i];
74770                 original = me.tree.getNodeById(record.getId());
74771                 parentNode = original.parentNode;
74772                 if (parentNode) {
74773                     // prevent being added to the removed cache
74774                     original.isReplace = true;
74775                     parentNode.replaceChild(record, original);
74776                     original.isReplace = false;
74777                 }
74778             }
74779         }
74780     },
74781
74782     /**
74783      * Remove any records when a write is returned from the server.
74784      * @private
74785      * @param {Array} records The array of removed records
74786      * @param {Ext.data.Operation} operation The operation that just completed
74787      * @param {Boolean} success True if the operation was successful
74788      */
74789     onDestroyRecords: function(records, operation, success){
74790         if (success) {
74791             this.removed = [];
74792         }
74793     },
74794
74795     // inherit docs
74796     removeAll: function() {
74797         this.getRootNode().destroy();
74798         this.fireEvent('clear', this);
74799     },
74800
74801     // inherit docs
74802     doSort: function(sorterFn) {
74803         var me = this;
74804         if (me.remoteSort) {
74805             //the load function will pick up the new sorters and request the sorted data from the proxy
74806             me.load();
74807         } else {
74808             me.tree.sort(sorterFn, true);
74809             me.fireEvent('datachanged', me);
74810         }   
74811         me.fireEvent('sort', me);
74812     }
74813 });
74814 /**
74815  * @author Ed Spencer
74816  * @class Ext.data.XmlStore
74817  * @extends Ext.data.Store
74818  * @private
74819  * @ignore
74820  * <p>Small helper class to make creating {@link Ext.data.Store}s from XML data easier.
74821  * A XmlStore will be automatically configured with a {@link Ext.data.reader.Xml}.</p>
74822  * <p>A store configuration would be something like:<pre><code>
74823 var store = new Ext.data.XmlStore({
74824     // store configs
74825     autoDestroy: true,
74826     storeId: 'myStore',
74827     url: 'sheldon.xml', // automatically configures a HttpProxy
74828     // reader configs
74829     record: 'Item', // records will have an "Item" tag
74830     idPath: 'ASIN',
74831     totalRecords: '@TotalResults'
74832     fields: [
74833         // set up the fields mapping into the xml doc
74834         // The first needs mapping, the others are very basic
74835         {name: 'Author', mapping: 'ItemAttributes > Author'},
74836         'Title', 'Manufacturer', 'ProductGroup'
74837     ]
74838 });
74839  * </code></pre></p>
74840  * <p>This store is configured to consume a returned object of the form:<pre><code>
74841 &#60?xml version="1.0" encoding="UTF-8"?>
74842 &#60ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2009-05-15">
74843     &#60Items>
74844         &#60Request>
74845             &#60IsValid>True&#60/IsValid>
74846             &#60ItemSearchRequest>
74847                 &#60Author>Sidney Sheldon&#60/Author>
74848                 &#60SearchIndex>Books&#60/SearchIndex>
74849             &#60/ItemSearchRequest>
74850         &#60/Request>
74851         &#60TotalResults>203&#60/TotalResults>
74852         &#60TotalPages>21&#60/TotalPages>
74853         &#60Item>
74854             &#60ASIN>0446355453&#60/ASIN>
74855             &#60DetailPageURL>
74856                 http://www.amazon.com/
74857             &#60/DetailPageURL>
74858             &#60ItemAttributes>
74859                 &#60Author>Sidney Sheldon&#60/Author>
74860                 &#60Manufacturer>Warner Books&#60/Manufacturer>
74861                 &#60ProductGroup>Book&#60/ProductGroup>
74862                 &#60Title>Master of the Game&#60/Title>
74863             &#60/ItemAttributes>
74864         &#60/Item>
74865     &#60/Items>
74866 &#60/ItemSearchResponse>
74867  * </code></pre>
74868  * An object literal of this form could also be used as the {@link #data} config option.</p>
74869  * <p><b>Note:</b> Although not listed here, this class accepts all of the configuration options of
74870  * <b>{@link Ext.data.reader.Xml XmlReader}</b>.</p>
74871  * @constructor
74872  * @param {Object} config
74873  * @xtype xmlstore
74874  */
74875 Ext.define('Ext.data.XmlStore', {
74876     extend: 'Ext.data.Store',
74877     alternateClassName: 'Ext.data.XmlStore',
74878     alias: 'store.xml',
74879
74880     /**
74881      * @cfg {Ext.data.DataReader} reader @hide
74882      */
74883     constructor: function(config){
74884         config = config || {};
74885         config = config || {};
74886
74887         Ext.applyIf(config, {
74888             proxy: {
74889                 type: 'ajax',
74890                 reader: 'xml',
74891                 writer: 'xml'
74892             }
74893         });
74894
74895         this.callParent([config]);
74896     }
74897 });
74898
74899 /**
74900  * @author Ed Spencer
74901  * @class Ext.data.proxy.Client
74902  * @extends Ext.data.proxy.Proxy
74903  * 
74904  * <p>Base class for any client-side storage. Used as a superclass for {@link Ext.data.proxy.Memory Memory} and 
74905  * {@link Ext.data.proxy.WebStorage Web Storage} proxies. Do not use directly, use one of the subclasses instead.</p>
74906  */
74907 Ext.define('Ext.data.proxy.Client', {
74908     extend: 'Ext.data.proxy.Proxy',
74909     alternateClassName: 'Ext.data.ClientProxy',
74910     
74911     /**
74912      * Abstract function that must be implemented by each ClientProxy subclass. This should purge all record data
74913      * from the client side storage, as well as removing any supporting data (such as lists of record IDs)
74914      */
74915     clear: function() {
74916         Ext.Error.raise("The Ext.data.proxy.Client subclass that you are using has not defined a 'clear' function. See src/data/ClientProxy.js for details.");
74917     }
74918 });
74919 /**
74920  * @author Ed Spencer
74921  * @class Ext.data.proxy.JsonP
74922  * @extends Ext.data.proxy.Server
74923  *
74924  * <p>JsonPProxy is useful when you need to load data from a domain other than the one your application is running
74925  * on. If your application is running on http://domainA.com it cannot use {@link Ext.data.proxy.Ajax Ajax} to load its
74926  * data from http://domainB.com because cross-domain ajax requests are prohibited by the browser.</p>
74927  *
74928  * <p>We can get around this using a JsonPProxy. JsonPProxy injects a &lt;script&gt; tag into the DOM whenever
74929  * an AJAX request would usually be made. Let's say we want to load data from http://domainB.com/users - the script tag
74930  * that would be injected might look like this:</p>
74931  *
74932 <pre><code>
74933 &lt;script src="http://domainB.com/users?callback=someCallback"&gt;&lt;/script&gt;
74934 </code></pre>
74935  *
74936  * <p>When we inject the tag above, the browser makes a request to that url and includes the response as if it was any
74937  * other type of JavaScript include. By passing a callback in the url above, we're telling domainB's server that we
74938  * want to be notified when the result comes in and that it should call our callback function with the data it sends
74939  * back. So long as the server formats the response to look like this, everything will work:</p>
74940  *
74941 <pre><code>
74942 someCallback({
74943     users: [
74944         {
74945             id: 1,
74946             name: "Ed Spencer",
74947             email: "ed@sencha.com"
74948         }
74949     ]
74950 });
74951 </code></pre>
74952  *
74953  * <p>As soon as the script finishes loading, the 'someCallback' function that we passed in the url is called with the
74954  * JSON object that the server returned.</p>
74955  *
74956  * <p>JsonPProxy takes care of all of this automatically. It formats the url you pass, adding the callback
74957  * parameter automatically. It even creates a temporary callback function, waits for it to be called and then puts
74958  * the data into the Proxy making it look just like you loaded it through a normal {@link Ext.data.proxy.Ajax AjaxProxy}.
74959  * Here's how we might set that up:</p>
74960  *
74961 <pre><code>
74962 Ext.define('User', {
74963     extend: 'Ext.data.Model',
74964     fields: ['id', 'name', 'email']
74965 });
74966
74967 var store = new Ext.data.Store({
74968     model: 'User',
74969     proxy: {
74970         type: 'jsonp',
74971         url : 'http://domainB.com/users'
74972     }
74973 });
74974
74975 store.load();
74976 </code></pre>
74977  *
74978  * <p>That's all we need to do - JsonPProxy takes care of the rest. In this case the Proxy will have injected a
74979  * script tag like this:
74980  *
74981 <pre><code>
74982 &lt;script src="http://domainB.com/users?callback=stcCallback001" id="stcScript001"&gt;&lt;/script&gt;
74983 </code></pre>
74984  *
74985  * <p><u>Customization</u></p>
74986  *
74987  * <p>Most parts of this script tag can be customized using the {@link #callbackParam}, {@link #callbackPrefix} and
74988  * {@link #scriptIdPrefix} configurations. For example:
74989  *
74990 <pre><code>
74991 var store = new Ext.data.Store({
74992     model: 'User',
74993     proxy: {
74994         type: 'jsonp',
74995         url : 'http://domainB.com/users',
74996         callbackParam: 'theCallbackFunction',
74997         callbackPrefix: 'ABC',
74998         scriptIdPrefix: 'injectedScript'
74999     }
75000 });
75001
75002 store.load();
75003 </code></pre>
75004  *
75005  * <p>Would inject a script tag like this:</p>
75006  *
75007 <pre><code>
75008 &lt;script src="http://domainB.com/users?theCallbackFunction=ABC001" id="injectedScript001"&gt;&lt;/script&gt;
75009 </code></pre>
75010  *
75011  * <p><u>Implementing on the server side</u></p>
75012  *
75013  * <p>The remote server side needs to be configured to return data in this format. Here are suggestions for how you
75014  * might achieve this using Java, PHP and ASP.net:</p>
75015  *
75016  * <p>Java:</p>
75017  *
75018 <pre><code>
75019 boolean jsonP = false;
75020 String cb = request.getParameter("callback");
75021 if (cb != null) {
75022     jsonP = true;
75023     response.setContentType("text/javascript");
75024 } else {
75025     response.setContentType("application/x-json");
75026 }
75027 Writer out = response.getWriter();
75028 if (jsonP) {
75029     out.write(cb + "(");
75030 }
75031 out.print(dataBlock.toJsonString());
75032 if (jsonP) {
75033     out.write(");");
75034 }
75035 </code></pre>
75036  *
75037  * <p>PHP:</p>
75038  *
75039 <pre><code>
75040 $callback = $_REQUEST['callback'];
75041
75042 // Create the output object.
75043 $output = array('a' => 'Apple', 'b' => 'Banana');
75044
75045 //start output
75046 if ($callback) {
75047     header('Content-Type: text/javascript');
75048     echo $callback . '(' . json_encode($output) . ');';
75049 } else {
75050     header('Content-Type: application/x-json');
75051     echo json_encode($output);
75052 }
75053 </code></pre>
75054  *
75055  * <p>ASP.net:</p>
75056  *
75057 <pre><code>
75058 String jsonString = "{success: true}";
75059 String cb = Request.Params.Get("callback");
75060 String responseString = "";
75061 if (!String.IsNullOrEmpty(cb)) {
75062     responseString = cb + "(" + jsonString + ")";
75063 } else {
75064     responseString = jsonString;
75065 }
75066 Response.Write(responseString);
75067 </code></pre>
75068  *
75069  */
75070 Ext.define('Ext.data.proxy.JsonP', {
75071     extend: 'Ext.data.proxy.Server',
75072     alternateClassName: 'Ext.data.ScriptTagProxy',
75073     alias: ['proxy.jsonp', 'proxy.scripttag'],
75074     requires: ['Ext.data.JsonP'],
75075
75076     defaultWriterType: 'base',
75077
75078     /**
75079      * @cfg {String} callbackKey (Optional) See {@link Ext.data.JsonP#callbackKey}.
75080      */
75081     callbackKey : 'callback',
75082
75083     /**
75084      * @cfg {String} recordParam
75085      * The param name to use when passing records to the server (e.g. 'records=someEncodedRecordString').
75086      * Defaults to 'records'
75087      */
75088     recordParam: 'records',
75089
75090     /**
75091      * @cfg {Boolean} autoAppendParams True to automatically append the request's params to the generated url. Defaults to true
75092      */
75093     autoAppendParams: true,
75094
75095     constructor: function(){
75096         this.addEvents(
75097             /**
75098              * @event exception
75099              * Fires when the server returns an exception
75100              * @param {Ext.data.proxy.Proxy} this
75101              * @param {Ext.data.Request} request The request that was sent
75102              * @param {Ext.data.Operation} operation The operation that triggered the request
75103              */
75104             'exception'
75105         );
75106         this.callParent(arguments);
75107     },
75108
75109     /**
75110      * @private
75111      * Performs the read request to the remote domain. JsonPProxy does not actually create an Ajax request,
75112      * instead we write out a <script> tag based on the configuration of the internal Ext.data.Request object
75113      * @param {Ext.data.Operation} operation The {@link Ext.data.Operation Operation} object to execute
75114      * @param {Function} callback A callback function to execute when the Operation has been completed
75115      * @param {Object} scope The scope to execute the callback in
75116      */
75117     doRequest: function(operation, callback, scope) {
75118         //generate the unique IDs for this request
75119         var me      = this,
75120             writer  = me.getWriter(),
75121             request = me.buildRequest(operation),
75122             params = request.params;
75123
75124         if (operation.allowWrite()) {
75125             request = writer.write(request);
75126         }
75127
75128         //apply JsonPProxy-specific attributes to the Request
75129         Ext.apply(request, {
75130             callbackKey: me.callbackKey,
75131             timeout: me.timeout,
75132             scope: me,
75133             disableCaching: false, // handled by the proxy
75134             callback: me.createRequestCallback(request, operation, callback, scope)
75135         });
75136         
75137         // prevent doubling up
75138         if (me.autoAppendParams) {
75139             request.params = {};
75140         }
75141         
75142         request.jsonp = Ext.data.JsonP.request(request);
75143         // restore on the request
75144         request.params = params;
75145         operation.setStarted();
75146         me.lastRequest = request;
75147
75148         return request;
75149     },
75150
75151     /**
75152      * @private
75153      * Creates and returns the function that is called when the request has completed. The returned function
75154      * should accept a Response object, which contains the response to be read by the configured Reader.
75155      * The third argument is the callback that should be called after the request has been completed and the Reader has decoded
75156      * the response. This callback will typically be the callback passed by a store, e.g. in proxy.read(operation, theCallback, scope)
75157      * theCallback refers to the callback argument received by this function.
75158      * See {@link #doRequest} for details.
75159      * @param {Ext.data.Request} request The Request object
75160      * @param {Ext.data.Operation} operation The Operation being executed
75161      * @param {Function} callback The callback function to be called when the request completes. This is usually the callback
75162      * passed to doRequest
75163      * @param {Object} scope The scope in which to execute the callback function
75164      * @return {Function} The callback function
75165      */
75166     createRequestCallback: function(request, operation, callback, scope) {
75167         var me = this;
75168
75169         return function(success, response, errorType) {
75170             delete me.lastRequest;
75171             me.processResponse(success, operation, request, response, callback, scope);
75172         };
75173     },
75174     
75175     // inherit docs
75176     setException: function(operation, response) {
75177         operation.setException(operation.request.jsonp.errorType);
75178     },
75179
75180
75181     /**
75182      * Generates a url based on a given Ext.data.Request object. Adds the params and callback function name to the url
75183      * @param {Ext.data.Request} request The request object
75184      * @return {String} The url
75185      */
75186     buildUrl: function(request) {
75187         var me      = this,
75188             url     = me.callParent(arguments),
75189             params  = Ext.apply({}, request.params),
75190             filters = params.filters,
75191             records,
75192             filter, i;
75193
75194         delete params.filters;
75195  
75196         if (me.autoAppendParams) {
75197             url = Ext.urlAppend(url, Ext.Object.toQueryString(params));
75198         }
75199
75200         if (filters && filters.length) {
75201             for (i = 0; i < filters.length; i++) {
75202                 filter = filters[i];
75203
75204                 if (filter.value) {
75205                     url = Ext.urlAppend(url, filter.property + "=" + filter.value);
75206                 }
75207             }
75208         }
75209
75210         //if there are any records present, append them to the url also
75211         records = request.records;
75212
75213         if (Ext.isArray(records) && records.length > 0) {
75214             url = Ext.urlAppend(url, Ext.String.format("{0}={1}", me.recordParam, me.encodeRecords(records)));
75215         }
75216
75217         return url;
75218     },
75219
75220     //inherit docs
75221     destroy: function() {
75222         this.abort();
75223         this.callParent();
75224     },
75225
75226     /**
75227      * Aborts the current server request if one is currently running
75228      */
75229     abort: function() {
75230         var lastRequest = this.lastRequest;
75231         if (lastRequest) {
75232             Ext.data.JsonP.abort(lastRequest.jsonp);
75233         }
75234     },
75235
75236     /**
75237      * Encodes an array of records into a string suitable to be appended to the script src url. This is broken
75238      * out into its own function so that it can be easily overridden.
75239      * @param {Array} records The records array
75240      * @return {String} The encoded records string
75241      */
75242     encodeRecords: function(records) {
75243         var encoded = "",
75244             i = 0,
75245             len = records.length;
75246
75247         for (; i < len; i++) {
75248             encoded += Ext.Object.toQueryString(records[i].data);
75249         }
75250
75251         return encoded;
75252     }
75253 });
75254
75255 /**
75256  * @author Ed Spencer
75257  * @class Ext.data.proxy.WebStorage
75258  * @extends Ext.data.proxy.Client
75259  * 
75260  * <p>WebStorageProxy is simply a superclass for the {@link Ext.data.proxy.LocalStorage localStorage} and 
75261  * {@link Ext.data.proxy.SessionStorage sessionStorage} proxies. It uses the new HTML5 key/value client-side storage 
75262  * objects to save {@link Ext.data.Model model instances} for offline use.</p>
75263  * 
75264  * @constructor
75265  * Creates the proxy, throws an error if local storage is not supported in the current browser
75266  * @param {Object} config Optional config object
75267  */
75268 Ext.define('Ext.data.proxy.WebStorage', {
75269     extend: 'Ext.data.proxy.Client',
75270     alternateClassName: 'Ext.data.WebStorageProxy',
75271     
75272     /**
75273      * @cfg {String} id The unique ID used as the key in which all record data are stored in the local storage object
75274      */
75275     id: undefined,
75276
75277     /**
75278      * @ignore
75279      */
75280     constructor: function(config) {
75281         this.callParent(arguments);
75282         
75283         /**
75284          * Cached map of records already retrieved by this Proxy - ensures that the same instance is always retrieved
75285          * @property cache
75286          * @type Object
75287          */
75288         this.cache = {};
75289
75290         if (this.getStorageObject() === undefined) {
75291             Ext.Error.raise("Local Storage is not supported in this browser, please use another type of data proxy");
75292         }
75293
75294         //if an id is not given, try to use the store's id instead
75295         this.id = this.id || (this.store ? this.store.storeId : undefined);
75296
75297         if (this.id === undefined) {
75298             Ext.Error.raise("No unique id was provided to the local storage proxy. See Ext.data.proxy.LocalStorage documentation for details");
75299         }
75300
75301         this.initialize();
75302     },
75303
75304     //inherit docs
75305     create: function(operation, callback, scope) {
75306         var records = operation.records,
75307             length  = records.length,
75308             ids     = this.getIds(),
75309             id, record, i;
75310         
75311         operation.setStarted();
75312
75313         for (i = 0; i < length; i++) {
75314             record = records[i];
75315
75316             if (record.phantom) {
75317                 record.phantom = false;
75318                 id = this.getNextId();
75319             } else {
75320                 id = record.getId();
75321             }
75322
75323             this.setRecord(record, id);
75324             ids.push(id);
75325         }
75326
75327         this.setIds(ids);
75328
75329         operation.setCompleted();
75330         operation.setSuccessful();
75331
75332         if (typeof callback == 'function') {
75333             callback.call(scope || this, operation);
75334         }
75335     },
75336
75337     //inherit docs
75338     read: function(operation, callback, scope) {
75339         //TODO: respect sorters, filters, start and limit options on the Operation
75340
75341         var records = [],
75342             ids     = this.getIds(),
75343             length  = ids.length,
75344             i, recordData, record;
75345         
75346         //read a single record
75347         if (operation.id) {
75348             record = this.getRecord(operation.id);
75349             
75350             if (record) {
75351                 records.push(record);
75352                 operation.setSuccessful();
75353             }
75354         } else {
75355             for (i = 0; i < length; i++) {
75356                 records.push(this.getRecord(ids[i]));
75357             }
75358             operation.setSuccessful();
75359         }
75360         
75361         operation.setCompleted();
75362
75363         operation.resultSet = Ext.create('Ext.data.ResultSet', {
75364             records: records,
75365             total  : records.length,
75366             loaded : true
75367         });
75368
75369         if (typeof callback == 'function') {
75370             callback.call(scope || this, operation);
75371         }
75372     },
75373
75374     //inherit docs
75375     update: function(operation, callback, scope) {
75376         var records = operation.records,
75377             length  = records.length,
75378             ids     = this.getIds(),
75379             record, id, i;
75380
75381         operation.setStarted();
75382
75383         for (i = 0; i < length; i++) {
75384             record = records[i];
75385             this.setRecord(record);
75386             
75387             //we need to update the set of ids here because it's possible that a non-phantom record was added
75388             //to this proxy - in which case the record's id would never have been added via the normal 'create' call
75389             id = record.getId();
75390             if (id !== undefined && Ext.Array.indexOf(ids, id) == -1) {
75391                 ids.push(id);
75392             }
75393         }
75394         this.setIds(ids);
75395
75396         operation.setCompleted();
75397         operation.setSuccessful();
75398
75399         if (typeof callback == 'function') {
75400             callback.call(scope || this, operation);
75401         }
75402     },
75403
75404     //inherit
75405     destroy: function(operation, callback, scope) {
75406         var records = operation.records,
75407             length  = records.length,
75408             ids     = this.getIds(),
75409
75410             //newIds is a copy of ids, from which we remove the destroyed records
75411             newIds  = [].concat(ids),
75412             i;
75413
75414         for (i = 0; i < length; i++) {
75415             Ext.Array.remove(newIds, records[i].getId());
75416             this.removeRecord(records[i], false);
75417         }
75418
75419         this.setIds(newIds);
75420         
75421         operation.setCompleted();
75422         operation.setSuccessful();
75423
75424         if (typeof callback == 'function') {
75425             callback.call(scope || this, operation);
75426         }
75427     },
75428
75429     /**
75430      * @private
75431      * Fetches a model instance from the Proxy by ID. Runs each field's decode function (if present) to decode the data
75432      * @param {String} id The record's unique ID
75433      * @return {Ext.data.Model} The model instance
75434      */
75435     getRecord: function(id) {
75436         if (this.cache[id] === undefined) {
75437             var rawData = Ext.decode(this.getStorageObject().getItem(this.getRecordKey(id))),
75438                 data    = {},
75439                 Model   = this.model,
75440                 fields  = Model.prototype.fields.items,
75441                 length  = fields.length,
75442                 i, field, name, record;
75443
75444             for (i = 0; i < length; i++) {
75445                 field = fields[i];
75446                 name  = field.name;
75447
75448                 if (typeof field.decode == 'function') {
75449                     data[name] = field.decode(rawData[name]);
75450                 } else {
75451                     data[name] = rawData[name];
75452                 }
75453             }
75454
75455             record = new Model(data, id);
75456             record.phantom = false;
75457
75458             this.cache[id] = record;
75459         }
75460         
75461         return this.cache[id];
75462     },
75463
75464     /**
75465      * Saves the given record in the Proxy. Runs each field's encode function (if present) to encode the data
75466      * @param {Ext.data.Model} record The model instance
75467      * @param {String} id The id to save the record under (defaults to the value of the record's getId() function)
75468      */
75469     setRecord: function(record, id) {
75470         if (id) {
75471             record.setId(id);
75472         } else {
75473             id = record.getId();
75474         }
75475
75476         var me = this,
75477             rawData = record.data,
75478             data    = {},
75479             model   = me.model,
75480             fields  = model.prototype.fields.items,
75481             length  = fields.length,
75482             i = 0,
75483             field, name, obj, key;
75484
75485         for (; i < length; i++) {
75486             field = fields[i];
75487             name  = field.name;
75488
75489             if (typeof field.encode == 'function') {
75490                 data[name] = field.encode(rawData[name], record);
75491             } else {
75492                 data[name] = rawData[name];
75493             }
75494         }
75495
75496         obj = me.getStorageObject();
75497         key = me.getRecordKey(id);
75498         
75499         //keep the cache up to date
75500         me.cache[id] = record;
75501         
75502         //iPad bug requires that we remove the item before setting it
75503         obj.removeItem(key);
75504         obj.setItem(key, Ext.encode(data));
75505     },
75506
75507     /**
75508      * @private
75509      * Physically removes a given record from the local storage. Used internally by {@link #destroy}, which you should
75510      * use instead because it updates the list of currently-stored record ids
75511      * @param {String|Number|Ext.data.Model} id The id of the record to remove, or an Ext.data.Model instance
75512      */
75513     removeRecord: function(id, updateIds) {
75514         var me = this,
75515             ids;
75516             
75517         if (id.isModel) {
75518             id = id.getId();
75519         }
75520
75521         if (updateIds !== false) {
75522             ids = me.getIds();
75523             Ext.Array.remove(ids, id);
75524             me.setIds(ids);
75525         }
75526
75527         me.getStorageObject().removeItem(me.getRecordKey(id));
75528     },
75529
75530     /**
75531      * @private
75532      * Given the id of a record, returns a unique string based on that id and the id of this proxy. This is used when
75533      * storing data in the local storage object and should prevent naming collisions.
75534      * @param {String|Number|Ext.data.Model} id The record id, or a Model instance
75535      * @return {String} The unique key for this record
75536      */
75537     getRecordKey: function(id) {
75538         if (id.isModel) {
75539             id = id.getId();
75540         }
75541
75542         return Ext.String.format("{0}-{1}", this.id, id);
75543     },
75544
75545     /**
75546      * @private
75547      * Returns the unique key used to store the current record counter for this proxy. This is used internally when
75548      * realizing models (creating them when they used to be phantoms), in order to give each model instance a unique id.
75549      * @return {String} The counter key
75550      */
75551     getRecordCounterKey: function() {
75552         return Ext.String.format("{0}-counter", this.id);
75553     },
75554
75555     /**
75556      * @private
75557      * Returns the array of record IDs stored in this Proxy
75558      * @return {Array} The record IDs. Each is cast as a Number
75559      */
75560     getIds: function() {
75561         var ids    = (this.getStorageObject().getItem(this.id) || "").split(","),
75562             length = ids.length,
75563             i;
75564
75565         if (length == 1 && ids[0] === "") {
75566             ids = [];
75567         } else {
75568             for (i = 0; i < length; i++) {
75569                 ids[i] = parseInt(ids[i], 10);
75570             }
75571         }
75572
75573         return ids;
75574     },
75575
75576     /**
75577      * @private
75578      * Saves the array of ids representing the set of all records in the Proxy
75579      * @param {Array} ids The ids to set
75580      */
75581     setIds: function(ids) {
75582         var obj = this.getStorageObject(),
75583             str = ids.join(",");
75584         
75585         obj.removeItem(this.id);
75586         
75587         if (!Ext.isEmpty(str)) {
75588             obj.setItem(this.id, str);
75589         }
75590     },
75591
75592     /**
75593      * @private
75594      * Returns the next numerical ID that can be used when realizing a model instance (see getRecordCounterKey). Increments
75595      * the counter.
75596      * @return {Number} The id
75597      */
75598     getNextId: function() {
75599         var obj  = this.getStorageObject(),
75600             key  = this.getRecordCounterKey(),
75601             last = obj.getItem(key),
75602             ids, id;
75603         
75604         if (last === null) {
75605             ids = this.getIds();
75606             last = ids[ids.length - 1] || 0;
75607         }
75608         
75609         id = parseInt(last, 10) + 1;
75610         obj.setItem(key, id);
75611         
75612         return id;
75613     },
75614
75615     /**
75616      * @private
75617      * Sets up the Proxy by claiming the key in the storage object that corresponds to the unique id of this Proxy. Called
75618      * automatically by the constructor, this should not need to be called again unless {@link #clear} has been called.
75619      */
75620     initialize: function() {
75621         var storageObject = this.getStorageObject();
75622         storageObject.setItem(this.id, storageObject.getItem(this.id) || "");
75623     },
75624
75625     /**
75626      * Destroys all records stored in the proxy and removes all keys and values used to support the proxy from the storage object
75627      */
75628     clear: function() {
75629         var obj = this.getStorageObject(),
75630             ids = this.getIds(),
75631             len = ids.length,
75632             i;
75633
75634         //remove all the records
75635         for (i = 0; i < len; i++) {
75636             this.removeRecord(ids[i]);
75637         }
75638
75639         //remove the supporting objects
75640         obj.removeItem(this.getRecordCounterKey());
75641         obj.removeItem(this.id);
75642     },
75643
75644     /**
75645      * @private
75646      * Abstract function which should return the storage object that data will be saved to. This must be implemented
75647      * in each subclass.
75648      * @return {Object} The storage object
75649      */
75650     getStorageObject: function() {
75651         Ext.Error.raise("The getStorageObject function has not been defined in your Ext.data.proxy.WebStorage subclass");
75652     }
75653 });
75654 /**
75655  * @author Ed Spencer
75656  * @class Ext.data.proxy.LocalStorage
75657  * @extends Ext.data.proxy.WebStorage
75658  * 
75659  * <p>The LocalStorageProxy uses the new HTML5 localStorage API to save {@link Ext.data.Model Model} data locally on
75660  * the client browser. HTML5 localStorage is a key-value store (e.g. cannot save complex objects like JSON), so
75661  * LocalStorageProxy automatically serializes and deserializes data when saving and retrieving it.</p>
75662  * 
75663  * <p>localStorage is extremely useful for saving user-specific information without needing to build server-side 
75664  * infrastructure to support it. Let's imagine we're writing a Twitter search application and want to save the user's
75665  * searches locally so they can easily perform a saved search again later. We'd start by creating a Search model:</p>
75666  * 
75667 <pre><code>
75668 Ext.define('Search', {
75669     fields: ['id', 'query'],
75670     extend: 'Ext.data.Model',
75671     proxy: {
75672         type: 'localstorage',
75673         id  : 'twitter-Searches'
75674     }
75675 });
75676 </code></pre>
75677  * 
75678  * <p>Our Search model contains just two fields - id and query - plus a Proxy definition. The only configuration we
75679  * need to pass to the LocalStorage proxy is an {@link #id}. This is important as it separates the Model data in this
75680  * Proxy from all others. The localStorage API puts all data into a single shared namespace, so by setting an id we
75681  * enable LocalStorageProxy to manage the saved Search data.</p>
75682  * 
75683  * <p>Saving our data into localStorage is easy and would usually be done with a {@link Ext.data.Store Store}:</p>
75684  * 
75685 <pre><code>
75686 //our Store automatically picks up the LocalStorageProxy defined on the Search model
75687 var store = new Ext.data.Store({
75688     model: "Search"
75689 });
75690
75691 //loads any existing Search data from localStorage
75692 store.load();
75693
75694 //now add some Searches
75695 store.add({query: 'Sencha Touch'});
75696 store.add({query: 'Ext JS'});
75697
75698 //finally, save our Search data to localStorage
75699 store.sync();
75700 </code></pre>
75701  * 
75702  * <p>The LocalStorageProxy automatically gives our new Searches an id when we call store.sync(). It encodes the Model
75703  * data and places it into localStorage. We can also save directly to localStorage, bypassing the Store altogether:</p>
75704  * 
75705 <pre><code>
75706 var search = Ext.ModelManager.create({query: 'Sencha Animator'}, 'Search');
75707
75708 //uses the configured LocalStorageProxy to save the new Search to localStorage
75709 search.save();
75710 </code></pre>
75711  * 
75712  * <p><u>Limitations</u></p>
75713  * 
75714  * <p>If this proxy is used in a browser where local storage is not supported, the constructor will throw an error.
75715  * A local storage proxy requires a unique ID which is used as a key in which all record data are stored in the
75716  * local storage object.</p>
75717  * 
75718  * <p>It's important to supply this unique ID as it cannot be reliably determined otherwise. If no id is provided
75719  * but the attached store has a storeId, the storeId will be used. If neither option is presented the proxy will
75720  * throw an error.</p>
75721  */
75722 Ext.define('Ext.data.proxy.LocalStorage', {
75723     extend: 'Ext.data.proxy.WebStorage',
75724     alias: 'proxy.localstorage',
75725     alternateClassName: 'Ext.data.LocalStorageProxy',
75726     
75727     //inherit docs
75728     getStorageObject: function() {
75729         return window.localStorage;
75730     }
75731 });
75732 /**
75733  * @author Ed Spencer
75734  * @class Ext.data.proxy.Memory
75735  * @extends Ext.data.proxy.Client
75736  *
75737  * <p>In-memory proxy. This proxy simply uses a local variable for data storage/retrieval, so its contents are lost on
75738  * every page refresh.</p>
75739  *
75740  * <p>Usually this Proxy isn't used directly, serving instead as a helper to a {@link Ext.data.Store Store} where a
75741  * reader is required to load data. For example, say we have a Store for a User model and have some inline data we want
75742  * to load, but this data isn't in quite the right format: we can use a MemoryProxy with a JsonReader to read it into
75743  * our Store:</p>
75744  *
75745 <pre><code>
75746 //this is the model we will be using in the store
75747 Ext.define('User', {
75748     extend: 'Ext.data.Model',
75749     fields: [
75750         {name: 'id',    type: 'int'},
75751         {name: 'name',  type: 'string'},
75752         {name: 'phone', type: 'string', mapping: 'phoneNumber'}
75753     ]
75754 });
75755
75756 //this data does not line up to our model fields - the phone field is called phoneNumber
75757 var data = {
75758     users: [
75759         {
75760             id: 1,
75761             name: 'Ed Spencer',
75762             phoneNumber: '555 1234'
75763         },
75764         {
75765             id: 2,
75766             name: 'Abe Elias',
75767             phoneNumber: '666 1234'
75768         }
75769     ]
75770 };
75771
75772 //note how we set the 'root' in the reader to match the data structure above
75773 var store = new Ext.data.Store({
75774     autoLoad: true,
75775     model: 'User',
75776     data : data,
75777     proxy: {
75778         type: 'memory',
75779         reader: {
75780             type: 'json',
75781             root: 'users'
75782         }
75783     }
75784 });
75785 </code></pre>
75786  */
75787 Ext.define('Ext.data.proxy.Memory', {
75788     extend: 'Ext.data.proxy.Client',
75789     alias: 'proxy.memory',
75790     alternateClassName: 'Ext.data.MemoryProxy',
75791
75792     /**
75793      * @cfg {Array} data Optional array of Records to load into the Proxy
75794      */
75795
75796     constructor: function(config) {
75797         this.callParent([config]);
75798
75799         //ensures that the reader has been instantiated properly
75800         this.setReader(this.reader);
75801     },
75802
75803     /**
75804      * Reads data from the configured {@link #data} object. Uses the Proxy's {@link #reader}, if present
75805      * @param {Ext.data.Operation} operation The read Operation
75806      * @param {Function} callback The callback to call when reading has completed
75807      * @param {Object} scope The scope to call the callback function in
75808      */
75809     read: function(operation, callback, scope) {
75810         var me     = this,
75811             reader = me.getReader(),
75812             result = reader.read(me.data);
75813
75814         Ext.apply(operation, {
75815             resultSet: result
75816         });
75817
75818         operation.setCompleted();
75819         operation.setSuccessful();
75820         Ext.callback(callback, scope || me, [operation]);
75821     },
75822
75823     clear: Ext.emptyFn
75824 });
75825
75826 /**
75827  * @author Ed Spencer
75828  * @class Ext.data.proxy.Rest
75829  * @extends Ext.data.proxy.Ajax
75830  * 
75831  * <p>RestProxy is a specialization of the {@link Ext.data.proxy.Ajax AjaxProxy} which simply maps the four actions 
75832  * (create, read, update and destroy) to RESTful HTTP verbs. For example, let's set up a {@link Ext.data.Model Model}
75833  * with an inline RestProxy</p>
75834  * 
75835 <pre><code>
75836 Ext.define('User', {
75837     extend: 'Ext.data.Model',
75838     fields: ['id', 'name', 'email'],
75839
75840     proxy: {
75841         type: 'rest',
75842         url : '/users'
75843     }
75844 });
75845 </code></pre>
75846  * 
75847  * <p>Now we can create a new User instance and save it via the RestProxy. Doing this will cause the Proxy to send a
75848  * POST request to '/users':
75849  * 
75850 <pre><code>
75851 var user = Ext.ModelManager.create({name: 'Ed Spencer', email: 'ed@sencha.com'}, 'User');
75852
75853 user.save(); //POST /users
75854 </code></pre>
75855  * 
75856  * <p>Let's expand this a little and provide a callback for the {@link Ext.data.Model#save} call to update the Model
75857  * once it has been created. We'll assume the creation went successfully and that the server gave this user an ID of 
75858  * 123:</p>
75859  * 
75860 <pre><code>
75861 user.save({
75862     success: function(user) {
75863         user.set('name', 'Khan Noonien Singh');
75864
75865         user.save(); //PUT /users/123
75866     }
75867 });
75868 </code></pre>
75869  * 
75870  * <p>Now that we're no longer creating a new Model instance, the request method is changed to an HTTP PUT, targeting
75871  * the relevant url for that user. Now let's delete this user, which will use the DELETE method:</p>
75872  * 
75873 <pre><code>
75874     user.destroy(); //DELETE /users/123
75875 </code></pre>
75876  * 
75877  * <p>Finally, when we perform a load of a Model or Store, RestProxy will use the GET method:</p>
75878  * 
75879 <pre><code>
75880 //1. Load via Store
75881
75882 //the Store automatically picks up the Proxy from the User model
75883 var store = new Ext.data.Store({
75884     model: 'User'
75885 });
75886
75887 store.load(); //GET /users
75888
75889 //2. Load directly from the Model
75890
75891 //GET /users/123
75892 Ext.ModelManager.getModel('User').load(123, {
75893     success: function(user) {
75894         console.log(user.getId()); //outputs 123
75895     }
75896 });
75897 </code></pre>
75898  * 
75899  * <p><u>Url generation</u></p>
75900  * 
75901  * <p>RestProxy is able to automatically generate the urls above based on two configuration options - {@link #appendId}
75902  * and {@link #format}. If appendId is true (it is by default) then RestProxy will automatically append the ID of the 
75903  * Model instance in question to the configured url, resulting in the '/users/123' that we saw above.</p>
75904  * 
75905  * <p>If the request is not for a specific Model instance (e.g. loading a Store), the url is not appended with an id. 
75906  * RestProxy will automatically insert a '/' before the ID if one is not already present.</p>
75907  * 
75908 <pre><code>
75909 new Ext.data.proxy.Rest({
75910     url: '/users',
75911     appendId: true //default
75912 });
75913
75914 // Collection url: /users
75915 // Instance url  : /users/123
75916 </code></pre>
75917  * 
75918  * <p>RestProxy can also optionally append a format string to the end of any generated url:</p>
75919  * 
75920 <pre><code>
75921 new Ext.data.proxy.Rest({
75922     url: '/users',
75923     format: 'json'
75924 });
75925
75926 // Collection url: /users.json
75927 // Instance url  : /users/123.json
75928 </code></pre>
75929  * 
75930  * <p>If further customization is needed, simply implement the {@link #buildUrl} method and add your custom generated
75931  * url onto the {@link Ext.data.Request Request} object that is passed to buildUrl. See 
75932  * <a href="source/RestProxy.html#method-Ext.data.proxy.Rest-buildUrl">RestProxy's implementation</a> for an example of
75933  * how to achieve this.</p>
75934  * 
75935  * <p>Note that RestProxy inherits from {@link Ext.data.proxy.Ajax AjaxProxy}, which already injects all of the sorter,
75936  * filter, group and paging options into the generated url. See the {@link Ext.data.proxy.Ajax AjaxProxy docs} for more
75937  * details.</p>
75938  */
75939 Ext.define('Ext.data.proxy.Rest', {
75940     extend: 'Ext.data.proxy.Ajax',
75941     alternateClassName: 'Ext.data.RestProxy',
75942     alias : 'proxy.rest',
75943     
75944     /**
75945      * @cfg {Boolean} appendId True to automatically append the ID of a Model instance when performing a request based
75946      * on that single instance. See RestProxy intro docs for more details. Defaults to true.
75947      */
75948     appendId: true,
75949     
75950     /**
75951      * @cfg {String} format Optional data format to send to the server when making any request (e.g. 'json'). See the
75952      * RestProxy intro docs for full details. Defaults to undefined.
75953      */
75954     
75955     /**
75956      * @cfg {Boolean} batchActions True to batch actions of a particular type when synchronizing the store.
75957      * Defaults to <tt>false</tt>.
75958      */
75959     batchActions: false,
75960     
75961     /**
75962      * Specialized version of buildUrl that incorporates the {@link #appendId} and {@link #format} options into the
75963      * generated url. Override this to provide further customizations, but remember to call the superclass buildUrl
75964      * so that additional parameters like the cache buster string are appended
75965      */
75966     buildUrl: function(request) {
75967         var me        = this,
75968             operation = request.operation,
75969             records   = operation.records || [],
75970             record    = records[0],
75971             format    = me.format,
75972             url       = me.getUrl(request),
75973             id        = record ? record.getId() : operation.id;
75974         
75975         if (me.appendId && id) {
75976             if (!url.match(/\/$/)) {
75977                 url += '/';
75978             }
75979             
75980             url += id;
75981         }
75982         
75983         if (format) {
75984             if (!url.match(/\.$/)) {
75985                 url += '.';
75986             }
75987             
75988             url += format;
75989         }
75990         
75991         request.url = url;
75992         
75993         return me.callParent(arguments);
75994     }
75995 }, function() {
75996     Ext.apply(this.prototype, {
75997         /**
75998          * Mapping of action name to HTTP request method. These default to RESTful conventions for the 'create', 'read',
75999          * 'update' and 'destroy' actions (which map to 'POST', 'GET', 'PUT' and 'DELETE' respectively). This object should
76000          * not be changed except globally via {@link Ext#override Ext.override} - the {@link #getMethod} function can be overridden instead.
76001          * @property actionMethods
76002          * @type Object
76003          */
76004         actionMethods: {
76005             create : 'POST',
76006             read   : 'GET',
76007             update : 'PUT',
76008             destroy: 'DELETE'
76009         }
76010     });
76011 });
76012
76013 /**
76014  * @author Ed Spencer
76015  * @class Ext.data.proxy.SessionStorage
76016  * @extends Ext.data.proxy.WebStorage
76017  * 
76018  * <p>Proxy which uses HTML5 session storage as its data storage/retrieval mechanism.
76019  * If this proxy is used in a browser where session storage is not supported, the constructor will throw an error.
76020  * A session storage proxy requires a unique ID which is used as a key in which all record data are stored in the
76021  * session storage object.</p>
76022  * 
76023  * <p>It's important to supply this unique ID as it cannot be reliably determined otherwise. If no id is provided
76024  * but the attached store has a storeId, the storeId will be used. If neither option is presented the proxy will
76025  * throw an error.</p>
76026  * 
76027  * <p>Proxies are almost always used with a {@link Ext.data.Store store}:<p>
76028  * 
76029 <pre><code>
76030 new Ext.data.Store({
76031     proxy: {
76032         type: 'sessionstorage',
76033         id  : 'myProxyKey'
76034     }
76035 });
76036 </code></pre>
76037  * 
76038  * <p>Alternatively you can instantiate the Proxy directly:</p>
76039  * 
76040 <pre><code>
76041 new Ext.data.proxy.SessionStorage({
76042     id  : 'myOtherProxyKey'
76043 });
76044  </code></pre>
76045  * 
76046  * <p>Note that session storage is different to local storage (see {@link Ext.data.proxy.LocalStorage}) - if a browser
76047  * session is ended (e.g. by closing the browser) then all data in a SessionStorageProxy are lost. Browser restarts
76048  * don't affect the {@link Ext.data.proxy.LocalStorage} - the data are preserved.</p>
76049  */
76050 Ext.define('Ext.data.proxy.SessionStorage', {
76051     extend: 'Ext.data.proxy.WebStorage',
76052     alias: 'proxy.sessionstorage',
76053     alternateClassName: 'Ext.data.SessionStorageProxy',
76054     
76055     //inherit docs
76056     getStorageObject: function() {
76057         return window.sessionStorage;
76058     }
76059 });
76060
76061 /**
76062  * @author Ed Spencer
76063  * @class Ext.data.reader.Array
76064  * @extends Ext.data.reader.Json
76065  * 
76066  * <p>Data reader class to create an Array of {@link Ext.data.Model} objects from an Array.
76067  * Each element of that Array represents a row of data fields. The
76068  * fields are pulled into a Record object using as a subscript, the <code>mapping</code> property
76069  * of the field definition if it exists, or the field's ordinal position in the definition.</p>
76070  * 
76071  * <p><u>Example code:</u></p>
76072  * 
76073 <pre><code>
76074 Employee = Ext.define('Employee', {
76075     extend: 'Ext.data.Model',
76076     fields: [
76077         'id',
76078         {name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
76079         {name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.        
76080     ]
76081 });
76082
76083 var myReader = new Ext.data.reader.Array({
76084     model: 'Employee'
76085 }, Employee);
76086 </code></pre>
76087  * 
76088  * <p>This would consume an Array like this:</p>
76089  * 
76090 <pre><code>
76091 [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
76092 </code></pre>
76093  * 
76094  * @constructor
76095  * Create a new ArrayReader
76096  * @param {Object} meta Metadata configuration options.
76097  */
76098 Ext.define('Ext.data.reader.Array', {
76099     extend: 'Ext.data.reader.Json',
76100     alternateClassName: 'Ext.data.ArrayReader',
76101     alias : 'reader.array',
76102
76103     /**
76104      * @private
76105      * Most of the work is done for us by JsonReader, but we need to overwrite the field accessors to just
76106      * reference the correct position in the array.
76107      */
76108     buildExtractors: function() {
76109         this.callParent(arguments);
76110         
76111         var fields = this.model.prototype.fields.items,
76112             length = fields.length,
76113             extractorFunctions = [],
76114             i;
76115         
76116         for (i = 0; i < length; i++) {
76117             extractorFunctions.push(function(index) {
76118                 return function(data) {
76119                     return data[index];
76120                 };
76121             }(fields[i].mapping || i));
76122         }
76123         
76124         this.extractorFunctions = extractorFunctions;
76125     }
76126 });
76127
76128 /**
76129  * @author Ed Spencer
76130  * @class Ext.data.reader.Xml
76131  * @extends Ext.data.reader.Reader
76132  * 
76133  * <p>The XML Reader is used by a Proxy to read a server response that is sent back in XML format. This usually
76134  * happens as a result of loading a Store - for example we might create something like this:</p>
76135  * 
76136 <pre><code>
76137 Ext.define('User', {
76138     extend: 'Ext.data.Model',
76139     fields: ['id', 'name', 'email']
76140 });
76141
76142 var store = new Ext.data.Store({
76143     model: 'User',
76144     proxy: {
76145         type: 'ajax',
76146         url : 'users.xml',
76147         reader: {
76148             type: 'xml',
76149             record: 'user'
76150         }
76151     }
76152 });
76153 </code></pre>
76154  * 
76155  * <p>The example above creates a 'User' model. Models are explained in the {@link Ext.data.Model Model} docs if you're
76156  * not already familiar with them.</p>
76157  * 
76158  * <p>We created the simplest type of XML Reader possible by simply telling our {@link Ext.data.Store Store}'s 
76159  * {@link Ext.data.proxy.Proxy Proxy} that we want a XML Reader. The Store automatically passes the configured model to the
76160  * Store, so it is as if we passed this instead:
76161  * 
76162 <pre><code>
76163 reader: {
76164     type : 'xml',
76165     model: 'User',
76166     record: 'user'
76167 }
76168 </code></pre>
76169  * 
76170  * <p>The reader we set up is ready to read data from our server - at the moment it will accept a response like this:</p>
76171  *
76172 <pre><code>
76173 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
76174 &lt;user&gt;
76175     &lt;id&gt;1&lt;/id&gt;
76176     &lt;name&gt;Ed Spencer&lt;/name&gt;
76177     &lt;email&gt;ed@sencha.com&lt;/email&gt;
76178 &lt;/user&gt;
76179 &lt;user&gt;
76180     &lt;id&gt;2&lt;/id&gt;
76181     &lt;name&gt;Abe Elias&lt;/name&gt;
76182     &lt;email&gt;abe@sencha.com&lt;/email&gt;
76183 &lt;/user&gt;
76184 </code></pre>
76185  * 
76186  * <p>The XML Reader uses the configured {@link #record} option to pull out the data for each record - in this case we
76187  * set record to 'user', so each &lt;user&gt; above will be converted into a User model.</p>
76188  * 
76189  * <p><u>Reading other XML formats</u></p>
76190  * 
76191  * <p>If you already have your XML format defined and it doesn't look quite like what we have above, you can usually
76192  * pass XmlReader a couple of configuration options to make it parse your format. For example, we can use the 
76193  * {@link #root} configuration to parse data that comes back like this:</p>
76194  * 
76195 <pre><code>
76196 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
76197 &lt;users&gt;
76198     &lt;user&gt;
76199         &lt;id&gt;1&lt;/id&gt;
76200         &lt;name&gt;Ed Spencer&lt;/name&gt;
76201         &lt;email&gt;ed@sencha.com&lt;/email&gt;
76202     &lt;/user&gt;
76203     &lt;user&gt;
76204         &lt;id&gt;2&lt;/id&gt;
76205         &lt;name&gt;Abe Elias&lt;/name&gt;
76206         &lt;email&gt;abe@sencha.com&lt;/email&gt;
76207     &lt;/user&gt;
76208 &lt;/users&gt;
76209 </code></pre>
76210  * 
76211  * <p>To parse this we just pass in a {@link #root} configuration that matches the 'users' above:</p>
76212  * 
76213 <pre><code>
76214 reader: {
76215     type  : 'xml',
76216     root  : 'users',
76217     record: 'user'
76218 }
76219 </code></pre>
76220  * 
76221  * <p>Note that XmlReader doesn't care whether your {@link #root} and {@link #record} elements are nested deep inside
76222  * a larger structure, so a response like this will still work:
76223  * 
76224 <pre><code>
76225 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
76226 &lt;deeply&gt;
76227     &lt;nested&gt;
76228         &lt;xml&gt;
76229             &lt;users&gt;
76230                 &lt;user&gt;
76231                     &lt;id&gt;1&lt;/id&gt;
76232                     &lt;name&gt;Ed Spencer&lt;/name&gt;
76233                     &lt;email&gt;ed@sencha.com&lt;/email&gt;
76234                 &lt;/user&gt;
76235                 &lt;user&gt;
76236                     &lt;id&gt;2&lt;/id&gt;
76237                     &lt;name&gt;Abe Elias&lt;/name&gt;
76238                     &lt;email&gt;abe@sencha.com&lt;/email&gt;
76239                 &lt;/user&gt;
76240             &lt;/users&gt;
76241         &lt;/xml&gt;
76242     &lt;/nested&gt;
76243 &lt;/deeply&gt;
76244 </code></pre>
76245  * 
76246  * <p><u>Response metadata</u></p>
76247  * 
76248  * <p>The server can return additional data in its response, such as the {@link #totalProperty total number of records} 
76249  * and the {@link #successProperty success status of the response}. These are typically included in the XML response
76250  * like this:</p>
76251  * 
76252 <pre><code>
76253 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
76254 &lt;total&gt;100&lt;/total&gt;
76255 &lt;success&gt;true&lt;/success&gt;
76256 &lt;users&gt;
76257     &lt;user&gt;
76258         &lt;id&gt;1&lt;/id&gt;
76259         &lt;name&gt;Ed Spencer&lt;/name&gt;
76260         &lt;email&gt;ed@sencha.com&lt;/email&gt;
76261     &lt;/user&gt;
76262     &lt;user&gt;
76263         &lt;id&gt;2&lt;/id&gt;
76264         &lt;name&gt;Abe Elias&lt;/name&gt;
76265         &lt;email&gt;abe@sencha.com&lt;/email&gt;
76266     &lt;/user&gt;
76267 &lt;/users&gt;
76268 </code></pre>
76269  * 
76270  * <p>If these properties are present in the XML response they can be parsed out by the XmlReader and used by the
76271  * Store that loaded it. We can set up the names of these properties by specifying a final pair of configuration 
76272  * options:</p>
76273  * 
76274 <pre><code>
76275 reader: {
76276     type: 'xml',
76277     root: 'users',
76278     totalProperty  : 'total',
76279     successProperty: 'success'
76280 }
76281 </code></pre>
76282  * 
76283  * <p>These final options are not necessary to make the Reader work, but can be useful when the server needs to report
76284  * an error or if it needs to indicate that there is a lot of data available of which only a subset is currently being
76285  * returned.</p>
76286  * 
76287  * <p><u>Response format</u></p>
76288  * 
76289  * <p><b>Note:</b> in order for the browser to parse a returned XML document, the Content-Type header in the HTTP 
76290  * response must be set to "text/xml" or "application/xml". This is very important - the XmlReader will not
76291  * work correctly otherwise.</p>
76292  */
76293 Ext.define('Ext.data.reader.Xml', {
76294     extend: 'Ext.data.reader.Reader',
76295     alternateClassName: 'Ext.data.XmlReader',
76296     alias : 'reader.xml',
76297     
76298     /**
76299      * @private
76300      * Creates a function to return some particular key of data from a response. The totalProperty and
76301      * successProperty are treated as special cases for type casting, everything else is just a simple selector.
76302      * @param {String} key
76303      * @return {Function}
76304      */
76305
76306     /**
76307      * @cfg {String} record The DomQuery path to the repeated element which contains record information.
76308      */
76309
76310     createAccessor: function() {
76311         var selectValue = function(expr, root){
76312             var node = Ext.DomQuery.selectNode(expr, root),
76313                 val;
76314                 
76315             
76316             
76317         };
76318
76319         return function(expr) {
76320             var me = this;
76321             
76322             if (Ext.isEmpty(expr)) {
76323                 return Ext.emptyFn;
76324             }
76325             
76326             if (Ext.isFunction(expr)) {
76327                 return expr;
76328             }
76329             
76330             return function(root) {
76331                 var node = Ext.DomQuery.selectNode(expr, root),
76332                     val = me.getNodeValue(node);
76333                     
76334                 return Ext.isEmpty(val) ? null : val;
76335             };
76336         };
76337     }(),
76338     
76339     getNodeValue: function(node) {
76340         var val;
76341         if (node && node.firstChild) {
76342             val = node.firstChild.nodeValue;
76343         }
76344         return val || null;
76345     },
76346
76347     //inherit docs
76348     getResponseData: function(response) {
76349         var xml = response.responseXML;
76350
76351         if (!xml) {
76352             Ext.Error.raise({
76353                 response: response,
76354                 msg: 'XML data not found in the response'
76355             });
76356         }
76357
76358         return xml;
76359     },
76360
76361     /**
76362      * Normalizes the data object
76363      * @param {Object} data The raw data object
76364      * @return {Object} Returns the documentElement property of the data object if present, or the same object if not
76365      */
76366     getData: function(data) {
76367         return data.documentElement || data;
76368     },
76369
76370     /**
76371      * @private
76372      * Given an XML object, returns the Element that represents the root as configured by the Reader's meta data
76373      * @param {Object} data The XML data object
76374      * @return {Element} The root node element
76375      */
76376     getRoot: function(data) {
76377         var nodeName = data.nodeName,
76378             root     = this.root;
76379         
76380         if (!root || (nodeName && nodeName == root)) {
76381             return data;
76382         } else if (Ext.DomQuery.isXml(data)) {
76383             // This fix ensures we have XML data
76384             // Related to TreeStore calling getRoot with the root node, which isn't XML
76385             // Probably should be resolved in TreeStore at some point
76386             return Ext.DomQuery.selectNode(root, data);
76387         }
76388     },
76389
76390     /**
76391      * @private
76392      * We're just preparing the data for the superclass by pulling out the record nodes we want
76393      * @param {Element} root The XML root node
76394      * @return {Array} The records
76395      */
76396     extractData: function(root) {
76397         var recordName = this.record;
76398         
76399         if (!recordName) {
76400             Ext.Error.raise('Record is a required parameter');
76401         }
76402         
76403         if (recordName != root.nodeName) {
76404             root = Ext.DomQuery.select(recordName, root);
76405         } else {
76406             root = [root];
76407         }
76408         return this.callParent([root]);
76409     },
76410     
76411     /**
76412      * @private
76413      * See Ext.data.reader.Reader's getAssociatedDataRoot docs
76414      * @param {Mixed} data The raw data object
76415      * @param {String} associationName The name of the association to get data for (uses associationKey if present)
76416      * @return {Mixed} The root
76417      */
76418     getAssociatedDataRoot: function(data, associationName) {
76419         return Ext.DomQuery.select(associationName, data)[0];
76420     },
76421
76422     /**
76423      * Parses an XML document and returns a ResultSet containing the model instances
76424      * @param {Object} doc Parsed XML document
76425      * @return {Ext.data.ResultSet} The parsed result set
76426      */
76427     readRecords: function(doc) {
76428         //it's possible that we get passed an array here by associations. Make sure we strip that out (see Ext.data.reader.Reader#readAssociated)
76429         if (Ext.isArray(doc)) {
76430             doc = doc[0];
76431         }
76432         
76433         /**
76434          * DEPRECATED - will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead
76435          * @property xmlData
76436          * @type Object
76437          */
76438         this.xmlData = doc;
76439         return this.callParent([doc]);
76440     }
76441 });
76442
76443 /**
76444  * @author Ed Spencer
76445  * @class Ext.data.writer.Xml
76446  * @extends Ext.data.writer.Writer
76447  * 
76448  * <p>Writer that outputs model data in XML format</p>
76449  */
76450 Ext.define('Ext.data.writer.Xml', {
76451     
76452     /* Begin Definitions */
76453     
76454     extend: 'Ext.data.writer.Writer',
76455     alternateClassName: 'Ext.data.XmlWriter',
76456     
76457     alias: 'writer.xml',
76458     
76459     /* End Definitions */
76460     
76461     /**
76462      * @cfg {String} documentRoot The name of the root element of the document. Defaults to <tt>'xmlData'</tt>.
76463      * If there is more than 1 record and the root is not specified, the default document root will still be used
76464      * to ensure a valid XML document is created.
76465      */
76466     documentRoot: 'xmlData',
76467     
76468     /**
76469      * @cfg {String} defaultDocumentRoot The root to be used if {@link #documentRoot} is empty and a root is required
76470      * to form a valid XML document.
76471      */
76472     defaultDocumentRoot: 'xmlData',
76473
76474     /**
76475      * @cfg {String} header A header to use in the XML document (such as setting the encoding or version).
76476      * Defaults to <tt>''</tt>.
76477      */
76478     header: '',
76479
76480     /**
76481      * @cfg {String} record The name of the node to use for each record. Defaults to <tt>'record'</tt>.
76482      */
76483     record: 'record',
76484
76485     //inherit docs
76486     writeRecords: function(request, data) {
76487         var me = this,
76488             xml = [],
76489             i = 0,
76490             len = data.length,
76491             root = me.documentRoot,
76492             record = me.record,
76493             needsRoot = data.length !== 1,
76494             item,
76495             key;
76496             
76497         // may not exist
76498         xml.push(me.header || '');
76499         
76500         if (!root && needsRoot) {
76501             root = me.defaultDocumentRoot;
76502         }
76503         
76504         if (root) {
76505             xml.push('<', root, '>');
76506         }
76507             
76508         for (; i < len; ++i) {
76509             item = data[i];
76510             xml.push('<', record, '>');
76511             for (key in item) {
76512                 if (item.hasOwnProperty(key)) {
76513                     xml.push('<', key, '>', item[key], '</', key, '>');
76514                 }
76515             }
76516             xml.push('</', record, '>');
76517         }
76518         
76519         if (root) {
76520             xml.push('</', root, '>');
76521         }
76522             
76523         request.xmlData = xml.join('');
76524         return request;
76525     }
76526 });
76527
76528 /**
76529  * @class Ext.direct.Event
76530  * A base class for all Ext.direct events. An event is
76531  * created after some kind of interaction with the server.
76532  * The event class is essentially just a data structure
76533  * to hold a direct response.
76534  * 
76535  * @constructor
76536  * @param {Object} config The config object
76537  */
76538 Ext.define('Ext.direct.Event', {
76539     
76540     /* Begin Definitions */
76541    
76542     alias: 'direct.event',
76543     
76544     requires: ['Ext.direct.Manager'],
76545     
76546     /* End Definitions */
76547    
76548     status: true,
76549     
76550     constructor: function(config) {
76551         Ext.apply(this, config);
76552     },
76553     
76554     /**
76555      * Return the raw data for this event.
76556      * @return {Object} The data from the event
76557      */
76558     getData: function(){
76559         return this.data;
76560     }
76561 });
76562
76563 /**
76564  * @class Ext.direct.RemotingEvent
76565  * @extends Ext.direct.Event
76566  * An event that is fired when data is received from a 
76567  * {@link Ext.direct.RemotingProvider}. Contains a method to the
76568  * related transaction for the direct request, see {@link #getTransaction}
76569  */
76570 Ext.define('Ext.direct.RemotingEvent', {
76571     
76572     /* Begin Definitions */
76573    
76574     extend: 'Ext.direct.Event',
76575     
76576     alias: 'direct.rpc',
76577     
76578     /* End Definitions */
76579     
76580     /**
76581      * Get the transaction associated with this event.
76582      * @return {Ext.direct.Transaction} The transaction
76583      */
76584     getTransaction: function(){
76585         return this.transaction || Ext.direct.Manager.getTransaction(this.tid);
76586     }
76587 });
76588
76589 /**
76590  * @class Ext.direct.ExceptionEvent
76591  * @extends Ext.direct.RemotingEvent
76592  * An event that is fired when an exception is received from a {@link Ext.direct.RemotingProvider}
76593  */
76594 Ext.define('Ext.direct.ExceptionEvent', {
76595     
76596     /* Begin Definitions */
76597    
76598     extend: 'Ext.direct.RemotingEvent',
76599     
76600     alias: 'direct.exception',
76601     
76602     /* End Definitions */
76603    
76604    status: false
76605 });
76606
76607 /**
76608  * @class Ext.direct.Provider
76609  * <p>Ext.direct.Provider is an abstract class meant to be extended.</p>
76610  * 
76611  * <p>For example ExtJs implements the following subclasses:</p>
76612  * <pre><code>
76613 Provider
76614 |
76615 +---{@link Ext.direct.JsonProvider JsonProvider} 
76616     |
76617     +---{@link Ext.direct.PollingProvider PollingProvider}   
76618     |
76619     +---{@link Ext.direct.RemotingProvider RemotingProvider}   
76620  * </code></pre>
76621  * @abstract
76622  */
76623 Ext.define('Ext.direct.Provider', {
76624     
76625     /* Begin Definitions */
76626    
76627    alias: 'direct.provider',
76628    
76629     mixins: {
76630         observable: 'Ext.util.Observable'   
76631     },
76632    
76633     /* End Definitions */
76634    
76635    /**
76636      * @cfg {String} id
76637      * The unique id of the provider (defaults to an {@link Ext#id auto-assigned id}).
76638      * You should assign an id if you need to be able to access the provider later and you do
76639      * not have an object reference available, for example:
76640      * <pre><code>
76641 Ext.direct.Manager.addProvider({
76642     type: 'polling',
76643     url:  'php/poll.php',
76644     id:   'poll-provider'
76645 });     
76646 var p = {@link Ext.direct.Manager}.{@link Ext.direct.Manager#getProvider getProvider}('poll-provider');
76647 p.disconnect();
76648      * </code></pre>
76649      */
76650     
76651     constructor : function(config){
76652         var me = this;
76653         
76654         Ext.apply(me, config);
76655         me.addEvents(
76656             /**
76657              * @event connect
76658              * Fires when the Provider connects to the server-side
76659              * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
76660              */            
76661             'connect',
76662             /**
76663              * @event disconnect
76664              * Fires when the Provider disconnects from the server-side
76665              * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
76666              */            
76667             'disconnect',
76668             /**
76669              * @event data
76670              * Fires when the Provider receives data from the server-side
76671              * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
76672              * @param {event} e The Ext.Direct.Event type that occurred.
76673              */            
76674             'data',
76675             /**
76676              * @event exception
76677              * Fires when the Provider receives an exception from the server-side
76678              */                        
76679             'exception'
76680         );
76681         me.mixins.observable.constructor.call(me, config);
76682     },
76683     
76684     /**
76685      * Returns whether or not the server-side is currently connected.
76686      * Abstract method for subclasses to implement.
76687      */
76688     isConnected: function(){
76689         return false;
76690     },
76691
76692     /**
76693      * Abstract methods for subclasses to implement.
76694      */
76695     connect: Ext.emptyFn,
76696     
76697     /**
76698      * Abstract methods for subclasses to implement.
76699      */
76700     disconnect: Ext.emptyFn
76701 });
76702
76703 /**
76704  * @class Ext.direct.JsonProvider
76705  * @extends Ext.direct.Provider
76706
76707 A base provider for communicating using JSON. This is an abstract class
76708 and should not be instanced directly.
76709
76710  * @markdown
76711  * @abstract
76712  */
76713
76714 Ext.define('Ext.direct.JsonProvider', {
76715     
76716     /* Begin Definitions */
76717     
76718     extend: 'Ext.direct.Provider',
76719     
76720     alias: 'direct.jsonprovider',
76721     
76722     uses: ['Ext.direct.ExceptionEvent'],
76723     
76724     /* End Definitions */
76725    
76726    /**
76727     * Parse the JSON response
76728     * @private
76729     * @param {Object} response The XHR response object
76730     * @return {Object} The data in the response.
76731     */
76732    parseResponse: function(response){
76733         if (!Ext.isEmpty(response.responseText)) {
76734             if (Ext.isObject(response.responseText)) {
76735                 return response.responseText;
76736             }
76737             return Ext.decode(response.responseText);
76738         }
76739         return null;
76740     },
76741
76742     /**
76743      * Creates a set of events based on the XHR response
76744      * @private
76745      * @param {Object} response The XHR response
76746      * @return {Array} An array of Ext.direct.Event
76747      */
76748     createEvents: function(response){
76749         var data = null,
76750             events = [],
76751             event,
76752             i = 0,
76753             len;
76754             
76755         try{
76756             data = this.parseResponse(response);
76757         } catch(e) {
76758             event = Ext.create('Ext.direct.ExceptionEvent', {
76759                 data: e,
76760                 xhr: response,
76761                 code: Ext.direct.Manager.self.exceptions.PARSE,
76762                 message: 'Error parsing json response: \n\n ' + data
76763             });
76764             return [event];
76765         }
76766         
76767         if (Ext.isArray(data)) {
76768             for (len = data.length; i < len; ++i) {
76769                 events.push(this.createEvent(data[i]));
76770             }
76771         } else {
76772             events.push(this.createEvent(data));
76773         }
76774         return events;
76775     },
76776     
76777     /**
76778      * Create an event from a response object
76779      * @param {Object} response The XHR response object
76780      * @return {Ext.direct.Event} The event
76781      */
76782     createEvent: function(response){
76783         return Ext.create('direct.' + response.type, response);
76784     }
76785 });
76786 /**
76787  * @class Ext.direct.PollingProvider
76788  * @extends Ext.direct.JsonProvider
76789  *
76790  * <p>Provides for repetitive polling of the server at distinct {@link #interval intervals}.
76791  * The initial request for data originates from the client, and then is responded to by the
76792  * server.</p>
76793  * 
76794  * <p>All configurations for the PollingProvider should be generated by the server-side
76795  * API portion of the Ext.Direct stack.</p>
76796  *
76797  * <p>An instance of PollingProvider may be created directly via the new keyword or by simply
76798  * specifying <tt>type = 'polling'</tt>.  For example:</p>
76799  * <pre><code>
76800 var pollA = new Ext.direct.PollingProvider({
76801     type:'polling',
76802     url: 'php/pollA.php',
76803 });
76804 Ext.direct.Manager.addProvider(pollA);
76805 pollA.disconnect();
76806
76807 Ext.direct.Manager.addProvider(
76808     {
76809         type:'polling',
76810         url: 'php/pollB.php',
76811         id: 'pollB-provider'
76812     }
76813 );
76814 var pollB = Ext.direct.Manager.getProvider('pollB-provider');
76815  * </code></pre>
76816  */
76817 Ext.define('Ext.direct.PollingProvider', {
76818     
76819     /* Begin Definitions */
76820     
76821     extend: 'Ext.direct.JsonProvider',
76822     
76823     alias: 'direct.pollingprovider',
76824     
76825     uses: ['Ext.direct.ExceptionEvent'],
76826     
76827     requires: ['Ext.Ajax', 'Ext.util.DelayedTask'],
76828     
76829     /* End Definitions */
76830     
76831     /**
76832      * @cfg {Number} interval
76833      * How often to poll the server-side in milliseconds (defaults to <tt>3000</tt> - every
76834      * 3 seconds).
76835      */
76836     interval: 3000,
76837
76838     /**
76839      * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
76840      * on every polling request
76841      */
76842     
76843     /**
76844      * @cfg {String/Function} url
76845      * The url which the PollingProvider should contact with each request. This can also be
76846      * an imported Ext.Direct method which will accept the baseParams as its only argument.
76847      */
76848
76849     // private
76850     constructor : function(config){
76851         this.callParent(arguments);
76852         this.addEvents(
76853             /**
76854              * @event beforepoll
76855              * Fired immediately before a poll takes place, an event handler can return false
76856              * in order to cancel the poll.
76857              * @param {Ext.direct.PollingProvider}
76858              */
76859             'beforepoll',            
76860             /**
76861              * @event poll
76862              * This event has not yet been implemented.
76863              * @param {Ext.direct.PollingProvider}
76864              */
76865             'poll'
76866         );
76867     },
76868
76869     // inherited
76870     isConnected: function(){
76871         return !!this.pollTask;
76872     },
76873
76874     /**
76875      * Connect to the server-side and begin the polling process. To handle each
76876      * response subscribe to the data event.
76877      */
76878     connect: function(){
76879         var me = this, url = me.url;
76880         
76881         if (url && !me.pollTask) {
76882             me.pollTask = Ext.TaskManager.start({
76883                 run: function(){
76884                     if (me.fireEvent('beforepoll', me) !== false) {
76885                         if (Ext.isFunction(url)) {
76886                             url(me.baseParams);
76887                         } else {
76888                             Ext.Ajax.request({
76889                                 url: url,
76890                                 callback: me.onData,
76891                                 scope: me,
76892                                 params: me.baseParams
76893                             });
76894                         }
76895                     }
76896                 },
76897                 interval: me.interval,
76898                 scope: me
76899             });
76900             me.fireEvent('connect', me);
76901         } else if (!url) {
76902             Ext.Error.raise('Error initializing PollingProvider, no url configured.');
76903         }
76904     },
76905
76906     /**
76907      * Disconnect from the server-side and stop the polling process. The disconnect
76908      * event will be fired on a successful disconnect.
76909      */
76910     disconnect: function(){
76911         var me = this;
76912         
76913         if (me.pollTask) {
76914             Ext.TaskManager.stop(me.pollTask);
76915             delete me.pollTask;
76916             me.fireEvent('disconnect', me);
76917         }
76918     },
76919
76920     // private
76921     onData: function(opt, success, response){
76922         var me = this, 
76923             i = 0, 
76924             len,
76925             events;
76926         
76927         if (success) {
76928             events = me.createEvents(response);
76929             for (len = events.length; i < len; ++i) {
76930                 me.fireEvent('data', me, events[i]);
76931             }
76932         } else {
76933             me.fireEvent('data', me, Ext.create('Ext.direct.ExceptionEvent', {
76934                 data: null,
76935                 code: Ext.direct.Manager.self.exceptions.TRANSPORT,
76936                 message: 'Unable to connect to the server.',
76937                 xhr: response
76938             }));
76939         }
76940     }
76941 });
76942 /**
76943  * Small utility class used internally to represent a Direct method.
76944  * Thi class is used internally.
76945  * @class Ext.direct.RemotingMethod
76946  * @ignore
76947  */
76948 Ext.define('Ext.direct.RemotingMethod', {
76949     
76950     constructor: function(config){
76951         var me = this,
76952             params = Ext.isDefined(config.params) ? config.params : config.len,
76953             name;
76954             
76955         me.name = config.name;
76956         me.formHandler = config.formHandler;
76957         if (Ext.isNumber(params)) {
76958             // given only the number of parameters
76959             me.len = params;
76960             me.ordered = true;
76961         } else {
76962             /*
76963              * Given an array of either
76964              * a) String
76965              * b) Objects with a name property. We may want to encode extra info in here later
76966              */
76967             me.params = [];
76968             Ext.each(params, function(param){
76969                 name = Ext.isObject(param) ? param.name : param;
76970                 me.params.push(name);
76971             });
76972         }
76973     },
76974     
76975     /**
76976      * Takes the arguments for the Direct function and splits the arguments
76977      * from the scope and the callback.
76978      * @param {Array} args The arguments passed to the direct call
76979      * @return {Object} An object with 3 properties, args, callback & scope.
76980      */
76981     getCallData: function(args){
76982         var me = this,
76983             data = null,
76984             len  = me.len,
76985             params = me.params,
76986             callback,
76987             scope,
76988             name;
76989             
76990         if (me.ordered) {
76991             callback = args[len];
76992             scope = args[len + 1];
76993             if (len !== 0) {
76994                 data = args.slice(0, len);
76995             }
76996         } else {
76997             data = Ext.apply({}, args[0]);
76998             callback = args[1];
76999             scope = args[2];
77000             
77001             // filter out any non-existent properties
77002             for (name in data) {
77003                 if (data.hasOwnProperty(name)) {
77004                     if (!Ext.Array.contains(params, name)) {
77005                         delete data[name];
77006                     }
77007                 }
77008             }
77009         }
77010         
77011         return {
77012             data: data,
77013             callback: callback,
77014             scope: scope    
77015         };
77016     }
77017 });
77018
77019 /**
77020  * @class Ext.direct.Transaction
77021  * @extends Object
77022  * <p>Supporting Class for Ext.Direct (not intended to be used directly).</p>
77023  * @constructor
77024  * @param {Object} config
77025  */
77026 Ext.define('Ext.direct.Transaction', {
77027     
77028     /* Begin Definitions */
77029    
77030     alias: 'direct.transaction',
77031     alternateClassName: 'Ext.Direct.Transaction',
77032    
77033     statics: {
77034         TRANSACTION_ID: 0
77035     },
77036    
77037     /* End Definitions */
77038    
77039     constructor: function(config){
77040         var me = this;
77041         
77042         Ext.apply(me, config);
77043         me.id = ++me.self.TRANSACTION_ID;
77044         me.retryCount = 0;
77045     },
77046    
77047     send: function(){
77048          this.provider.queueTransaction(this);
77049     },
77050
77051     retry: function(){
77052         this.retryCount++;
77053         this.send();
77054     },
77055
77056     getProvider: function(){
77057         return this.provider;
77058     }
77059 });
77060
77061 /**
77062  * @class Ext.direct.RemotingProvider
77063  * @extends Ext.direct.JsonProvider
77064  * 
77065  * <p>The {@link Ext.direct.RemotingProvider RemotingProvider} exposes access to
77066  * server side methods on the client (a remote procedure call (RPC) type of
77067  * connection where the client can initiate a procedure on the server).</p>
77068  * 
77069  * <p>This allows for code to be organized in a fashion that is maintainable,
77070  * while providing a clear path between client and server, something that is
77071  * not always apparent when using URLs.</p>
77072  * 
77073  * <p>To accomplish this the server-side needs to describe what classes and methods
77074  * are available on the client-side. This configuration will typically be
77075  * outputted by the server-side Ext.Direct stack when the API description is built.</p>
77076  */
77077 Ext.define('Ext.direct.RemotingProvider', {
77078     
77079     /* Begin Definitions */
77080    
77081     alias: 'direct.remotingprovider',
77082     
77083     extend: 'Ext.direct.JsonProvider', 
77084     
77085     requires: [
77086         'Ext.util.MixedCollection', 
77087         'Ext.util.DelayedTask', 
77088         'Ext.direct.Transaction',
77089         'Ext.direct.RemotingMethod'
77090     ],
77091    
77092     /* End Definitions */
77093    
77094    /**
77095      * @cfg {Object} actions
77096      * Object literal defining the server side actions and methods. For example, if
77097      * the Provider is configured with:
77098      * <pre><code>
77099 "actions":{ // each property within the 'actions' object represents a server side Class 
77100     "TestAction":[ // array of methods within each server side Class to be   
77101     {              // stubbed out on client
77102         "name":"doEcho", 
77103         "len":1            
77104     },{
77105         "name":"multiply",// name of method
77106         "len":2           // The number of parameters that will be used to create an
77107                           // array of data to send to the server side function.
77108                           // Ensure the server sends back a Number, not a String. 
77109     },{
77110         "name":"doForm",
77111         "formHandler":true, // direct the client to use specialized form handling method 
77112         "len":1
77113     }]
77114 }
77115      * </code></pre>
77116      * <p>Note that a Store is not required, a server method can be called at any time.
77117      * In the following example a <b>client side</b> handler is used to call the
77118      * server side method "multiply" in the server-side "TestAction" Class:</p>
77119      * <pre><code>
77120 TestAction.multiply(
77121     2, 4, // pass two arguments to server, so specify len=2
77122     // callback function after the server is called
77123     // result: the result returned by the server
77124     //      e: Ext.direct.RemotingEvent object
77125     function(result, e){
77126         var t = e.getTransaction();
77127         var action = t.action; // server side Class called
77128         var method = t.method; // server side method called
77129         if(e.status){
77130             var answer = Ext.encode(result); // 8
77131     
77132         }else{
77133             var msg = e.message; // failure message
77134         }
77135     }
77136 );
77137      * </code></pre>
77138      * In the example above, the server side "multiply" function will be passed two
77139      * arguments (2 and 4).  The "multiply" method should return the value 8 which will be
77140      * available as the <tt>result</tt> in the example above. 
77141      */
77142     
77143     /**
77144      * @cfg {String/Object} namespace
77145      * Namespace for the Remoting Provider (defaults to the browser global scope of <i>window</i>).
77146      * Explicitly specify the namespace Object, or specify a String to have a
77147      * {@link Ext#namespace namespace created} implicitly.
77148      */
77149     
77150     /**
77151      * @cfg {String} url
77152      * <b>Required<b>. The url to connect to the {@link Ext.direct.Manager} server-side router. 
77153      */
77154     
77155     /**
77156      * @cfg {String} enableUrlEncode
77157      * Specify which param will hold the arguments for the method.
77158      * Defaults to <tt>'data'</tt>.
77159      */
77160     
77161     /**
77162      * @cfg {Number/Boolean} enableBuffer
77163      * <p><tt>true</tt> or <tt>false</tt> to enable or disable combining of method
77164      * calls. If a number is specified this is the amount of time in milliseconds
77165      * to wait before sending a batched request (defaults to <tt>10</tt>).</p>
77166      * <br><p>Calls which are received within the specified timeframe will be
77167      * concatenated together and sent in a single request, optimizing the
77168      * application by reducing the amount of round trips that have to be made
77169      * to the server.</p>
77170      */
77171     enableBuffer: 10,
77172     
77173     /**
77174      * @cfg {Number} maxRetries
77175      * Number of times to re-attempt delivery on failure of a call. Defaults to <tt>1</tt>.
77176      */
77177     maxRetries: 1,
77178     
77179     /**
77180      * @cfg {Number} timeout
77181      * The timeout to use for each request. Defaults to <tt>undefined</tt>.
77182      */
77183     timeout: undefined,
77184     
77185     constructor : function(config){
77186         var me = this;
77187         me.callParent(arguments);
77188         me.addEvents(
77189             /**
77190              * @event beforecall
77191              * Fires immediately before the client-side sends off the RPC call.
77192              * By returning false from an event handler you can prevent the call from
77193              * executing.
77194              * @param {Ext.direct.RemotingProvider} provider
77195              * @param {Ext.direct.Transaction} transaction
77196              * @param {Object} meta The meta data
77197              */            
77198             'beforecall',            
77199             /**
77200              * @event call
77201              * Fires immediately after the request to the server-side is sent. This does
77202              * NOT fire after the response has come back from the call.
77203              * @param {Ext.direct.RemotingProvider} provider
77204              * @param {Ext.direct.Transaction} transaction
77205              * @param {Object} meta The meta data
77206              */            
77207             'call'
77208         );
77209         me.namespace = (Ext.isString(me.namespace)) ? Ext.ns(me.namespace) : me.namespace || window;
77210         me.transactions = Ext.create('Ext.util.MixedCollection');
77211         me.callBuffer = [];
77212     },
77213     
77214     /**
77215      * Initialize the API
77216      * @private
77217      */
77218     initAPI : function(){
77219         var actions = this.actions,
77220             namespace = this.namespace,
77221             action,
77222             cls,
77223             methods,
77224             i,
77225             len,
77226             method;
77227             
77228         for (action in actions) {
77229             cls = namespace[action];
77230             if (!cls) {
77231                 cls = namespace[action] = {};
77232             }
77233             methods = actions[action];
77234             
77235             for (i = 0, len = methods.length; i < len; ++i) {
77236                 method = Ext.create('Ext.direct.RemotingMethod', methods[i]);
77237                 cls[method.name] = this.createHandler(action, method);
77238             }
77239         }
77240     },
77241     
77242     /**
77243      * Create a handler function for a direct call.
77244      * @private
77245      * @param {String} action The action the call is for
77246      * @param {Object} method The details of the method
77247      * @return {Function} A JS function that will kick off the call
77248      */
77249     createHandler : function(action, method){
77250         var me = this,
77251             handler;
77252         
77253         if (!method.formHandler) {
77254             handler = function(){
77255                 me.configureRequest(action, method, Array.prototype.slice.call(arguments, 0));
77256             };
77257         } else {
77258             handler = function(form, callback, scope){
77259                 me.configureFormRequest(action, method, form, callback, scope);
77260             };
77261         }
77262         handler.directCfg = {
77263             action: action,
77264             method: method
77265         };
77266         return handler;
77267     },
77268     
77269     // inherit docs
77270     isConnected: function(){
77271         return !!this.connected;
77272     },
77273
77274     // inherit docs
77275     connect: function(){
77276         var me = this;
77277         
77278         if (me.url) {
77279             me.initAPI();
77280             me.connected = true;
77281             me.fireEvent('connect', me);
77282         } else if(!me.url) {
77283             Ext.Error.raise('Error initializing RemotingProvider, no url configured.');
77284         }
77285     },
77286
77287     // inherit docs
77288     disconnect: function(){
77289         var me = this;
77290         
77291         if (me.connected) {
77292             me.connected = false;
77293             me.fireEvent('disconnect', me);
77294         }
77295     },
77296     
77297     /**
77298      * Run any callbacks related to the transaction.
77299      * @private
77300      * @param {Ext.direct.Transaction} transaction The transaction
77301      * @param {Ext.direct.Event} event The event
77302      */
77303     runCallback: function(transaction, event){
77304         var funcName = event.status ? 'success' : 'failure',
77305             callback,
77306             result;
77307         
77308         if (transaction && transaction.callback) {
77309             callback = transaction.callback;
77310             result = Ext.isDefined(event.result) ? event.result : event.data;
77311         
77312             if (Ext.isFunction(callback)) {
77313                 callback(result, event);
77314             } else {
77315                 Ext.callback(callback[funcName], callback.scope, [result, event]);
77316                 Ext.callback(callback.callback, callback.scope, [result, event]);
77317             }
77318         }
77319     },
77320     
77321     /**
77322      * React to the ajax request being completed
77323      * @private
77324      */
77325     onData: function(options, success, response){
77326         var me = this,
77327             i = 0,
77328             len,
77329             events,
77330             event,
77331             transaction,
77332             transactions;
77333             
77334         if (success) {
77335             events = me.createEvents(response);
77336             for (len = events.length; i < len; ++i) {
77337                 event = events[i];
77338                 transaction = me.getTransaction(event);
77339                 me.fireEvent('data', me, event);
77340                 if (transaction) {
77341                     me.runCallback(transaction, event, true);
77342                     Ext.direct.Manager.removeTransaction(transaction);
77343                 }
77344             }
77345         } else {
77346             transactions = [].concat(options.transaction);
77347             for (len = transactions.length; i < len; ++i) {
77348                 transaction = me.getTransaction(transactions[i]);
77349                 if (transaction && transaction.retryCount < me.maxRetries) {
77350                     transaction.retry();
77351                 } else {
77352                     event = Ext.create('Ext.direct.ExceptionEvent', {
77353                         data: null,
77354                         transaction: transaction,
77355                         code: Ext.direct.Manager.self.exceptions.TRANSPORT,
77356                         message: 'Unable to connect to the server.',
77357                         xhr: response
77358                     });
77359                     me.fireEvent('data', me, event);
77360                     if (transaction) {
77361                         me.runCallback(transaction, event, false);
77362                         Ext.direct.Manager.removeTransaction(transaction);
77363                     }
77364                 }
77365             }
77366         }
77367     },
77368     
77369     /**
77370      * Get transaction from XHR options
77371      * @private
77372      * @param {Object} options The options sent to the Ajax request
77373      * @return {Ext.direct.Transaction} The transaction, null if not found
77374      */
77375     getTransaction: function(options){
77376         return options && options.tid ? Ext.direct.Manager.getTransaction(options.tid) : null;
77377     },
77378     
77379     /**
77380      * Configure a direct request
77381      * @private
77382      * @param {String} action The action being executed
77383      * @param {Object} method The being executed
77384      */
77385     configureRequest: function(action, method, args){
77386         var me = this,
77387             callData = method.getCallData(args),
77388             data = callData.data, 
77389             callback = callData.callback, 
77390             scope = callData.scope,
77391             transaction;
77392
77393         transaction = Ext.create('Ext.direct.Transaction', {
77394             provider: me,
77395             args: args,
77396             action: action,
77397             method: method.name,
77398             data: data,
77399             callback: scope && Ext.isFunction(callback) ? Ext.Function.bind(callback, scope) : callback
77400         });
77401
77402         if (me.fireEvent('beforecall', me, transaction, method) !== false) {
77403             Ext.direct.Manager.addTransaction(transaction);
77404             me.queueTransaction(transaction);
77405             me.fireEvent('call', me, transaction, method);
77406         }
77407     },
77408     
77409     /**
77410      * Gets the Ajax call info for a transaction
77411      * @private
77412      * @param {Ext.direct.Transaction} transaction The transaction
77413      * @return {Object} The call params
77414      */
77415     getCallData: function(transaction){
77416         return {
77417             action: transaction.action,
77418             method: transaction.method,
77419             data: transaction.data,
77420             type: 'rpc',
77421             tid: transaction.id
77422         };
77423     },
77424     
77425     /**
77426      * Sends a request to the server
77427      * @private
77428      * @param {Object/Array} data The data to send
77429      */
77430     sendRequest : function(data){
77431         var me = this,
77432             request = {
77433                 url: me.url,
77434                 callback: me.onData,
77435                 scope: me,
77436                 transaction: data,
77437                 timeout: me.timeout
77438             }, callData,
77439             enableUrlEncode = me.enableUrlEncode,
77440             i = 0,
77441             len,
77442             params;
77443             
77444
77445         if (Ext.isArray(data)) {
77446             callData = [];
77447             for (len = data.length; i < len; ++i) {
77448                 callData.push(me.getCallData(data[i]));
77449             }
77450         } else {
77451             callData = me.getCallData(data);
77452         }
77453
77454         if (enableUrlEncode) {
77455             params = {};
77456             params[Ext.isString(enableUrlEncode) ? enableUrlEncode : 'data'] = Ext.encode(callData);
77457             request.params = params;
77458         } else {
77459             request.jsonData = callData;
77460         }
77461         Ext.Ajax.request(request);
77462     },
77463     
77464     /**
77465      * Add a new transaction to the queue
77466      * @private
77467      * @param {Ext.direct.Transaction} transaction The transaction
77468      */
77469     queueTransaction: function(transaction){
77470         var me = this,
77471             enableBuffer = me.enableBuffer;
77472         
77473         if (transaction.form) {
77474             me.sendFormRequest(transaction);
77475             return;
77476         }
77477         
77478         me.callBuffer.push(transaction);
77479         if (enableBuffer) {
77480             if (!me.callTask) {
77481                 me.callTask = Ext.create('Ext.util.DelayedTask', me.combineAndSend, me);
77482             }
77483             me.callTask.delay(Ext.isNumber(enableBuffer) ? enableBuffer : 10);
77484         } else {
77485             me.combineAndSend();
77486         }
77487     },
77488     
77489     /**
77490      * Combine any buffered requests and send them off
77491      * @private
77492      */
77493     combineAndSend : function(){
77494         var buffer = this.callBuffer,
77495             len = buffer.length;
77496             
77497         if (len > 0) {
77498             this.sendRequest(len == 1 ? buffer[0] : buffer);
77499             this.callBuffer = [];
77500         }
77501     },
77502     
77503     /**
77504      * Configure a form submission request
77505      * @private
77506      * @param {String} action The action being executed
77507      * @param {Object} method The method being executed
77508      * @param {HTMLElement} form The form being submitted
77509      * @param {Function} callback (optional) A callback to run after the form submits
77510      * @param {Object} scope A scope to execute the callback in
77511      */
77512     configureFormRequest : function(action, method, form, callback, scope){
77513         var me = this,
77514             transaction = Ext.create('Ext.direct.Transaction', {
77515                 provider: me,
77516                 action: action,
77517                 method: method.name,
77518                 args: [form, callback, scope],
77519                 callback: scope && Ext.isFunction(callback) ? Ext.Function.bind(callback, scope) : callback,
77520                 isForm: true
77521             }),
77522             isUpload,
77523             params;
77524
77525         if (me.fireEvent('beforecall', me, transaction, method) !== false) {
77526             Ext.direct.Manager.addTransaction(transaction);
77527             isUpload = String(form.getAttribute("enctype")).toLowerCase() == 'multipart/form-data';
77528             
77529             params = {
77530                 extTID: transaction.id,
77531                 extAction: action,
77532                 extMethod: method.name,
77533                 extType: 'rpc',
77534                 extUpload: String(isUpload)
77535             };
77536             
77537             // change made from typeof callback check to callback.params
77538             // to support addl param passing in DirectSubmit EAC 6/2
77539             Ext.apply(transaction, {
77540                 form: Ext.getDom(form),
77541                 isUpload: isUpload,
77542                 params: callback && Ext.isObject(callback.params) ? Ext.apply(params, callback.params) : params
77543             });
77544             me.fireEvent('call', me, transaction, method);
77545             me.sendFormRequest(transaction);
77546         }
77547     },
77548     
77549     /**
77550      * Sends a form request
77551      * @private
77552      * @param {Ext.direct.Transaction} transaction The transaction to send
77553      */
77554     sendFormRequest: function(transaction){
77555         Ext.Ajax.request({
77556             url: this.url,
77557             params: transaction.params,
77558             callback: this.onData,
77559             scope: this,
77560             form: transaction.form,
77561             isUpload: transaction.isUpload,
77562             transaction: transaction
77563         });
77564     }
77565     
77566 });
77567
77568 /*
77569  * @class Ext.draw.Matrix
77570  * @private
77571  */
77572 Ext.define('Ext.draw.Matrix', {
77573
77574     /* Begin Definitions */
77575
77576     requires: ['Ext.draw.Draw'],
77577
77578     /* End Definitions */
77579
77580     constructor: function(a, b, c, d, e, f) {
77581         if (a != null) {
77582             this.matrix = [[a, c, e], [b, d, f], [0, 0, 1]];
77583         }
77584         else {
77585             this.matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
77586         }
77587     },
77588
77589     add: function(a, b, c, d, e, f) {
77590         var me = this,
77591             out = [[], [], []],
77592             matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
77593             x,
77594             y,
77595             z,
77596             res;
77597
77598         for (x = 0; x < 3; x++) {
77599             for (y = 0; y < 3; y++) {
77600                 res = 0;
77601                 for (z = 0; z < 3; z++) {
77602                     res += me.matrix[x][z] * matrix[z][y];
77603                 }
77604                 out[x][y] = res;
77605             }
77606         }
77607         me.matrix = out;
77608     },
77609
77610     prepend: function(a, b, c, d, e, f) {
77611         var me = this,
77612             out = [[], [], []],
77613             matrix = [[a, c, e], [b, d, f], [0, 0, 1]],
77614             x,
77615             y,
77616             z,
77617             res;
77618
77619         for (x = 0; x < 3; x++) {
77620             for (y = 0; y < 3; y++) {
77621                 res = 0;
77622                 for (z = 0; z < 3; z++) {
77623                     res += matrix[x][z] * me.matrix[z][y];
77624                 }
77625                 out[x][y] = res;
77626             }
77627         }
77628         me.matrix = out;
77629     },
77630
77631     invert: function() {
77632         var matrix = this.matrix,
77633             a = matrix[0][0],
77634             b = matrix[1][0],
77635             c = matrix[0][1],
77636             d = matrix[1][1],
77637             e = matrix[0][2],
77638             f = matrix[1][2],
77639             x = a * d - b * c;
77640         return new Ext.draw.Matrix(d / x, -b / x, -c / x, a / x, (c * f - d * e) / x, (b * e - a * f) / x);
77641     },
77642
77643     clone: function() {
77644         var matrix = this.matrix,
77645             a = matrix[0][0],
77646             b = matrix[1][0],
77647             c = matrix[0][1],
77648             d = matrix[1][1],
77649             e = matrix[0][2],
77650             f = matrix[1][2];
77651         return new Ext.draw.Matrix(a, b, c, d, e, f);
77652     },
77653
77654     translate: function(x, y) {
77655         this.prepend(1, 0, 0, 1, x, y);
77656     },
77657
77658     scale: function(x, y, cx, cy) {
77659         var me = this;
77660         if (y == null) {
77661             y = x;
77662         }
77663         me.add(1, 0, 0, 1, cx, cy);
77664         me.add(x, 0, 0, y, 0, 0);
77665         me.add(1, 0, 0, 1, -cx, -cy);
77666     },
77667
77668     rotate: function(a, x, y) {
77669         a = Ext.draw.Draw.rad(a);
77670         var me = this,
77671             cos = +Math.cos(a).toFixed(9),
77672             sin = +Math.sin(a).toFixed(9);
77673         me.add(cos, sin, -sin, cos, x, y);
77674         me.add(1, 0, 0, 1, -x, -y);
77675     },
77676
77677     x: function(x, y) {
77678         var matrix = this.matrix;
77679         return x * matrix[0][0] + y * matrix[0][1] + matrix[0][2];
77680     },
77681
77682     y: function(x, y) {
77683         var matrix = this.matrix;
77684         return x * matrix[1][0] + y * matrix[1][1] + matrix[1][2];
77685     },
77686
77687     get: function(i, j) {
77688         return + this.matrix[i][j].toFixed(4);
77689     },
77690
77691     toString: function() {
77692         var me = this;
77693         return [me.get(0, 0), me.get(0, 1), me.get(1, 0), me.get(1, 1), 0, 0].join();
77694     },
77695
77696     toSvg: function() {
77697         var me = this;
77698         return "matrix(" + [me.get(0, 0), me.get(1, 0), me.get(0, 1), me.get(1, 1), me.get(0, 2), me.get(1, 2)].join() + ")";
77699     },
77700
77701     toFilter: function() {
77702         var me = this;
77703         return "progid:DXImageTransform.Microsoft.Matrix(M11=" + me.get(0, 0) +
77704             ", M12=" + me.get(0, 1) + ", M21=" + me.get(1, 0) + ", M22=" + me.get(1, 1) +
77705             ", Dx=" + me.get(0, 2) + ", Dy=" + me.get(1, 2) + ")";
77706     },
77707
77708     offset: function() {
77709         var matrix = this.matrix;
77710         return [matrix[0][2].toFixed(4), matrix[1][2].toFixed(4)];
77711     },
77712
77713     // Split matrix into Translate Scale, Shear, and Rotate
77714     split: function () {
77715         function norm(a) {
77716             return a[0] * a[0] + a[1] * a[1];
77717         }
77718         function normalize(a) {
77719             var mag = Math.sqrt(norm(a));
77720             a[0] /= mag;
77721             a[1] /= mag;
77722         }
77723         var matrix = this.matrix,
77724             out = {
77725                 translateX: matrix[0][2],
77726                 translateY: matrix[1][2]
77727             },
77728             row;
77729
77730         // scale and shear
77731         row = [[matrix[0][0], matrix[0][1]], [matrix[1][1], matrix[1][1]]];
77732         out.scaleX = Math.sqrt(norm(row[0]));
77733         normalize(row[0]);
77734
77735         out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
77736         row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
77737
77738         out.scaleY = Math.sqrt(norm(row[1]));
77739         normalize(row[1]);
77740         out.shear /= out.scaleY;
77741
77742         // rotation
77743         out.rotate = Math.asin(-row[0][1]);
77744
77745         out.isSimple = !+out.shear.toFixed(9) && (out.scaleX.toFixed(9) == out.scaleY.toFixed(9) || !out.rotate);
77746
77747         return out;
77748     }
77749 });
77750 // private - DD implementation for Panels
77751 Ext.define('Ext.draw.SpriteDD', {
77752     extend: 'Ext.dd.DragSource',
77753
77754     constructor : function(sprite, cfg){
77755         var me = this,
77756             el = sprite.el;
77757         me.sprite = sprite;
77758         me.el = el;
77759         me.dragData = {el: el, sprite: sprite};
77760         me.callParent([el, cfg]);
77761         me.sprite.setStyle('cursor', 'move');
77762     },
77763
77764     showFrame: Ext.emptyFn,
77765     createFrame : Ext.emptyFn,
77766
77767     getDragEl : function(e){
77768         return this.el;
77769     },
77770     
77771     getRegion: function() {
77772         var me = this,
77773             el = me.el,
77774             pos, x1, x2, y1, y2, t, r, b, l, bbox, sprite;
77775         
77776         sprite = me.sprite;
77777         bbox = sprite.getBBox();
77778         
77779         try {
77780             pos = Ext.core.Element.getXY(el);
77781         } catch (e) { }
77782
77783         if (!pos) {
77784             return null;
77785         }
77786
77787         x1 = pos[0];
77788         x2 = x1 + bbox.width;
77789         y1 = pos[1];
77790         y2 = y1 + bbox.height;
77791         
77792         return Ext.create('Ext.util.Region', y1, x2, y2, x1);
77793     },
77794
77795     /*
77796       TODO(nico): Cumulative translations in VML are handled
77797       differently than in SVG. While in SVG we specify the translation
77798       relative to the original x, y position attributes, in VML the translation
77799       is a delta between the last position of the object (modified by the last
77800       translation) and the new one.
77801       
77802       In VML the translation alters the position
77803       of the object, we should change that or alter the SVG impl.
77804     */
77805      
77806     startDrag: function(x, y) {
77807         var me = this,
77808             attr = me.sprite.attr,
77809             trans = attr.translation;
77810         if (me.sprite.vml) {
77811             me.prevX = x + attr.x;
77812             me.prevY = y + attr.y;
77813         } else {
77814             me.prevX = x - trans.x;
77815             me.prevY = y - trans.y;
77816         }
77817     },
77818
77819     onDrag: function(e) {
77820         var xy = e.getXY(),
77821             me = this,
77822             sprite = me.sprite,
77823             attr = sprite.attr;
77824         me.translateX = xy[0] - me.prevX;
77825         me.translateY = xy[1] - me.prevY;
77826         sprite.setAttributes({
77827             translate: {
77828                 x: me.translateX,
77829                 y: me.translateY
77830             }
77831         }, true);
77832         if (sprite.vml) {
77833             me.prevX = xy[0] + attr.x || 0;
77834             me.prevY = xy[1] + attr.y || 0;
77835         }
77836     }
77837 });
77838 /**
77839  * @class Ext.draw.Sprite
77840  * @extends Object
77841  *
77842  * A Sprite is an object rendered in a Drawing surface. There are different options and types of sprites.
77843  * The configuration of a Sprite is an object with the following properties:
77844  *
77845  * - **type** - (String) The type of the sprite. Possible options are 'circle', 'path', 'rect', 'text', 'square'. 
77846  * - **width** - (Number) Used in rectangle sprites, the width of the rectangle.
77847  * - **height** - (Number) Used in rectangle sprites, the height of the rectangle.
77848  * - **size** - (Number) Used in square sprites, the dimension of the square.
77849  * - **radius** - (Number) Used in circle sprites, the radius of the circle.
77850  * - **x** - (Number) The position along the x-axis.
77851  * - **y** - (Number) The position along the y-axis.
77852  * - **path** - (Array) Used in path sprites, the path of the sprite written in SVG-like path syntax.
77853  * - **opacity** - (Number) The opacity of the sprite.
77854  * - **fill** - (String) The fill color.
77855  * - **stroke** - (String) The stroke color.
77856  * - **stroke-width** - (Number) The width of the stroke.
77857  * - **font** - (String) Used with text type sprites. The full font description. Uses the same syntax as the CSS `font` parameter.
77858  * - **text** - (String) Used with text type sprites. The text itself.
77859  * 
77860  * Additionally there are three transform objects that can be set with `setAttributes` which are `translate`, `rotate` and
77861  * `scale`.
77862  * 
77863  * For translate, the configuration object contains x and y attributes that indicate where to
77864  * translate the object. For example:
77865  * 
77866  *     sprite.setAttributes({
77867  *       translate: {
77868  *        x: 10,
77869  *        y: 10
77870  *       }
77871  *     }, true);
77872  * 
77873  * For rotation, the configuration object contains x and y attributes for the center of the rotation (which are optional),
77874  * and a `degrees` attribute that specifies the rotation in degrees. For example:
77875  * 
77876  *     sprite.setAttributes({
77877  *       rotate: {
77878  *        degrees: 90
77879  *       }
77880  *     }, true);
77881  * 
77882  * For scaling, the configuration object contains x and y attributes for the x-axis and y-axis scaling. For example:
77883  * 
77884  *     sprite.setAttributes({
77885  *       scale: {
77886  *        x: 10,
77887  *        y: 3
77888  *       }
77889  *     }, true);
77890  *
77891  * Sprites can be created with a reference to a {@link Ext.draw.Surface}
77892  *
77893  *      var drawComponent = Ext.create('Ext.draw.Component', options here...);
77894  *
77895  *      var sprite = Ext.create('Ext.draw.Sprite', {
77896  *          type: 'circle',
77897  *          fill: '#ff0',
77898  *          surface: drawComponent.surface,
77899  *          radius: 5
77900  *      });
77901  *
77902  * Sprites can also be added to the surface as a configuration object:
77903  *
77904  *      var sprite = drawComponent.surface.add({
77905  *          type: 'circle',
77906  *          fill: '#ff0',
77907  *          radius: 5
77908  *      });
77909  *
77910  * In order to properly apply properties and render the sprite we have to
77911  * `show` the sprite setting the option `redraw` to `true`:
77912  *
77913  *      sprite.show(true);
77914  *
77915  * The constructor configuration object of the Sprite can also be used and passed into the {@link Ext.draw.Surface}
77916  * add method to append a new sprite to the canvas. For example:
77917  *
77918  *     drawComponent.surface.add({
77919  *         type: 'circle',
77920  *         fill: '#ffc',
77921  *         radius: 100,
77922  *         x: 100,
77923  *         y: 100
77924  *     });
77925  */
77926 Ext.define('Ext.draw.Sprite', {
77927     /* Begin Definitions */
77928
77929     mixins: {
77930         observable: 'Ext.util.Observable',
77931         animate: 'Ext.util.Animate'
77932     },
77933
77934     requires: ['Ext.draw.SpriteDD'],
77935
77936     /* End Definitions */
77937
77938     dirty: false,
77939     dirtyHidden: false,
77940     dirtyTransform: false,
77941     dirtyPath: true,
77942     dirtyFont: true,
77943     zIndexDirty: true,
77944     isSprite: true,
77945     zIndex: 0,
77946     fontProperties: [
77947         'font',
77948         'font-size',
77949         'font-weight',
77950         'font-style',
77951         'font-family',
77952         'text-anchor',
77953         'text'
77954     ],
77955     pathProperties: [
77956         'x',
77957         'y',
77958         'd',
77959         'path',
77960         'height',
77961         'width',
77962         'radius',
77963         'r',
77964         'rx',
77965         'ry',
77966         'cx',
77967         'cy'
77968     ],
77969     constructor: function(config) {
77970         var me = this;
77971         config = config || {};
77972         me.id = Ext.id(null, 'ext-sprite-');
77973         me.transformations = [];
77974         Ext.copyTo(this, config, 'surface,group,type,draggable');
77975         //attribute bucket
77976         me.bbox = {};
77977         me.attr = {
77978             zIndex: 0,
77979             translation: {
77980                 x: null,
77981                 y: null
77982             },
77983             rotation: {
77984                 degrees: null,
77985                 x: null,
77986                 y: null
77987             },
77988             scaling: {
77989                 x: null,
77990                 y: null,
77991                 cx: null,
77992                 cy: null
77993             }
77994         };
77995         //delete not bucket attributes
77996         delete config.surface;
77997         delete config.group;
77998         delete config.type;
77999         delete config.draggable;
78000         me.setAttributes(config);
78001         me.addEvents(
78002             'beforedestroy',
78003             'destroy',
78004             'render',
78005             'mousedown',
78006             'mouseup',
78007             'mouseover',
78008             'mouseout',
78009             'mousemove',
78010             'click'
78011         );
78012         me.mixins.observable.constructor.apply(this, arguments);
78013     },
78014
78015     /**
78016      * <p>If this Sprite is configured {@link #draggable}, this property will contain
78017      * an instance of {@link Ext.dd.DragSource} which handles dragging the Sprite.</p>
78018      * The developer must provide implementations of the abstract methods of {@link Ext.dd.DragSource}
78019      * in order to supply behaviour for each stage of the drag/drop process. See {@link #draggable}.
78020      * @type Ext.dd.DragSource.
78021      * @property dd
78022      */
78023     initDraggable: function() {
78024         var me = this;
78025         me.draggable = true;
78026         //create element if it doesn't exist.
78027         if (!me.el) {
78028             me.surface.createSprite(me);
78029         }
78030         me.dd = Ext.create('Ext.draw.SpriteDD', me, Ext.isBoolean(me.draggable) ? null : me.draggable);
78031         me.on('beforedestroy', me.dd.destroy, me.dd);
78032     },
78033
78034     /**
78035      * Change the attributes of the sprite.
78036      * @param {Object} attrs attributes to be changed on the sprite.
78037      * @param {Boolean} redraw Flag to immediatly draw the change.
78038      * @return {Ext.draw.Sprite} this
78039      */
78040     setAttributes: function(attrs, redraw) {
78041         var me = this,
78042             fontProps = me.fontProperties,
78043             fontPropsLength = fontProps.length,
78044             pathProps = me.pathProperties,
78045             pathPropsLength = pathProps.length,
78046             hasSurface = !!me.surface,
78047             custom = hasSurface && me.surface.customAttributes || {},
78048             spriteAttrs = me.attr,
78049             attr, i, translate, translation, rotate, rotation, scale, scaling;
78050
78051         for (attr in custom) {
78052             if (attrs.hasOwnProperty(attr) && typeof custom[attr] == "function") {
78053                 Ext.apply(attrs, custom[attr].apply(me, [].concat(attrs[attr])));
78054             }
78055         }
78056
78057         // Flag a change in hidden
78058         if (!!attrs.hidden !== !!spriteAttrs.hidden) {
78059             me.dirtyHidden = true;
78060         }
78061
78062         // Flag path change
78063         for (i = 0; i < pathPropsLength; i++) {
78064             attr = pathProps[i];
78065             if (attr in attrs && attrs[attr] !== spriteAttrs[attr]) {
78066                 me.dirtyPath = true;
78067                 break;
78068             }
78069         }
78070
78071         // Flag zIndex change
78072         if ('zIndex' in attrs) {
78073             me.zIndexDirty = true;
78074         }
78075
78076         // Flag font/text change
78077         for (i = 0; i < fontPropsLength; i++) {
78078             attr = fontProps[i];
78079             if (attr in attrs && attrs[attr] !== spriteAttrs[attr]) {
78080                 me.dirtyFont = true;
78081                 break;
78082             }
78083         }
78084
78085         translate = attrs.translate;
78086         translation = spriteAttrs.translation;
78087         if (translate) {
78088             if ((translate.x && translate.x !== translation.x) ||
78089                 (translate.y && translate.y !== translation.y)) {
78090                 Ext.apply(translation, translate);
78091                 me.dirtyTransform = true;
78092             }
78093             delete attrs.translate;
78094         }
78095
78096         rotate = attrs.rotate;
78097         rotation = spriteAttrs.rotation;
78098         if (rotate) {
78099             if ((rotate.x && rotate.x !== rotation.x) || 
78100                 (rotate.y && rotate.y !== rotation.y) ||
78101                 (rotate.degrees && rotate.degrees !== rotation.degrees)) {
78102                 Ext.apply(rotation, rotate);
78103                 me.dirtyTransform = true;
78104             }
78105             delete attrs.rotate;
78106         }
78107
78108         scale = attrs.scale;
78109         scaling = spriteAttrs.scaling;
78110         if (scale) {
78111             if ((scale.x && scale.x !== scaling.x) || 
78112                 (scale.y && scale.y !== scaling.y) ||
78113                 (scale.cx && scale.cx !== scaling.cx) ||
78114                 (scale.cy && scale.cy !== scaling.cy)) {
78115                 Ext.apply(scaling, scale);
78116                 me.dirtyTransform = true;
78117             }
78118             delete attrs.scale;
78119         }
78120
78121         Ext.apply(spriteAttrs, attrs);
78122         me.dirty = true;
78123
78124         if (redraw === true && hasSurface) {
78125             me.redraw();
78126         }
78127         return this;
78128     },
78129
78130     /**
78131      * Retrieve the bounding box of the sprite. This will be returned as an object with x, y, width, and height properties.
78132      * @return {Object} bbox
78133      */
78134     getBBox: function() {
78135         return this.surface.getBBox(this);
78136     },
78137     
78138     setText: function(text) {
78139         return this.surface.setText(this, text);
78140     },
78141
78142     /**
78143      * Hide the sprite.
78144      * @param {Boolean} redraw Flag to immediatly draw the change.
78145      * @return {Ext.draw.Sprite} this
78146      */
78147     hide: function(redraw) {
78148         this.setAttributes({
78149             hidden: true
78150         }, redraw);
78151         return this;
78152     },
78153
78154     /**
78155      * Show the sprite.
78156      * @param {Boolean} redraw Flag to immediatly draw the change.
78157      * @return {Ext.draw.Sprite} this
78158      */
78159     show: function(redraw) {
78160         this.setAttributes({
78161             hidden: false
78162         }, redraw);
78163         return this;
78164     },
78165
78166     /**
78167      * Remove the sprite.
78168      */
78169     remove: function() {
78170         if (this.surface) {
78171             this.surface.remove(this);
78172             return true;
78173         }
78174         return false;
78175     },
78176
78177     onRemove: function() {
78178         this.surface.onRemove(this);
78179     },
78180
78181     /**
78182      * Removes the sprite and clears all listeners.
78183      */
78184     destroy: function() {
78185         var me = this;
78186         if (me.fireEvent('beforedestroy', me) !== false) {
78187             me.remove();
78188             me.surface.onDestroy(me);
78189             me.clearListeners();
78190             me.fireEvent('destroy');
78191         }
78192     },
78193
78194     /**
78195      * Redraw the sprite.
78196      * @return {Ext.draw.Sprite} this
78197      */
78198     redraw: function() {
78199         this.surface.renderItem(this);
78200         return this;
78201     },
78202
78203     /**
78204      * Wrapper for setting style properties, also takes single object parameter of multiple styles.
78205      * @param {String/Object} property The style property to be set, or an object of multiple styles.
78206      * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
78207      * @return {Ext.draw.Sprite} this
78208      */
78209     setStyle: function() {
78210         this.el.setStyle.apply(this.el, arguments);
78211         return this;
78212     },
78213
78214     /**
78215      * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.  Note this method
78216      * is severly limited in VML.
78217      * @param {String/Array} className The CSS class to add, or an array of classes
78218      * @return {Ext.draw.Sprite} this
78219      */
78220     addCls: function(obj) {
78221         this.surface.addCls(this, obj);
78222         return this;
78223     },
78224
78225     /**
78226      * Removes one or more CSS classes from the element.
78227      * @param {String/Array} className The CSS class to remove, or an array of classes.  Note this method
78228      * is severly limited in VML.
78229      * @return {Ext.draw.Sprite} this
78230      */
78231     removeCls: function(obj) {
78232         this.surface.removeCls(this, obj);
78233         return this;
78234     }
78235 });
78236
78237 /**
78238  * @class Ext.draw.engine.Svg
78239  * @extends Ext.draw.Surface
78240  * Provides specific methods to draw with SVG.
78241  */
78242 Ext.define('Ext.draw.engine.Svg', {
78243
78244     /* Begin Definitions */
78245
78246     extend: 'Ext.draw.Surface',
78247
78248     requires: ['Ext.draw.Draw', 'Ext.draw.Sprite', 'Ext.draw.Matrix', 'Ext.core.Element'],
78249
78250     /* End Definitions */
78251
78252     engine: 'Svg',
78253
78254     trimRe: /^\s+|\s+$/g,
78255     spacesRe: /\s+/,
78256     xlink: "http:/" + "/www.w3.org/1999/xlink",
78257
78258     translateAttrs: {
78259         radius: "r",
78260         radiusX: "rx",
78261         radiusY: "ry",
78262         path: "d",
78263         lineWidth: "stroke-width",
78264         fillOpacity: "fill-opacity",
78265         strokeOpacity: "stroke-opacity",
78266         strokeLinejoin: "stroke-linejoin"
78267     },
78268
78269     minDefaults: {
78270         circle: {
78271             cx: 0,
78272             cy: 0,
78273             r: 0,
78274             fill: "none",
78275             stroke: null,
78276             "stroke-width": null,
78277             opacity: null,
78278             "fill-opacity": null,
78279             "stroke-opacity": null
78280         },
78281         ellipse: {
78282             cx: 0,
78283             cy: 0,
78284             rx: 0,
78285             ry: 0,
78286             fill: "none",
78287             stroke: null,
78288             "stroke-width": null,
78289             opacity: null,
78290             "fill-opacity": null,
78291             "stroke-opacity": null
78292         },
78293         rect: {
78294             x: 0,
78295             y: 0,
78296             width: 0,
78297             height: 0,
78298             rx: 0,
78299             ry: 0,
78300             fill: "none",
78301             stroke: null,
78302             "stroke-width": null,
78303             opacity: null,
78304             "fill-opacity": null,
78305             "stroke-opacity": null
78306         },
78307         text: {
78308             x: 0,
78309             y: 0,
78310             "text-anchor": "start",
78311             "font-family": null,
78312             "font-size": null,
78313             "font-weight": null,
78314             "font-style": null,
78315             fill: "#000",
78316             stroke: null,
78317             "stroke-width": null,
78318             opacity: null,
78319             "fill-opacity": null,
78320             "stroke-opacity": null
78321         },
78322         path: {
78323             d: "M0,0",
78324             fill: "none",
78325             stroke: null,
78326             "stroke-width": null,
78327             opacity: null,
78328             "fill-opacity": null,
78329             "stroke-opacity": null
78330         },
78331         image: {
78332             x: 0,
78333             y: 0,
78334             width: 0,
78335             height: 0,
78336             preserveAspectRatio: "none",
78337             opacity: null
78338         }
78339     },
78340
78341     createSvgElement: function(type, attrs) {
78342         var el = this.domRef.createElementNS("http:/" + "/www.w3.org/2000/svg", type),
78343             key;
78344         if (attrs) {
78345             for (key in attrs) {
78346                 el.setAttribute(key, String(attrs[key]));
78347             }
78348         }
78349         return el;
78350     },
78351
78352     createSpriteElement: function(sprite) {
78353         // Create svg element and append to the DOM.
78354         var el = this.createSvgElement(sprite.type);
78355         el.id = sprite.id;
78356         if (el.style) {
78357             el.style.webkitTapHighlightColor = "rgba(0,0,0,0)";
78358         }
78359         sprite.el = Ext.get(el);
78360         this.applyZIndex(sprite); //performs the insertion
78361         sprite.matrix = Ext.create('Ext.draw.Matrix');
78362         sprite.bbox = {
78363             plain: 0,
78364             transform: 0
78365         };
78366         sprite.fireEvent("render", sprite);
78367         return el;
78368     },
78369
78370     getBBox: function (sprite, isWithoutTransform) {
78371         var realPath = this["getPath" + sprite.type](sprite);
78372         if (isWithoutTransform) {
78373             sprite.bbox.plain = sprite.bbox.plain || Ext.draw.Draw.pathDimensions(realPath);
78374             return sprite.bbox.plain;
78375         }
78376         sprite.bbox.transform = sprite.bbox.transform || Ext.draw.Draw.pathDimensions(Ext.draw.Draw.mapPath(realPath, sprite.matrix));
78377         return sprite.bbox.transform;
78378     },
78379     
78380     getBBoxText: function (sprite) {
78381         var bbox = {},
78382             bb, height, width, i, ln, el;
78383
78384         if (sprite && sprite.el) {
78385             el = sprite.el.dom;
78386             try {
78387                 bbox = el.getBBox();
78388                 return bbox;
78389             } catch(e) {
78390                 // Firefox 3.0.x plays badly here
78391             }
78392             bbox = {x: bbox.x, y: Infinity, width: 0, height: 0};
78393             ln = el.getNumberOfChars();
78394             for (i = 0; i < ln; i++) {
78395                 bb = el.getExtentOfChar(i);
78396                 bbox.y = Math.min(bb.y, bbox.y);
78397                 height = bb.y + bb.height - bbox.y;
78398                 bbox.height = Math.max(bbox.height, height);
78399                 width = bb.x + bb.width - bbox.x;
78400                 bbox.width = Math.max(bbox.width, width);
78401             }
78402             return bbox;
78403         }
78404     },
78405
78406     hide: function() {
78407         Ext.get(this.el).hide();
78408     },
78409
78410     show: function() {
78411         Ext.get(this.el).show();
78412     },
78413
78414     hidePrim: function(sprite) {
78415         this.addCls(sprite, Ext.baseCSSPrefix + 'hide-visibility');
78416     },
78417
78418     showPrim: function(sprite) {
78419         this.removeCls(sprite, Ext.baseCSSPrefix + 'hide-visibility');
78420     },
78421
78422     getDefs: function() {
78423         return this._defs || (this._defs = this.createSvgElement("defs"));
78424     },
78425
78426     transform: function(sprite) {
78427         var me = this,
78428             matrix = Ext.create('Ext.draw.Matrix'),
78429             transforms = sprite.transformations,
78430             transformsLength = transforms.length,
78431             i = 0,
78432             transform, type;
78433             
78434         for (; i < transformsLength; i++) {
78435             transform = transforms[i];
78436             type = transform.type;
78437             if (type == "translate") {
78438                 matrix.translate(transform.x, transform.y);
78439             }
78440             else if (type == "rotate") {
78441                 matrix.rotate(transform.degrees, transform.x, transform.y);
78442             }
78443             else if (type == "scale") {
78444                 matrix.scale(transform.x, transform.y, transform.centerX, transform.centerY);
78445             }
78446         }
78447         sprite.matrix = matrix;
78448         sprite.el.set({transform: matrix.toSvg()});
78449     },
78450
78451     setSize: function(w, h) {
78452         var me = this,
78453             el = me.el;
78454         
78455         w = +w || me.width;
78456         h = +h || me.height;
78457         me.width = w;
78458         me.height = h;
78459
78460         el.setSize(w, h);
78461         el.set({
78462             width: w,
78463             height: h
78464         });
78465         me.callParent([w, h]);
78466     },
78467
78468     /**
78469      * Get the region for the surface's canvas area
78470      * @returns {Ext.util.Region}
78471      */
78472     getRegion: function() {
78473         // Mozilla requires using the background rect because the svg element returns an
78474         // incorrect region. Webkit gives no region for the rect and must use the svg element.
78475         var svgXY = this.el.getXY(),
78476             rectXY = this.bgRect.getXY(),
78477             max = Math.max,
78478             x = max(svgXY[0], rectXY[0]),
78479             y = max(svgXY[1], rectXY[1]);
78480         return {
78481             left: x,
78482             top: y,
78483             right: x + this.width,
78484             bottom: y + this.height
78485         };
78486     },
78487
78488     onRemove: function(sprite) {
78489         if (sprite.el) {
78490             sprite.el.remove();
78491             delete sprite.el;
78492         }
78493         this.callParent(arguments);
78494     },
78495     
78496     setViewBox: function(x, y, width, height) {
78497         if (isFinite(x) && isFinite(y) && isFinite(width) && isFinite(height)) {
78498             this.callParent(arguments);
78499             this.el.dom.setAttribute("viewBox", [x, y, width, height].join(" "));
78500         }
78501     },
78502
78503     render: function (container) {
78504         var me = this;
78505         if (!me.el) {
78506             var width = me.width || 10,
78507                 height = me.height || 10,
78508                 el = me.createSvgElement('svg', {
78509                     xmlns: "http:/" + "/www.w3.org/2000/svg",
78510                     version: 1.1,
78511                     width: width,
78512                     height: height
78513                 }),
78514                 defs = me.getDefs(),
78515
78516                 // Create a rect that is always the same size as the svg root; this serves 2 purposes:
78517                 // (1) It allows mouse events to be fired over empty areas in Webkit, and (2) we can
78518                 // use it rather than the svg element for retrieving the correct client rect of the
78519                 // surface in Mozilla (see https://bugzilla.mozilla.org/show_bug.cgi?id=530985)
78520                 bgRect = me.createSvgElement("rect", {
78521                     width: "100%",
78522                     height: "100%",
78523                     fill: "#000",
78524                     stroke: "none",
78525                     opacity: 0
78526                 }),
78527                 webkitRect;
78528             
78529                 if (Ext.isSafari3) {
78530                     // Rect that we will show/hide to fix old WebKit bug with rendering issues.
78531                     webkitRect = me.createSvgElement("rect", {
78532                         x: -10,
78533                         y: -10,
78534                         width: "110%",
78535                         height: "110%",
78536                         fill: "none",
78537                         stroke: "#000"
78538                     });
78539                 }
78540             el.appendChild(defs);
78541             if (Ext.isSafari3) {
78542                 el.appendChild(webkitRect);
78543             }
78544             el.appendChild(bgRect);
78545             container.appendChild(el);
78546             me.el = Ext.get(el);
78547             me.bgRect = Ext.get(bgRect);
78548             if (Ext.isSafari3) {
78549                 me.webkitRect = Ext.get(webkitRect);
78550                 me.webkitRect.hide();
78551             }
78552             me.el.on({
78553                 scope: me,
78554                 mouseup: me.onMouseUp,
78555                 mousedown: me.onMouseDown,
78556                 mouseover: me.onMouseOver,
78557                 mouseout: me.onMouseOut,
78558                 mousemove: me.onMouseMove,
78559                 mouseenter: me.onMouseEnter,
78560                 mouseleave: me.onMouseLeave,
78561                 click: me.onClick
78562             });
78563         }
78564         me.renderAll();
78565     },
78566
78567     // private
78568     onMouseEnter: function(e) {
78569         if (this.el.parent().getRegion().contains(e.getPoint())) {
78570             this.fireEvent('mouseenter', e);
78571         }
78572     },
78573
78574     // private
78575     onMouseLeave: function(e) {
78576         if (!this.el.parent().getRegion().contains(e.getPoint())) {
78577             this.fireEvent('mouseleave', e);
78578         }
78579     },
78580     // @private - Normalize a delegated single event from the main container to each sprite and sprite group
78581     processEvent: function(name, e) {
78582         var target = e.getTarget(),
78583             surface = this.surface,
78584             sprite;
78585
78586         this.fireEvent(name, e);
78587         // We wrap text types in a tspan, sprite is the parent.
78588         if (target.nodeName == "tspan" && target.parentNode) {
78589             target = target.parentNode;
78590         }
78591         sprite = this.items.get(target.id);
78592         if (sprite) {
78593             sprite.fireEvent(name, sprite, e);
78594         }
78595     },
78596
78597     /* @private - Wrap SVG text inside a tspan to allow for line wrapping.  In addition this normallizes
78598      * the baseline for text the vertical middle of the text to be the same as VML.
78599      */
78600     tuneText: function (sprite, attrs) {
78601         var el = sprite.el.dom,
78602             tspans = [],
78603             height, tspan, text, i, ln, texts, factor;
78604
78605         if (attrs.hasOwnProperty("text")) {
78606            tspans = this.setText(sprite, attrs.text);
78607         }
78608         // Normalize baseline via a DY shift of first tspan. Shift other rows by height * line height (1.2)
78609         if (tspans.length) {
78610             height = this.getBBoxText(sprite).height;
78611             for (i = 0, ln = tspans.length; i < ln; i++) {
78612                 // The text baseline for FireFox 3.0 and 3.5 is different than other SVG implementations
78613                 // so we are going to normalize that here
78614                 factor = (Ext.isFF3_0 || Ext.isFF3_5) ? 2 : 4;
78615                 tspans[i].setAttribute("dy", i ? height * 1.2 : height / factor);
78616             }
78617             sprite.dirty = true;
78618         }
78619     },
78620
78621     setText: function(sprite, textString) {
78622          var me = this,
78623              el = sprite.el.dom,
78624              x = el.getAttribute("x"),
78625              tspans = [],
78626              height, tspan, text, i, ln, texts;
78627         
78628         while (el.firstChild) {
78629             el.removeChild(el.firstChild);
78630         }
78631         // Wrap each row into tspan to emulate rows
78632         texts = String(textString).split("\n");
78633         for (i = 0, ln = texts.length; i < ln; i++) {
78634             text = texts[i];
78635             if (text) {
78636                 tspan = me.createSvgElement("tspan");
78637                 tspan.appendChild(document.createTextNode(Ext.htmlDecode(text)));
78638                 tspan.setAttribute("x", x);
78639                 el.appendChild(tspan);
78640                 tspans[i] = tspan;
78641             }
78642         }
78643         return tspans;
78644     },
78645
78646     renderAll: function() {
78647         this.items.each(this.renderItem, this);
78648     },
78649
78650     renderItem: function (sprite) {
78651         if (!this.el) {
78652             return;
78653         }
78654         if (!sprite.el) {
78655             this.createSpriteElement(sprite);
78656         }
78657         if (sprite.zIndexDirty) {
78658             this.applyZIndex(sprite);
78659         }
78660         if (sprite.dirty) {
78661             this.applyAttrs(sprite);
78662             this.applyTransformations(sprite);
78663         }
78664     },
78665
78666     redraw: function(sprite) {
78667         sprite.dirty = sprite.zIndexDirty = true;
78668         this.renderItem(sprite);
78669     },
78670
78671     applyAttrs: function (sprite) {
78672         var me = this,
78673             el = sprite.el,
78674             group = sprite.group,
78675             sattr = sprite.attr,
78676             groups, i, ln, attrs, font, key, style, name, rect;
78677
78678         if (group) {
78679             groups = [].concat(group);
78680             ln = groups.length;
78681             for (i = 0; i < ln; i++) {
78682                 group = groups[i];
78683                 me.getGroup(group).add(sprite);
78684             }
78685             delete sprite.group;
78686         }
78687         attrs = me.scrubAttrs(sprite) || {};
78688
78689         // if (sprite.dirtyPath) {
78690         sprite.bbox.plain = 0;
78691         sprite.bbox.transform = 0;
78692             if (sprite.type == "circle" || sprite.type == "ellipse") {
78693                 attrs.cx = attrs.cx || attrs.x;
78694                 attrs.cy = attrs.cy || attrs.y;
78695             }
78696             else if (sprite.type == "rect") {
78697                 attrs.rx = attrs.ry = attrs.r;
78698             }
78699             else if (sprite.type == "path" && attrs.d) {
78700                 attrs.d = Ext.draw.Draw.pathToAbsolute(attrs.d);
78701             }
78702             sprite.dirtyPath = false;
78703         // }
78704
78705         if (attrs['clip-rect']) {
78706             me.setClip(sprite, attrs);
78707             delete attrs['clip-rect'];
78708         }
78709         if (sprite.type == 'text' && attrs.font && sprite.dirtyFont) {
78710             el.set({ style: "font: " + attrs.font});
78711             sprite.dirtyFont = false;
78712         }
78713         if (sprite.type == "image") {
78714             el.dom.setAttributeNS(me.xlink, "href", attrs.src);
78715         }
78716         Ext.applyIf(attrs, me.minDefaults[sprite.type]);
78717
78718         if (sprite.dirtyHidden) {
78719             (sattr.hidden) ? me.hidePrim(sprite) : me.showPrim(sprite);
78720             sprite.dirtyHidden = false;
78721         }
78722         for (key in attrs) {
78723             if (attrs.hasOwnProperty(key) && attrs[key] != null) {
78724                 el.dom.setAttribute(key, String(attrs[key]));
78725             }
78726         }
78727         if (sprite.type == 'text') {
78728             me.tuneText(sprite, attrs);
78729         }
78730
78731         //set styles
78732         style = sattr.style;
78733         if (style) {
78734             el.setStyle(style);
78735         }
78736
78737         sprite.dirty = false;
78738
78739         if (Ext.isSafari3) {
78740             // Refreshing the view to fix bug EXTJSIV-1: rendering issue in old Safari 3
78741             me.webkitRect.show();
78742             setTimeout(function () {
78743                 me.webkitRect.hide();
78744             });
78745         }
78746     },
78747
78748     setClip: function(sprite, params) {
78749         var me = this,
78750             rect = params["clip-rect"],
78751             clipEl, clipPath;
78752         if (rect) {
78753             if (sprite.clip) {
78754                 sprite.clip.parentNode.parentNode.removeChild(sprite.clip.parentNode);
78755             }
78756             clipEl = me.createSvgElement('clipPath');
78757             clipPath = me.createSvgElement('rect');
78758             clipEl.id = Ext.id(null, 'ext-clip-');
78759             clipPath.setAttribute("x", rect.x);
78760             clipPath.setAttribute("y", rect.y);
78761             clipPath.setAttribute("width", rect.width);
78762             clipPath.setAttribute("height", rect.height);
78763             clipEl.appendChild(clipPath);
78764             me.getDefs().appendChild(clipEl);
78765             sprite.el.dom.setAttribute("clip-path", "url(#" + clipEl.id + ")");
78766             sprite.clip = clipPath;
78767         }
78768         // if (!attrs[key]) {
78769         //     var clip = Ext.getDoc().dom.getElementById(sprite.el.getAttribute("clip-path").replace(/(^url\(#|\)$)/g, ""));
78770         //     clip && clip.parentNode.removeChild(clip);
78771         //     sprite.el.setAttribute("clip-path", "");
78772         //     delete attrss.clip;
78773         // }
78774     },
78775
78776     /**
78777      * Insert or move a given sprite's element to the correct place in the DOM list for its zIndex
78778      * @param {Ext.draw.Sprite} sprite
78779      */
78780     applyZIndex: function(sprite) {
78781         var idx = this.normalizeSpriteCollection(sprite),
78782             el = sprite.el,
78783             prevEl;
78784         if (this.el.dom.childNodes[idx + 2] !== el.dom) { //shift by 2 to account for defs and bg rect 
78785             if (idx > 0) {
78786                 // Find the first previous sprite which has its DOM element created already
78787                 do {
78788                     prevEl = this.items.getAt(--idx).el;
78789                 } while (!prevEl && idx > 0);
78790             }
78791             el.insertAfter(prevEl || this.bgRect);
78792         }
78793         sprite.zIndexDirty = false;
78794     },
78795
78796     createItem: function (config) {
78797         var sprite = Ext.create('Ext.draw.Sprite', config);
78798         sprite.surface = this;
78799         return sprite;
78800     },
78801
78802     addGradient: function(gradient) {
78803         gradient = Ext.draw.Draw.parseGradient(gradient);
78804         var ln = gradient.stops.length,
78805             vector = gradient.vector,
78806             gradientEl,
78807             stop,
78808             stopEl,
78809             i;
78810         if (gradient.type == "linear") {
78811             gradientEl = this.createSvgElement("linearGradient");
78812             gradientEl.setAttribute("x1", vector[0]);
78813             gradientEl.setAttribute("y1", vector[1]);
78814             gradientEl.setAttribute("x2", vector[2]);
78815             gradientEl.setAttribute("y2", vector[3]);
78816         }
78817         else {
78818             gradientEl = this.createSvgElement("radialGradient");
78819             gradientEl.setAttribute("cx", gradient.centerX);
78820             gradientEl.setAttribute("cy", gradient.centerY);
78821             gradientEl.setAttribute("r", gradient.radius);
78822             if (Ext.isNumber(gradient.focalX) && Ext.isNumber(gradient.focalY)) {
78823                 gradientEl.setAttribute("fx", gradient.focalX);
78824                 gradientEl.setAttribute("fy", gradient.focalY);
78825             }
78826         }    
78827         gradientEl.id = gradient.id;
78828         this.getDefs().appendChild(gradientEl);
78829
78830         for (i = 0; i < ln; i++) {
78831             stop = gradient.stops[i];
78832             stopEl = this.createSvgElement("stop");
78833             stopEl.setAttribute("offset", stop.offset + "%");
78834             stopEl.setAttribute("stop-color", stop.color);
78835             stopEl.setAttribute("stop-opacity",stop.opacity);
78836             gradientEl.appendChild(stopEl);
78837         }
78838     },
78839
78840     /**
78841      * Checks if the specified CSS class exists on this element's DOM node.
78842      * @param {String} className The CSS class to check for
78843      * @return {Boolean} True if the class exists, else false
78844      */
78845     hasCls: function(sprite, className) {
78846         return className && (' ' + (sprite.el.dom.getAttribute('class') || '') + ' ').indexOf(' ' + className + ' ') != -1;
78847     },
78848
78849     addCls: function(sprite, className) {
78850         var el = sprite.el,
78851             i,
78852             len,
78853             v,
78854             cls = [],
78855             curCls =  el.getAttribute('class') || '';
78856         // Separate case is for speed
78857         if (!Ext.isArray(className)) {
78858             if (typeof className == 'string' && !this.hasCls(sprite, className)) {
78859                 el.set({ 'class': curCls + ' ' + className });
78860             }
78861         }
78862         else {
78863             for (i = 0, len = className.length; i < len; i++) {
78864                 v = className[i];
78865                 if (typeof v == 'string' && (' ' + curCls + ' ').indexOf(' ' + v + ' ') == -1) {
78866                     cls.push(v);
78867                 }
78868             }
78869             if (cls.length) {
78870                 el.set({ 'class': ' ' + cls.join(' ') });
78871             }
78872         }
78873     },
78874
78875     removeCls: function(sprite, className) {
78876         var me = this,
78877             el = sprite.el,
78878             curCls =  el.getAttribute('class') || '',
78879             i, idx, len, cls, elClasses;
78880         if (!Ext.isArray(className)){
78881             className = [className];
78882         }
78883         if (curCls) {
78884             elClasses = curCls.replace(me.trimRe, ' ').split(me.spacesRe);
78885             for (i = 0, len = className.length; i < len; i++) {
78886                 cls = className[i];
78887                 if (typeof cls == 'string') {
78888                     cls = cls.replace(me.trimRe, '');
78889                     idx = Ext.Array.indexOf(elClasses, cls);
78890                     if (idx != -1) {
78891                         elClasses.splice(idx, 1);
78892                     }
78893                 }
78894             }
78895             el.set({ 'class': elClasses.join(' ') });
78896         }
78897     },
78898
78899     destroy: function() {
78900         var me = this;
78901         
78902         me.callParent();
78903         if (me.el) {
78904             me.el.remove();
78905         }
78906         delete me.el;
78907     }
78908 });
78909 /**
78910  * @class Ext.draw.engine.Vml
78911  * @extends Ext.draw.Surface
78912  * Provides specific methods to draw with VML.
78913  */
78914
78915 Ext.define('Ext.draw.engine.Vml', {
78916
78917     /* Begin Definitions */
78918
78919     extend: 'Ext.draw.Surface',
78920
78921     requires: ['Ext.draw.Draw', 'Ext.draw.Color', 'Ext.draw.Sprite', 'Ext.draw.Matrix', 'Ext.core.Element'],
78922
78923     /* End Definitions */
78924
78925     engine: 'Vml',
78926
78927     map: {M: "m", L: "l", C: "c", Z: "x", m: "t", l: "r", c: "v", z: "x"},
78928     bitesRe: /([clmz]),?([^clmz]*)/gi,
78929     valRe: /-?[^,\s-]+/g,
78930     fillUrlRe: /^url\(\s*['"]?([^\)]+?)['"]?\s*\)$/i,
78931     pathlike: /^(path|rect)$/,
78932     NonVmlPathRe: /[ahqstv]/ig, // Non-VML Pathing ops
78933     partialPathRe: /[clmz]/g,
78934     fontFamilyRe: /^['"]+|['"]+$/g,
78935     baseVmlCls: Ext.baseCSSPrefix + 'vml-base',
78936     vmlGroupCls: Ext.baseCSSPrefix + 'vml-group',
78937     spriteCls: Ext.baseCSSPrefix + 'vml-sprite',
78938     measureSpanCls: Ext.baseCSSPrefix + 'vml-measure-span',
78939     zoom: 21600,
78940     coordsize: 1000,
78941     coordorigin: '0 0',
78942
78943     // @private
78944     // Convert an SVG standard path into a VML path
78945     path2vml: function (path) {
78946         var me = this,
78947             nonVML =  me.NonVmlPathRe,
78948             map = me.map,
78949             val = me.valRe,
78950             zoom = me.zoom,
78951             bites = me.bitesRe,
78952             command = Ext.Function.bind(Ext.draw.Draw.pathToAbsolute, Ext.draw.Draw),
78953             res, pa, p, r, i, ii, j, jj;
78954         if (String(path).match(nonVML)) {
78955             command = Ext.Function.bind(Ext.draw.Draw.path2curve, Ext.draw.Draw);
78956         } else if (!String(path).match(me.partialPathRe)) {
78957             res = String(path).replace(bites, function (all, command, args) {
78958                 var vals = [],
78959                     isMove = command.toLowerCase() == "m",
78960                     res = map[command];
78961                 args.replace(val, function (value) {
78962                     if (isMove && vals[length] == 2) {
78963                         res += vals + map[command == "m" ? "l" : "L"];
78964                         vals = [];
78965                     }
78966                     vals.push(Math.round(value * zoom));
78967                 });
78968                 return res + vals;
78969             });
78970             return res;
78971         }
78972         pa = command(path);
78973         res = [];
78974         for (i = 0, ii = pa.length; i < ii; i++) {
78975             p = pa[i];
78976             r = pa[i][0].toLowerCase();
78977             if (r == "z") {
78978                 r = "x";
78979             }
78980             for (j = 1, jj = p.length; j < jj; j++) {
78981                 r += Math.round(p[j] * me.zoom) + (j != jj - 1 ? "," : "");
78982             }
78983             res.push(r);
78984         }
78985         return res.join(" ");
78986     },
78987
78988     // @private - set of attributes which need to be translated from the sprite API to the native browser API
78989     translateAttrs: {
78990         radius: "r",
78991         radiusX: "rx",
78992         radiusY: "ry",
78993         lineWidth: "stroke-width",
78994         fillOpacity: "fill-opacity",
78995         strokeOpacity: "stroke-opacity",
78996         strokeLinejoin: "stroke-linejoin"
78997     },
78998
78999     // @private - Minimun set of defaults for different types of sprites.
79000     minDefaults: {
79001         circle: {
79002             fill: "none",
79003             stroke: null,
79004             "stroke-width": null,
79005             opacity: null,
79006             "fill-opacity": null,
79007             "stroke-opacity": null
79008         },
79009         ellipse: {
79010             cx: 0,
79011             cy: 0,
79012             rx: 0,
79013             ry: 0,
79014             fill: "none",
79015             stroke: null,
79016             "stroke-width": null,
79017             opacity: null,
79018             "fill-opacity": null,
79019             "stroke-opacity": null
79020         },
79021         rect: {
79022             x: 0,
79023             y: 0,
79024             width: 0,
79025             height: 0,
79026             rx: 0,
79027             ry: 0,
79028             fill: "none",
79029             stroke: null,
79030             "stroke-width": null,
79031             opacity: null,
79032             "fill-opacity": null,
79033             "stroke-opacity": null
79034         },
79035         text: {
79036             x: 0,
79037             y: 0,
79038             "text-anchor": "start",
79039             font: '10px "Arial"',
79040             fill: "#000",
79041             stroke: null,
79042             "stroke-width": null,
79043             opacity: null,
79044             "fill-opacity": null,
79045             "stroke-opacity": null
79046         },
79047         path: {
79048             d: "M0,0",
79049             fill: "none",
79050             stroke: null,
79051             "stroke-width": null,
79052             opacity: null,
79053             "fill-opacity": null,
79054             "stroke-opacity": null
79055         },
79056         image: {
79057             x: 0,
79058             y: 0,
79059             width: 0,
79060             height: 0,
79061             preserveAspectRatio: "none",
79062             opacity: null
79063         }
79064     },
79065
79066     // private
79067     onMouseEnter: function(e) {
79068         this.fireEvent("mouseenter", e);
79069     },
79070
79071     // private
79072     onMouseLeave: function(e) {
79073         this.fireEvent("mouseleave", e);
79074     },
79075
79076     // @private - Normalize a delegated single event from the main container to each sprite and sprite group
79077     processEvent: function(name, e) {
79078         var target = e.getTarget(),
79079             surface = this.surface,
79080             sprite;
79081         this.fireEvent(name, e);
79082         sprite = this.items.get(target.id);
79083         if (sprite) {
79084             sprite.fireEvent(name, sprite, e);
79085         }
79086     },
79087
79088     // Create the VML element/elements and append them to the DOM
79089     createSpriteElement: function(sprite) {
79090         var me = this,
79091             attr = sprite.attr,
79092             type = sprite.type,
79093             zoom = me.zoom,
79094             vml = sprite.vml || (sprite.vml = {}),
79095             round = Math.round,
79096             el = (type === 'image') ? me.createNode('image') : me.createNode('shape'),
79097             path, skew, textPath;
79098
79099         el.coordsize = zoom + ' ' + zoom;
79100         el.coordorigin = attr.coordorigin || "0 0";
79101         Ext.get(el).addCls(me.spriteCls);
79102         if (type == "text") {
79103             vml.path = path = me.createNode("path");
79104             path.textpathok = true;
79105             vml.textpath = textPath = me.createNode("textpath");
79106             textPath.on = true;
79107             el.appendChild(textPath);
79108             el.appendChild(path);
79109         }
79110         el.id = sprite.id;
79111         sprite.el = Ext.get(el);
79112         me.el.appendChild(el);
79113         if (type !== 'image') {
79114             skew = me.createNode("skew");
79115             skew.on = true;
79116             el.appendChild(skew);
79117             sprite.skew = skew;
79118         }
79119         sprite.matrix = Ext.create('Ext.draw.Matrix');
79120         sprite.bbox = {
79121             plain: null,
79122             transform: null
79123         };
79124         sprite.fireEvent("render", sprite);
79125         return sprite.el;
79126     },
79127
79128     // @private - Get bounding box for the sprite.  The Sprite itself has the public method.
79129     getBBox: function (sprite, isWithoutTransform) {
79130         var realPath = this["getPath" + sprite.type](sprite);
79131         if (isWithoutTransform) {
79132             sprite.bbox.plain = sprite.bbox.plain || Ext.draw.Draw.pathDimensions(realPath);
79133             return sprite.bbox.plain;
79134         }
79135         sprite.bbox.transform = sprite.bbox.transform || Ext.draw.Draw.pathDimensions(Ext.draw.Draw.mapPath(realPath, sprite.matrix));
79136         return sprite.bbox.transform;
79137     },
79138
79139     getBBoxText: function (sprite) {
79140         var vml = sprite.vml;
79141         return {
79142             x: vml.X + (vml.bbx || 0) - vml.W / 2,
79143             y: vml.Y - vml.H / 2,
79144             width: vml.W,
79145             height: vml.H
79146         };
79147     },
79148
79149     applyAttrs: function (sprite) {
79150         var me = this,
79151             vml = sprite.vml,
79152             group = sprite.group,
79153             spriteAttr = sprite.attr,
79154             el = sprite.el,
79155             dom = el.dom,
79156             style, name, groups, i, ln, scrubbedAttrs, font, key, bbox;
79157
79158         if (group) {
79159             groups = [].concat(group);
79160             ln = groups.length;
79161             for (i = 0; i < ln; i++) {
79162                 group = groups[i];
79163                 me.getGroup(group).add(sprite);
79164             }
79165             delete sprite.group;
79166         }
79167         scrubbedAttrs = me.scrubAttrs(sprite) || {};
79168
79169         if (sprite.zIndexDirty) {
79170             me.setZIndex(sprite);
79171         }
79172
79173         // Apply minimum default attributes
79174         Ext.applyIf(scrubbedAttrs, me.minDefaults[sprite.type]);
79175
79176         if (sprite.type == 'image') {
79177             Ext.apply(sprite.attr, {
79178                 x: scrubbedAttrs.x,
79179                 y: scrubbedAttrs.y,
79180                 width: scrubbedAttrs.width,
79181                 height: scrubbedAttrs.height
79182             });
79183             bbox = sprite.getBBox();
79184             el.setStyle({
79185                 width: bbox.width + 'px',
79186                 height: bbox.height + 'px'
79187             });
79188             dom.src = scrubbedAttrs.src;
79189         }
79190
79191         if (dom.href) {
79192             dom.href = scrubbedAttrs.href;
79193         }
79194         if (dom.title) {
79195             dom.title = scrubbedAttrs.title;
79196         }
79197         if (dom.target) {
79198             dom.target = scrubbedAttrs.target;
79199         }
79200         if (dom.cursor) {
79201             dom.cursor = scrubbedAttrs.cursor;
79202         }
79203
79204         // Change visibility
79205         if (sprite.dirtyHidden) {
79206             (scrubbedAttrs.hidden) ? me.hidePrim(sprite) : me.showPrim(sprite);
79207             sprite.dirtyHidden = false;
79208         }
79209
79210         // Update path
79211         if (sprite.dirtyPath) {
79212             if (sprite.type == "circle" || sprite.type == "ellipse") {
79213                 var cx = scrubbedAttrs.x,
79214                     cy = scrubbedAttrs.y,
79215                     rx = scrubbedAttrs.rx || scrubbedAttrs.r || 0,
79216                     ry = scrubbedAttrs.ry || scrubbedAttrs.r || 0;
79217                 dom.path = Ext.String.format("ar{0},{1},{2},{3},{4},{1},{4},{1}",
79218                             Math.round((cx - rx) * me.zoom),
79219                             Math.round((cy - ry) * me.zoom),
79220                             Math.round((cx + rx) * me.zoom),
79221                             Math.round((cy + ry) * me.zoom),
79222                             Math.round(cx * me.zoom));
79223                 sprite.dirtyPath = false;
79224             }
79225             else if (sprite.type !== "text" && sprite.type !== 'image') {
79226                 sprite.attr.path = scrubbedAttrs.path = me.setPaths(sprite, scrubbedAttrs) || scrubbedAttrs.path;
79227                 dom.path = me.path2vml(scrubbedAttrs.path);
79228                 sprite.dirtyPath = false;
79229             }
79230         }
79231
79232         // Apply clipping
79233         if ("clip-rect" in scrubbedAttrs) {
79234             me.setClip(sprite, scrubbedAttrs);
79235         }
79236
79237         // Handle text (special handling required)
79238         if (sprite.type == "text") {
79239             me.setTextAttributes(sprite, scrubbedAttrs);
79240         }
79241
79242         // Handle fill and opacity
79243         if (scrubbedAttrs.opacity  || scrubbedAttrs['stroke-opacity'] || scrubbedAttrs.fill) {
79244             me.setFill(sprite, scrubbedAttrs);
79245         }
79246
79247         // Handle stroke (all fills require a stroke element)
79248         if (scrubbedAttrs.stroke || scrubbedAttrs['stroke-opacity'] || scrubbedAttrs.fill) {
79249             me.setStroke(sprite, scrubbedAttrs);
79250         }
79251         
79252         //set styles
79253         style = spriteAttr.style;
79254         if (style) {
79255             el.setStyle(style);
79256         }
79257
79258         sprite.dirty = false;
79259     },
79260
79261     setZIndex: function(sprite) {
79262         if (sprite.el) {
79263             if (sprite.attr.zIndex != undefined) {
79264                 sprite.el.setStyle('zIndex', sprite.attr.zIndex);
79265             }
79266             sprite.zIndexDirty = false;
79267         }
79268     },
79269
79270     // Normalize all virtualized types into paths.
79271     setPaths: function(sprite, params) {
79272         var spriteAttr = sprite.attr;
79273         // Clear bbox cache
79274         sprite.bbox.plain = null;
79275         sprite.bbox.transform = null;
79276         if (sprite.type == 'circle') {
79277             spriteAttr.rx = spriteAttr.ry = params.r;
79278             return Ext.draw.Draw.ellipsePath(sprite);
79279         }
79280         else if (sprite.type == 'ellipse') {
79281             spriteAttr.rx = params.rx;
79282             spriteAttr.ry = params.ry;
79283             return Ext.draw.Draw.ellipsePath(sprite);
79284         }
79285         else if (sprite.type == 'rect') {
79286             spriteAttr.rx = spriteAttr.ry = params.r;
79287             return Ext.draw.Draw.rectPath(sprite);
79288         }
79289         else if (sprite.type == 'path' && spriteAttr.path) {
79290             return Ext.draw.Draw.pathToAbsolute(spriteAttr.path);
79291         }
79292         return false;
79293     },
79294
79295     setFill: function(sprite, params) {
79296         var me = this,
79297             el = sprite.el.dom,
79298             fillEl = el.fill,
79299             newfill = false,
79300             opacity, gradient, fillUrl, rotation, angle;
79301
79302         if (!fillEl) {
79303             // NOT an expando (but it sure looks like one)...
79304             fillEl = el.fill = me.createNode("fill");
79305             newfill = true;
79306         }
79307         if (Ext.isArray(params.fill)) {
79308             params.fill = params.fill[0];
79309         }
79310         if (params.fill == "none") {
79311             fillEl.on = false;
79312         }
79313         else {
79314             if (typeof params.opacity == "number") {
79315                 fillEl.opacity = params.opacity;
79316             }
79317             if (typeof params["fill-opacity"] == "number") {
79318                 fillEl.opacity = params["fill-opacity"];
79319             }
79320             fillEl.on = true;
79321             if (typeof params.fill == "string") {
79322                 fillUrl = params.fill.match(me.fillUrlRe);
79323                 if (fillUrl) {
79324                     fillUrl = fillUrl[1];
79325                     // If the URL matches one of the registered gradients, render that gradient
79326                     if (fillUrl.charAt(0) == "#") {
79327                         gradient = me.gradientsColl.getByKey(fillUrl.substring(1));
79328                     }
79329                     if (gradient) {
79330                         // VML angle is offset and inverted from standard, and must be adjusted to match rotation transform
79331                         rotation = params.rotation;
79332                         angle = -(gradient.angle + 270 + (rotation ? rotation.degrees : 0)) % 360;
79333                         // IE will flip the angle at 0 degrees...
79334                         if (angle === 0) {
79335                             angle = 180;
79336                         }
79337                         fillEl.angle = angle;
79338                         fillEl.type = "gradient";
79339                         fillEl.method = "sigma";
79340                         fillEl.colors.value = gradient.colors;
79341                     }
79342                     // Otherwise treat it as an image
79343                     else {
79344                         fillEl.src = fillUrl;
79345                         fillEl.type = "tile";
79346                     }
79347                 }
79348                 else {
79349                     fillEl.color = Ext.draw.Color.toHex(params.fill);
79350                     fillEl.src = "";
79351                     fillEl.type = "solid";
79352                 }
79353             }
79354         }
79355         if (newfill) {
79356             el.appendChild(fillEl);
79357         }
79358     },
79359
79360     setStroke: function(sprite, params) {
79361         var me = this,
79362             el = sprite.el.dom,
79363             strokeEl = sprite.strokeEl,
79364             newStroke = false,
79365             width, opacity;
79366
79367         if (!strokeEl) {
79368             strokeEl = sprite.strokeEl = me.createNode("stroke");
79369             newStroke = true;
79370         }
79371         if (Ext.isArray(params.stroke)) {
79372             params.stroke = params.stroke[0];
79373         }
79374         if (!params.stroke || params.stroke == "none" || params.stroke == 0 || params["stroke-width"] == 0) {
79375             strokeEl.on = false;
79376         }
79377         else {
79378             strokeEl.on = true;
79379             if (params.stroke && !params.stroke.match(me.fillUrlRe)) {
79380                 // VML does NOT support a gradient stroke :(
79381                 strokeEl.color = Ext.draw.Color.toHex(params.stroke);
79382             }
79383             strokeEl.joinstyle = params["stroke-linejoin"];
79384             strokeEl.endcap = params["stroke-linecap"] || "round";
79385             strokeEl.miterlimit = params["stroke-miterlimit"] || 8;
79386             width = parseFloat(params["stroke-width"] || 1) * 0.75;
79387             opacity = params["stroke-opacity"] || 1;
79388             // VML Does not support stroke widths under 1, so we're going to fiddle with stroke-opacity instead.
79389             if (Ext.isNumber(width) && width < 1) {
79390                 strokeEl.weight = 1;
79391                 strokeEl.opacity = opacity * width;
79392             }
79393             else {
79394                 strokeEl.weight = width;
79395                 strokeEl.opacity = opacity;
79396             }
79397         }
79398         if (newStroke) {
79399             el.appendChild(strokeEl);
79400         }
79401     },
79402
79403     setClip: function(sprite, params) {
79404         var me = this,
79405             el = sprite.el,
79406             clipEl = sprite.clipEl,
79407             rect = String(params["clip-rect"]).split(me.separatorRe);
79408         if (!clipEl) {
79409             clipEl = sprite.clipEl = me.el.insertFirst(Ext.getDoc().dom.createElement("div"));
79410             clipEl.addCls(Ext.baseCSSPrefix + 'vml-sprite');
79411         }
79412         if (rect.length == 4) {
79413             rect[2] = +rect[2] + (+rect[0]);
79414             rect[3] = +rect[3] + (+rect[1]);
79415             clipEl.setStyle("clip", Ext.String.format("rect({1}px {2}px {3}px {0}px)", rect[0], rect[1], rect[2], rect[3]));
79416             clipEl.setSize(me.el.width, me.el.height);
79417         }
79418         else {
79419             clipEl.setStyle("clip", "");
79420         }
79421     },
79422
79423     setTextAttributes: function(sprite, params) {
79424         var me = this,
79425             vml = sprite.vml,
79426             textStyle = vml.textpath.style,
79427             spanCacheStyle = me.span.style,
79428             zoom = me.zoom,
79429             round = Math.round,
79430             fontObj = {
79431                 fontSize: "font-size",
79432                 fontWeight: "font-weight",
79433                 fontStyle: "font-style"
79434             },
79435             fontProp,
79436             paramProp;
79437         if (sprite.dirtyFont) {
79438             if (params.font) {
79439                 textStyle.font = spanCacheStyle.font = params.font;
79440             }
79441             if (params["font-family"]) {
79442                 textStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(me.fontFamilyRe, "") + '"';
79443                 spanCacheStyle.fontFamily = params["font-family"];
79444             }
79445
79446             for (fontProp in fontObj) {
79447                 paramProp = params[fontObj[fontProp]];
79448                 if (paramProp) {
79449                     textStyle[fontProp] = spanCacheStyle[fontProp] = paramProp;
79450                 }
79451             }
79452
79453             me.setText(sprite, params.text);
79454             
79455             if (vml.textpath.string) {
79456                 me.span.innerHTML = String(vml.textpath.string).replace(/</g, "&#60;").replace(/&/g, "&#38;").replace(/\n/g, "<br>");
79457             }
79458             vml.W = me.span.offsetWidth;
79459             vml.H = me.span.offsetHeight + 2; // TODO handle baseline differences and offset in VML Textpath
79460
79461             // text-anchor emulation
79462             if (params["text-anchor"] == "middle") {
79463                 textStyle["v-text-align"] = "center";
79464             }
79465             else if (params["text-anchor"] == "end") {
79466                 textStyle["v-text-align"] = "right";
79467                 vml.bbx = -Math.round(vml.W / 2);
79468             }
79469             else {
79470                 textStyle["v-text-align"] = "left";
79471                 vml.bbx = Math.round(vml.W / 2);
79472             }
79473         }
79474         vml.X = params.x;
79475         vml.Y = params.y;
79476         vml.path.v = Ext.String.format("m{0},{1}l{2},{1}", Math.round(vml.X * zoom), Math.round(vml.Y * zoom), Math.round(vml.X * zoom) + 1);
79477         // Clear bbox cache
79478         sprite.bbox.plain = null;
79479         sprite.bbox.transform = null;
79480         sprite.dirtyFont = false;
79481     },
79482     
79483     setText: function(sprite, text) {
79484         sprite.vml.textpath.string = Ext.htmlDecode(text);
79485     },
79486
79487     hide: function() {
79488         this.el.hide();
79489     },
79490
79491     show: function() {
79492         this.el.show();
79493     },
79494
79495     hidePrim: function(sprite) {
79496         sprite.el.addCls(Ext.baseCSSPrefix + 'hide-visibility');
79497     },
79498
79499     showPrim: function(sprite) {
79500         sprite.el.removeCls(Ext.baseCSSPrefix + 'hide-visibility');
79501     },
79502
79503     setSize: function(width, height) {
79504         var me = this,
79505             viewBox = me.viewBox,
79506             scaleX, scaleY, items, i, len;
79507         width = width || me.width;
79508         height = height || me.height;
79509         me.width = width;
79510         me.height = height;
79511
79512         if (!me.el) {
79513             return;
79514         }
79515
79516         // Size outer div
79517         if (width != undefined) {
79518             me.el.setWidth(width);
79519         }
79520         if (height != undefined) {
79521             me.el.setHeight(height);
79522         }
79523
79524         // Handle viewBox sizing
79525         if (viewBox && (width || height)) {
79526             var viewBoxX = viewBox.x,
79527                 viewBoxY = viewBox.y,
79528                 viewBoxWidth = viewBox.width,
79529                 viewBoxHeight = viewBox.height,
79530                 relativeHeight = height / viewBoxHeight,
79531                 relativeWidth = width / viewBoxWidth,
79532                 size;
79533             if (viewBoxWidth * relativeHeight < width) {
79534                 viewBoxX -= (width - viewBoxWidth * relativeHeight) / 2 / relativeHeight;
79535             }
79536             if (viewBoxHeight * relativeWidth < height) {
79537                 viewBoxY -= (height - viewBoxHeight * relativeWidth) / 2 / relativeWidth;
79538             }
79539             size = 1 / Math.max(viewBoxWidth / width, viewBoxHeight / height);
79540             // Scale and translate group
79541             me.viewBoxShift = {
79542                 dx: -viewBoxX,
79543                 dy: -viewBoxY,
79544                 scale: size
79545             };
79546             items = me.items.items;
79547             for (i = 0, len = items.length; i < len; i++) {
79548                 me.transform(items[i]);
79549             }
79550         }
79551         this.callParent(arguments);
79552     },
79553
79554     setViewBox: function(x, y, width, height) {
79555         this.callParent(arguments);
79556         this.viewBox = {
79557             x: x,
79558             y: y,
79559             width: width,
79560             height: height
79561         };
79562     },
79563
79564     onAdd: function(item) {
79565         this.callParent(arguments);
79566         if (this.el) {
79567             this.renderItem(item);
79568         }
79569     },
79570
79571     onRemove: function(sprite) {
79572         if (sprite.el) {
79573             sprite.el.remove();
79574             delete sprite.el;
79575         }
79576         this.callParent(arguments);
79577     },
79578
79579     render: function (container) {
79580         var me = this,
79581             doc = Ext.getDoc().dom;
79582         // VML Node factory method (createNode)
79583         if (!me.createNode) {
79584             try {
79585                 if (!doc.namespaces.rvml) {
79586                     doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
79587                 }
79588                 me.createNode = function (tagName) {
79589                     return doc.createElement("<rvml:" + tagName + ' class="rvml">');
79590                 };
79591             } catch (e) {
79592                 me.createNode = function (tagName) {
79593                     return doc.createElement("<" + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
79594                 };
79595             }
79596         }
79597
79598         if (!me.el) {
79599             var el = doc.createElement("div");
79600             me.el = Ext.get(el);
79601             me.el.addCls(me.baseVmlCls);
79602
79603             // Measuring span (offscrren)
79604             me.span = doc.createElement("span");
79605             Ext.get(me.span).addCls(me.measureSpanCls);
79606             el.appendChild(me.span);
79607             me.el.setSize(me.width || 10, me.height || 10);
79608             container.appendChild(el);
79609             me.el.on({
79610                 scope: me,
79611                 mouseup: me.onMouseUp,
79612                 mousedown: me.onMouseDown,
79613                 mouseover: me.onMouseOver,
79614                 mouseout: me.onMouseOut,
79615                 mousemove: me.onMouseMove,
79616                 mouseenter: me.onMouseEnter,
79617                 mouseleave: me.onMouseLeave,
79618                 click: me.onClick
79619             });
79620         }
79621         me.renderAll();
79622     },
79623
79624     renderAll: function() {
79625         this.items.each(this.renderItem, this);
79626     },
79627
79628     redraw: function(sprite) {
79629         sprite.dirty = true;
79630         this.renderItem(sprite);
79631     },
79632
79633     renderItem: function (sprite) {
79634         // Does the surface element exist?
79635         if (!this.el) {
79636             return;
79637         }
79638
79639         // Create sprite element if necessary
79640         if (!sprite.el) {
79641             this.createSpriteElement(sprite);
79642         }
79643
79644         if (sprite.dirty) {
79645             this.applyAttrs(sprite);
79646             if (sprite.dirtyTransform) {
79647                 this.applyTransformations(sprite);
79648             }
79649         }
79650     },
79651
79652     rotationCompensation: function (deg, dx, dy) {
79653         var matrix = Ext.create('Ext.draw.Matrix');
79654         matrix.rotate(-deg, 0.5, 0.5);
79655         return {
79656             x: matrix.x(dx, dy),
79657             y: matrix.y(dx, dy)
79658         };
79659     },
79660
79661     transform: function(sprite) {
79662         var me = this,
79663             matrix = Ext.create('Ext.draw.Matrix'),
79664             transforms = sprite.transformations,
79665             transformsLength = transforms.length,
79666             i = 0,
79667             deltaDegrees = 0,
79668             deltaScaleX = 1,
79669             deltaScaleY = 1,
79670             flip = "",
79671             el = sprite.el,
79672             dom = el.dom,
79673             domStyle = dom.style,
79674             zoom = me.zoom,
79675             skew = sprite.skew,
79676             deltaX, deltaY, transform, type, compensate, y, fill, newAngle,zoomScaleX, zoomScaleY, newOrigin;
79677
79678         for (; i < transformsLength; i++) {
79679             transform = transforms[i];
79680             type = transform.type;
79681             if (type == "translate") {
79682                 matrix.translate(transform.x, transform.y);
79683             }
79684             else if (type == "rotate") {
79685                 matrix.rotate(transform.degrees, transform.x, transform.y);
79686                 deltaDegrees += transform.degrees;
79687             }
79688             else if (type == "scale") {
79689                 matrix.scale(transform.x, transform.y, transform.centerX, transform.centerY);
79690                 deltaScaleX *= transform.x;
79691                 deltaScaleY *= transform.y;
79692             }
79693         }
79694
79695         if (me.viewBoxShift) {
79696             matrix.scale(me.viewBoxShift.scale, me.viewBoxShift.scale, -1, -1);
79697             matrix.add(1, 0, 0, 1, me.viewBoxShift.dx, me.viewBoxShift.dy);
79698         }
79699
79700         sprite.matrix = matrix;
79701
79702
79703         // Hide element while we transform
79704
79705         if (sprite.type != "image" && skew) {
79706             // matrix transform via VML skew
79707             skew.matrix = matrix.toString();
79708             skew.offset = matrix.offset();
79709         }
79710         else {
79711             deltaX = matrix.matrix[0][2];
79712             deltaY = matrix.matrix[1][2];
79713             // Scale via coordsize property
79714             zoomScaleX = zoom / deltaScaleX;
79715             zoomScaleY = zoom / deltaScaleY;
79716
79717             dom.coordsize = Math.abs(zoomScaleX) + " " + Math.abs(zoomScaleY);
79718
79719             // Rotate via rotation property
79720             newAngle = deltaDegrees * (deltaScaleX * ((deltaScaleY < 0) ? -1 : 1));
79721             if (newAngle != domStyle.rotation && !(newAngle === 0 && !domStyle.rotation)) {
79722                 domStyle.rotation = newAngle;
79723             }
79724             if (deltaDegrees) {
79725                 // Compensate x/y position due to rotation
79726                 compensate = me.rotationCompensation(deltaDegrees, deltaX, deltaY);
79727                 deltaX = compensate.x;
79728                 deltaY = compensate.y;
79729             }
79730
79731             // Handle negative scaling via flipping
79732             if (deltaScaleX < 0) {
79733                 flip += "x";
79734             }
79735             if (deltaScaleY < 0) {
79736                 flip += " y";
79737                 y = -1;
79738             }
79739             if (flip != "" && !dom.style.flip) {
79740                 domStyle.flip = flip;
79741             }
79742
79743             // Translate via coordorigin property
79744             newOrigin = (deltaX * -zoomScaleX) + " " + (deltaY * -zoomScaleY);
79745             if (newOrigin != dom.coordorigin) {
79746                 dom.coordorigin = (deltaX * -zoomScaleX) + " " + (deltaY * -zoomScaleY);
79747             }
79748         }
79749     },
79750
79751     createItem: function (config) {
79752         return Ext.create('Ext.draw.Sprite', config);
79753     },
79754
79755     getRegion: function() {
79756         return this.el.getRegion();
79757     },
79758
79759     addCls: function(sprite, className) {
79760         if (sprite && sprite.el) {
79761             sprite.el.addCls(className);
79762         }
79763     },
79764
79765     removeCls: function(sprite, className) {
79766         if (sprite && sprite.el) {
79767             sprite.el.removeCls(className);
79768         }
79769     },
79770
79771     /**
79772      * Adds a definition to this Surface for a linear gradient. We convert the gradient definition
79773      * to its corresponding VML attributes and store it for later use by individual sprites.
79774      * @param {Object} gradient
79775      */
79776     addGradient: function(gradient) {
79777         var gradients = this.gradientsColl || (this.gradientsColl = Ext.create('Ext.util.MixedCollection')),
79778             colors = [],
79779             stops = Ext.create('Ext.util.MixedCollection');
79780
79781         // Build colors string
79782         stops.addAll(gradient.stops);
79783         stops.sortByKey("ASC", function(a, b) {
79784             a = parseInt(a, 10);
79785             b = parseInt(b, 10);
79786             return a > b ? 1 : (a < b ? -1 : 0);
79787         });
79788         stops.eachKey(function(k, v) {
79789             colors.push(k + "% " + v.color);
79790         });
79791
79792         gradients.add(gradient.id, {
79793             colors: colors.join(","),
79794             angle: gradient.angle
79795         });
79796     },
79797
79798     destroy: function() {
79799         var me = this;
79800         
79801         me.callParent(arguments);
79802         if (me.el) {
79803             me.el.remove();
79804         }
79805         delete me.el;
79806     }
79807 });
79808
79809 /**
79810  * @class Ext.fx.target.ElementCSS
79811  * @extends Ext.fx.target.Element
79812  * 
79813  * This class represents a animation target for an {@link Ext.core.Element} that supports CSS
79814  * based animation. In general this class will not be created directly, the {@link Ext.core.Element} 
79815  * will be passed to the animation and the appropriate target will be created.
79816  */
79817 Ext.define('Ext.fx.target.ElementCSS', {
79818
79819     /* Begin Definitions */
79820
79821     extend: 'Ext.fx.target.Element',
79822
79823     /* End Definitions */
79824
79825     setAttr: function(targetData, isFirstFrame) {
79826         var cssArr = {
79827                 attrs: [],
79828                 duration: [],
79829                 easing: []
79830             },
79831             ln = targetData.length,
79832             attributes,
79833             attrs,
79834             attr,
79835             easing,
79836             duration,
79837             o,
79838             i,
79839             j,
79840             ln2;
79841         for (i = 0; i < ln; i++) {
79842             attrs = targetData[i];
79843             duration = attrs.duration;
79844             easing = attrs.easing;
79845             attrs = attrs.attrs;
79846             for (attr in attrs) {
79847                 if (Ext.Array.indexOf(cssArr.attrs, attr) == -1) {
79848                     cssArr.attrs.push(attr.replace(/[A-Z]/g, function(v) {
79849                         return '-' + v.toLowerCase();
79850                     }));
79851                     cssArr.duration.push(duration + 'ms');
79852                     cssArr.easing.push(easing);
79853                 }
79854             }
79855         }
79856         attributes = cssArr.attrs.join(',');
79857         duration = cssArr.duration.join(',');
79858         easing = cssArr.easing.join(', ');
79859         for (i = 0; i < ln; i++) {
79860             attrs = targetData[i].attrs;
79861             for (attr in attrs) {
79862                 ln2 = attrs[attr].length;
79863                 for (j = 0; j < ln2; j++) {
79864                     o = attrs[attr][j];
79865                     o[0].setStyle(Ext.supports.CSS3Prefix + 'TransitionProperty', isFirstFrame ? '' : attributes);
79866                     o[0].setStyle(Ext.supports.CSS3Prefix + 'TransitionDuration', isFirstFrame ? '' : duration);
79867                     o[0].setStyle(Ext.supports.CSS3Prefix + 'TransitionTimingFunction', isFirstFrame ? '' : easing);
79868                     o[0].setStyle(attr, o[1]);
79869
79870                     // Must trigger reflow to make this get used as the start point for the transition that follows
79871                     if (isFirstFrame) {
79872                         o = o[0].dom.offsetWidth;
79873                     }
79874                     else {
79875                         // Remove transition properties when completed.
79876                         o[0].on(Ext.supports.CSS3TransitionEnd, function() {
79877                             this.setStyle(Ext.supports.CSS3Prefix + 'TransitionProperty', null);
79878                             this.setStyle(Ext.supports.CSS3Prefix + 'TransitionDuration', null);
79879                             this.setStyle(Ext.supports.CSS3Prefix + 'TransitionTimingFunction', null);
79880                         }, o[0], { single: true });
79881                     }
79882                 }
79883             }
79884         }
79885     }
79886 });
79887 /**
79888  * @class Ext.fx.target.CompositeElementCSS
79889  * @extends Ext.fx.target.CompositeElement
79890  * 
79891  * This class represents a animation target for a {@link Ext.CompositeElement}, where the
79892  * constituent elements support CSS based animation. It allows each {@link Ext.core.Element} in 
79893  * the group to be animated as a whole. In general this class will not be created directly, 
79894  * the {@link Ext.CompositeElement} will be passed to the animation and the appropriate target 
79895  * will be created.
79896  */
79897 Ext.define('Ext.fx.target.CompositeElementCSS', {
79898
79899     /* Begin Definitions */
79900
79901     extend: 'Ext.fx.target.CompositeElement',
79902
79903     requires: ['Ext.fx.target.ElementCSS'],
79904
79905     /* End Definitions */
79906     setAttr: function() {
79907         return Ext.fx.target.ElementCSS.prototype.setAttr.apply(this, arguments);
79908     }
79909 });
79910 /**
79911  * @class Ext.layout.container.AbstractFit
79912  * @extends Ext.layout.container.Container
79913  * <p>This is a base class for layouts that contain <b>a single item</b> that automatically expands to fill the layout's
79914  * container.  This class is intended to be extended or created via the <tt>layout:'fit'</tt> {@link Ext.container.Container#layout}
79915  * config, and should generally not need to be created directly via the new keyword.</p>
79916  * <p>FitLayout does not have any direct config options (other than inherited ones).  To fit a panel to a container
79917  * using FitLayout, simply set layout:'fit' on the container and add a single panel to it.  If the container has
79918  * multiple panels, only the first one will be displayed.  Example usage:</p>
79919  * <pre><code>
79920 var p = new Ext.panel.Panel({
79921     title: 'Fit Layout',
79922     layout:'fit',
79923     items: {
79924         title: 'Inner Panel',
79925         html: '&lt;p&gt;This is the inner panel content&lt;/p&gt;',
79926         border: false
79927     }
79928 });
79929 </code></pre>
79930  */
79931 Ext.define('Ext.layout.container.AbstractFit', {
79932
79933     /* Begin Definitions */
79934
79935     extend: 'Ext.layout.container.Container',
79936
79937     /* End Definitions */
79938
79939     itemCls: Ext.baseCSSPrefix + 'fit-item',
79940     targetCls: Ext.baseCSSPrefix + 'layout-fit',
79941     type: 'fit'
79942 });
79943 /**
79944  * @class Ext.layout.container.Fit
79945  * @extends Ext.layout.container.AbstractFit
79946  * <p>This is a base class for layouts that contain <b>a single item</b> that automatically expands to fill the layout's
79947  * container.  This class is intended to be extended or created via the <tt>layout:'fit'</tt> {@link Ext.container.Container#layout}
79948  * config, and should generally not need to be created directly via the new keyword.</p>
79949  * <p>FitLayout does not have any direct config options (other than inherited ones).  To fit a panel to a container
79950  * using FitLayout, simply set layout:'fit' on the container and add a single panel to it.  If the container has
79951  * multiple panels, only the first one will be displayed.  
79952  * {@img Ext.layout.container.Fit/Ext.layout.container.Fit.png Ext.layout.container.Fit container layout}
79953  * Example usage:</p>
79954  * <pre><code>
79955     Ext.create('Ext.panel.Panel', {
79956         title: 'Fit Layout',
79957         width: 300,
79958         height: 150,
79959         layout:'fit',
79960         items: {
79961             title: 'Inner Panel',
79962             html: '<p>This is the inner panel content</p>',
79963             bodyPadding: 20,
79964             border: false
79965         },
79966         renderTo: Ext.getBody()
79967     });  
79968 </code></pre>
79969  */
79970 Ext.define('Ext.layout.container.Fit', {
79971
79972     /* Begin Definitions */
79973
79974     extend: 'Ext.layout.container.AbstractFit',
79975     alias: 'layout.fit',
79976     alternateClassName: 'Ext.layout.FitLayout',
79977
79978     /* End Definitions */
79979    
79980     // @private
79981     onLayout : function() {
79982         var me = this;
79983         me.callParent();
79984
79985         if (me.owner.items.length) {
79986             me.setItemBox(me.owner.items.get(0), me.getLayoutTargetSize());
79987         }
79988     },
79989
79990     getTargetBox : function() {
79991         return this.getLayoutTargetSize();
79992     },
79993
79994     setItemBox : function(item, box) {
79995         var me = this;
79996         if (item && box.height > 0) {
79997             if (me.isManaged('width') === true) {
79998                box.width = undefined;
79999             }
80000             if (me.isManaged('height') === true) {
80001                box.height = undefined;
80002             }
80003             me.setItemSize(item, box.width, box.height);
80004         }
80005     }
80006 });
80007 /**
80008  * @class Ext.layout.container.AbstractCard
80009  * @extends Ext.layout.container.Fit
80010  * <p>This layout manages multiple child Components, each is fit to the Container, where only a single child Component
80011  * can be visible at any given time.  This layout style is most commonly used for wizards, tab implementations, etc.
80012  * This class is intended to be extended or created via the layout:'card' {@link Ext.container.Container#layout} config,
80013  * and should generally not need to be created directly via the new keyword.</p>
80014  * <p>The CardLayout's focal method is {@link #setActiveItem}.  Since only one panel is displayed at a time,
80015  * the only way to move from one Component to the next is by calling setActiveItem, passing the id or index of
80016  * the next panel to display.  The layout itself does not provide a user interface for handling this navigation,
80017  * so that functionality must be provided by the developer.</p>
80018  * <p>Containers that are configured with a card layout will have a method setActiveItem dynamically added to it.
80019  * <pre><code>
80020       var p = new Ext.panel.Panel({
80021           fullscreen: true,
80022           layout: 'card',
80023           items: [{
80024               html: 'Card 1'
80025           },{
80026               html: 'Card 2'
80027           }]
80028       });
80029       p.setActiveItem(1);
80030    </code></pre>
80031  * </p>
80032  */
80033
80034 Ext.define('Ext.layout.container.AbstractCard', {
80035
80036     /* Begin Definitions */
80037
80038     extend: 'Ext.layout.container.Fit',
80039
80040     /* End Definitions */
80041
80042     type: 'card',
80043
80044     sizeAllCards: false,
80045
80046     hideInactive: true,
80047
80048     /**
80049      * @cfg {Boolean} deferredRender
80050      * True to render each contained item at the time it becomes active, false to render all contained items
80051      * as soon as the layout is rendered (defaults to false).  If there is a significant amount of content or
80052      * a lot of heavy controls being rendered into panels that are not displayed by default, setting this to
80053      * true might improve performance.
80054      */
80055     deferredRender : false,
80056
80057     beforeLayout: function() {
80058         var me = this;
80059         me.activeItem = me.getActiveItem();
80060         if (me.activeItem && me.deferredRender) {
80061             me.renderItems([me.activeItem], me.getRenderTarget());
80062             return true;
80063         }
80064         else {
80065             return this.callParent(arguments);
80066         }
80067     },
80068
80069     onLayout: function() {
80070         var me = this,
80071             activeItem = me.activeItem,
80072             items = me.getVisibleItems(),
80073             ln = items.length,
80074             targetBox = me.getTargetBox(),
80075             i, item;
80076
80077         for (i = 0; i < ln; i++) {
80078             item = items[i];
80079             me.setItemBox(item, targetBox);
80080         }
80081
80082         if (!me.firstActivated && activeItem) {
80083             if (activeItem.fireEvent('beforeactivate', activeItem) !== false) {
80084                 activeItem.fireEvent('activate', activeItem);
80085             }
80086             me.firstActivated = true;
80087         }
80088     },
80089
80090     isValidParent : function(item, target, position) {
80091         // Note: Card layout does not care about order within the target because only one is ever visible.
80092         // We only care whether the item is a direct child of the target.
80093         var itemEl = item.el ? item.el.dom : Ext.getDom(item);
80094         return (itemEl && itemEl.parentNode === (target.dom || target)) || false;
80095     },
80096
80097     /**
80098      * Return the active (visible) component in the layout.
80099      * @returns {Ext.Component}
80100      */
80101     getActiveItem: function() {
80102         var me = this;
80103         if (!me.activeItem && me.owner) {
80104             me.activeItem = me.parseActiveItem(me.owner.activeItem);
80105         }
80106
80107         if (me.activeItem && me.owner.items.indexOf(me.activeItem) != -1) {
80108             return me.activeItem;
80109         }
80110
80111         return null;
80112     },
80113
80114     // @private
80115     parseActiveItem: function(item) {
80116         if (item && item.isComponent) {
80117             return item;
80118         }
80119         else if (typeof item == 'number' || item === undefined) {
80120             return this.getLayoutItems()[item || 0];
80121         }
80122         else {
80123             return this.owner.getComponent(item);
80124         }
80125     },
80126
80127     // @private
80128     configureItem: function(item, position) {
80129         this.callParent([item, position]);
80130         if (this.hideInactive && this.activeItem !== item) {
80131             item.hide();
80132         }
80133         else {
80134             item.show();
80135         }
80136     },
80137
80138     onRemove: function(component) {
80139         if (component === this.activeItem) {
80140             this.activeItem = null;
80141             if (this.owner.items.getCount() === 0) {
80142                 this.firstActivated = false;
80143             }
80144         }
80145     },
80146
80147     // @private
80148     getAnimation: function(newCard, owner) {
80149         var newAnim = (newCard || {}).cardSwitchAnimation;
80150         if (newAnim === false) {
80151             return false;
80152         }
80153         return newAnim || owner.cardSwitchAnimation;
80154     },
80155
80156     /**
80157      * Return the active (visible) component in the layout to the next card
80158      * @returns {Ext.Component}
80159      */
80160     getNext: function(wrap) {
80161         //NOTE: Removed the JSDoc for this function's arguments because it is not actually supported in 4.0. This 
80162         //should come back in 4.1
80163         
80164         var items = this.getLayoutItems(),
80165             index = Ext.Array.indexOf(items, this.activeItem);
80166         return items[index + 1] || (wrap ? items[0] : false);
80167     },
80168
80169     /**
80170      * Sets the active (visible) component in the layout to the next card
80171      */
80172     next: function(anim, wrap) {
80173         //NOTE: Removed the JSDoc for this function's arguments because it is not actually supported in 4.0. This 
80174         //should come back in 4.1
80175         
80176         return this.setActiveItem(this.getNext(wrap), anim);
80177     },
80178
80179     /**
80180      * Return the active (visible) component in the layout to the previous card
80181      * @returns {Ext.Component}
80182      */
80183     getPrev: function(wrap) {
80184         //NOTE: Removed the JSDoc for this function's arguments because it is not actually supported in 4.0. This 
80185         //should come back in 4.1
80186         
80187         var items = this.getLayoutItems(),
80188             index = Ext.Array.indexOf(items, this.activeItem);
80189         return items[index - 1] || (wrap ? items[items.length - 1] : false);
80190     },
80191
80192     /**
80193      * Sets the active (visible) component in the layout to the previous card
80194      */
80195     prev: function(anim, wrap) {
80196         //NOTE: Removed the JSDoc for this function's arguments because it is not actually supported in 4.0. This 
80197         //should come back in 4.1
80198         
80199         return this.setActiveItem(this.getPrev(wrap), anim);
80200     }
80201 });
80202
80203 /**
80204  * @class Ext.selection.Model
80205  * @extends Ext.util.Observable
80206  *
80207  * Tracks what records are currently selected in a databound widget.
80208  *
80209  * This is an abstract class and is not meant to be directly used.
80210  *
80211  * DataBound UI widgets such as GridPanel, TreePanel, and ListView
80212  * should subclass AbstractStoreSelectionModel and provide a way
80213  * to binding to the component.
80214  *
80215  * The abstract methods onSelectChange and onLastFocusChanged should
80216  * be implemented in these subclasses to update the UI widget.
80217  */
80218 Ext.define('Ext.selection.Model', {
80219     extend: 'Ext.util.Observable',
80220     alternateClassName: 'Ext.AbstractStoreSelectionModel',
80221     requires: ['Ext.data.StoreManager'],
80222     // lastSelected
80223
80224     /**
80225      * @cfg {String} mode
80226      * Modes of selection.
80227      * Valid values are SINGLE, SIMPLE, and MULTI. Defaults to 'SINGLE'
80228      */
80229     
80230     /**
80231      * @cfg {Boolean} allowDeselect
80232      * Allow users to deselect a record in a DataView, List or Grid. Only applicable when the SelectionModel's mode is 'SINGLE'. Defaults to false.
80233      */
80234     allowDeselect: false,
80235
80236     /**
80237      * @property selected
80238      * READ-ONLY A MixedCollection that maintains all of the currently selected
80239      * records.
80240      */
80241     selected: null,
80242     
80243     
80244     /**
80245      * Prune records when they are removed from the store from the selection.
80246      * This is a private flag. For an example of its usage, take a look at
80247      * Ext.selection.TreeModel.
80248      * @private
80249      */
80250     pruneRemoved: true,
80251
80252     constructor: function(cfg) {
80253         var me = this;
80254         
80255         cfg = cfg || {};
80256         Ext.apply(me, cfg);
80257         
80258         me.addEvents(
80259             /**
80260              * @event selectionchange
80261              * Fired after a selection change has occurred
80262              * @param {Ext.selection.Model} this
80263              * @param  {Array} selected The selected records
80264              */
80265              'selectionchange'
80266         );
80267
80268         me.modes = {
80269             SINGLE: true,
80270             SIMPLE: true,
80271             MULTI: true
80272         };
80273
80274         // sets this.selectionMode
80275         me.setSelectionMode(cfg.mode || me.mode);
80276
80277         // maintains the currently selected records.
80278         me.selected = Ext.create('Ext.util.MixedCollection');
80279         
80280         me.callParent(arguments);
80281     },
80282
80283     // binds the store to the selModel.
80284     bind : function(store, initial){
80285         var me = this;
80286         
80287         if(!initial && me.store){
80288             if(store !== me.store && me.store.autoDestroy){
80289                 me.store.destroy();
80290             }else{
80291                 me.store.un("add", me.onStoreAdd, me);
80292                 me.store.un("clear", me.onStoreClear, me);
80293                 me.store.un("remove", me.onStoreRemove, me);
80294                 me.store.un("update", me.onStoreUpdate, me);
80295             }
80296         }
80297         if(store){
80298             store = Ext.data.StoreManager.lookup(store);
80299             store.on({
80300                 add: me.onStoreAdd,
80301                 clear: me.onStoreClear,
80302                 remove: me.onStoreRemove,
80303                 update: me.onStoreUpdate,
80304                 scope: me
80305             });
80306         }
80307         me.store = store;
80308         if(store && !initial) {
80309             me.refresh();
80310         }
80311     },
80312
80313     selectAll: function(silent) {
80314         var selections = this.store.getRange(),
80315             i = 0,
80316             len = selections.length;
80317             
80318         for (; i < len; i++) {
80319             this.doSelect(selections[i], true, silent);
80320         }
80321     },
80322
80323     deselectAll: function() {
80324         var selections = this.getSelection(),
80325             i = 0,
80326             len = selections.length;
80327             
80328         for (; i < len; i++) {
80329             this.doDeselect(selections[i]);
80330         }
80331     },
80332
80333     // Provides differentiation of logic between MULTI, SIMPLE and SINGLE
80334     // selection modes. Requires that an event be passed so that we can know
80335     // if user held ctrl or shift.
80336     selectWithEvent: function(record, e) {
80337         var me = this;
80338         
80339         switch (me.selectionMode) {
80340             case 'MULTI':
80341                 if (e.ctrlKey && me.isSelected(record)) {
80342                     me.doDeselect(record, false);
80343                 } else if (e.shiftKey && me.lastFocused) {
80344                     me.selectRange(me.lastFocused, record, e.ctrlKey);
80345                 } else if (e.ctrlKey) {
80346                     me.doSelect(record, true, false);
80347                 } else if (me.isSelected(record) && !e.shiftKey && !e.ctrlKey && me.selected.getCount() > 1) {
80348                     me.doSelect(record, false, false);
80349                 } else {
80350                     me.doSelect(record, false);
80351                 }
80352                 break;
80353             case 'SIMPLE':
80354                 if (me.isSelected(record)) {
80355                     me.doDeselect(record);
80356                 } else {
80357                     me.doSelect(record, true);
80358                 }
80359                 break;
80360             case 'SINGLE':
80361                 // if allowDeselect is on and this record isSelected, deselect it
80362                 if (me.allowDeselect && me.isSelected(record)) {
80363                     me.doDeselect(record);
80364                 // select the record and do NOT maintain existing selections
80365                 } else {
80366                     me.doSelect(record, false);
80367                 }
80368                 break;
80369         }
80370     },
80371
80372     /**
80373      * Selects a range of rows if the selection model {@link #isLocked is not locked}.
80374      * All rows in between startRow and endRow are also selected.
80375      * @param {Ext.data.Model/Number} startRow The record or index of the first row in the range
80376      * @param {Ext.data.Model/Number} endRow The record or index of the last row in the range
80377      * @param {Boolean} keepExisting (optional) True to retain existing selections
80378      */
80379     selectRange : function(startRow, endRow, keepExisting, dir){
80380         var me = this,
80381             store = me.store,
80382             selectedCount = 0,
80383             i,
80384             tmp,
80385             dontDeselect,
80386             records = [];
80387         
80388         if (me.isLocked()){
80389             return;
80390         }
80391         
80392         if (!keepExisting) {
80393             me.clearSelections();
80394         }
80395         
80396         if (!Ext.isNumber(startRow)) {
80397             startRow = store.indexOf(startRow);
80398         } 
80399         if (!Ext.isNumber(endRow)) {
80400             endRow = store.indexOf(endRow);
80401         }
80402         
80403         // swap values
80404         if (startRow > endRow){
80405             tmp = endRow;
80406             endRow = startRow;
80407             startRow = tmp;
80408         }
80409
80410         for (i = startRow; i <= endRow; i++) {
80411             if (me.isSelected(store.getAt(i))) {
80412                 selectedCount++;
80413             }
80414         }
80415
80416         if (!dir) {
80417             dontDeselect = -1;
80418         } else {
80419             dontDeselect = (dir == 'up') ? startRow : endRow;
80420         }
80421         
80422         for (i = startRow; i <= endRow; i++){
80423             if (selectedCount == (endRow - startRow + 1)) {
80424                 if (i != dontDeselect) {
80425                     me.doDeselect(i, true);
80426                 }
80427             } else {
80428                 records.push(store.getAt(i));
80429             }
80430         }
80431         me.doMultiSelect(records, true);
80432     },
80433     
80434     /**
80435      * Selects a record instance by record instance or index.
80436      * @param {Ext.data.Model/Index} records An array of records or an index
80437      * @param {Boolean} keepExisting
80438      * @param {Boolean} suppressEvent Set to false to not fire a select event
80439      */
80440     select: function(records, keepExisting, suppressEvent) {
80441         this.doSelect(records, keepExisting, suppressEvent);
80442     },
80443
80444     /**
80445      * Deselects a record instance by record instance or index.
80446      * @param {Ext.data.Model/Index} records An array of records or an index
80447      * @param {Boolean} suppressEvent Set to false to not fire a deselect event
80448      */
80449     deselect: function(records, suppressEvent) {
80450         this.doDeselect(records, suppressEvent);
80451     },
80452     
80453     doSelect: function(records, keepExisting, suppressEvent) {
80454         var me = this,
80455             record;
80456             
80457         if (me.locked) {
80458             return;
80459         }
80460         if (typeof records === "number") {
80461             records = [me.store.getAt(records)];
80462         }
80463         if (me.selectionMode == "SINGLE" && records) {
80464             record = records.length ? records[0] : records;
80465             me.doSingleSelect(record, suppressEvent);
80466         } else {
80467             me.doMultiSelect(records, keepExisting, suppressEvent);
80468         }
80469     },
80470
80471     doMultiSelect: function(records, keepExisting, suppressEvent) {
80472         var me = this,
80473             selected = me.selected,
80474             change = false,
80475             i = 0,
80476             len, record;
80477             
80478         if (me.locked) {
80479             return;
80480         }
80481         
80482
80483         records = !Ext.isArray(records) ? [records] : records;
80484         len = records.length;
80485         if (!keepExisting && selected.getCount() > 0) {
80486             change = true;
80487             me.doDeselect(me.getSelection(), true);
80488         }
80489
80490         for (; i < len; i++) {
80491             record = records[i];
80492             if (keepExisting && me.isSelected(record)) {
80493                 continue;
80494             }
80495             change = true;
80496             me.lastSelected = record;
80497             selected.add(record);
80498
80499             me.onSelectChange(record, true, suppressEvent);
80500         }
80501         me.setLastFocused(record, suppressEvent);
80502         // fire selchange if there was a change and there is no suppressEvent flag
80503         me.maybeFireSelectionChange(change && !suppressEvent);
80504     },
80505
80506     // records can be an index, a record or an array of records
80507     doDeselect: function(records, suppressEvent) {
80508         var me = this,
80509             selected = me.selected,
80510             change = false,
80511             i = 0,
80512             len, record;
80513             
80514         if (me.locked) {
80515             return;
80516         }
80517
80518         if (typeof records === "number") {
80519             records = [me.store.getAt(records)];
80520         }
80521
80522         records = !Ext.isArray(records) ? [records] : records;
80523         len = records.length;
80524         for (; i < len; i++) {
80525             record = records[i];
80526             if (selected.remove(record)) {
80527                 if (me.lastSelected == record) {
80528                     me.lastSelected = selected.last();
80529                 }
80530                 me.onSelectChange(record, false, suppressEvent);
80531                 change = true;
80532             }
80533         }
80534         // fire selchange if there was a change and there is no suppressEvent flag
80535         me.maybeFireSelectionChange(change && !suppressEvent);
80536     },
80537
80538     doSingleSelect: function(record, suppressEvent) {
80539         var me = this,
80540             selected = me.selected;
80541             
80542         if (me.locked) {
80543             return;
80544         }
80545         // already selected.
80546         // should we also check beforeselect?
80547         if (me.isSelected(record)) {
80548             return;
80549         }
80550         if (selected.getCount() > 0) {
80551             me.doDeselect(me.lastSelected, suppressEvent);
80552         }
80553         selected.add(record);
80554         me.lastSelected = record;
80555         me.onSelectChange(record, true, suppressEvent);
80556         if (!suppressEvent) {
80557             me.setLastFocused(record);
80558         }
80559         me.maybeFireSelectionChange(!suppressEvent);
80560     },
80561
80562     /**
80563      * @param {Ext.data.Model} record
80564      * Set a record as the last focused record. This does NOT mean
80565      * that the record has been selected.
80566      */
80567     setLastFocused: function(record, supressFocus) {
80568         var me = this,
80569             recordBeforeLast = me.lastFocused;
80570         me.lastFocused = record;
80571         me.onLastFocusChanged(recordBeforeLast, record, supressFocus);
80572     },
80573     
80574     /**
80575      * Determines if this record is currently focused.
80576      * @param Ext.data.Record record
80577      */
80578     isFocused: function(record) {
80579         return record === this.getLastFocused();
80580     },
80581
80582
80583     // fire selection change as long as true is not passed
80584     // into maybeFireSelectionChange
80585     maybeFireSelectionChange: function(fireEvent) {
80586         if (fireEvent) {
80587             var me = this;
80588             me.fireEvent('selectionchange', me, me.getSelection());
80589         }
80590     },
80591
80592     /**
80593      * Returns the last selected record.
80594      */
80595     getLastSelected: function() {
80596         return this.lastSelected;
80597     },
80598     
80599     getLastFocused: function() {
80600         return this.lastFocused;
80601     },
80602
80603     /**
80604      * Returns an array of the currently selected records.
80605      */
80606     getSelection: function() {
80607         return this.selected.getRange();
80608     },
80609
80610     /**
80611      * Returns the current selectionMode. SINGLE, MULTI or SIMPLE.
80612      */
80613     getSelectionMode: function() {
80614         return this.selectionMode;
80615     },
80616
80617     /**
80618      * Sets the current selectionMode. SINGLE, MULTI or SIMPLE.
80619      */
80620     setSelectionMode: function(selMode) {
80621         selMode = selMode ? selMode.toUpperCase() : 'SINGLE';
80622         // set to mode specified unless it doesnt exist, in that case
80623         // use single.
80624         this.selectionMode = this.modes[selMode] ? selMode : 'SINGLE';
80625     },
80626
80627     /**
80628      * Returns true if the selections are locked.
80629      * @return {Boolean}
80630      */
80631     isLocked: function() {
80632         return this.locked;
80633     },
80634
80635     /**
80636      * Locks the current selection and disables any changes from
80637      * happening to the selection.
80638      * @param {Boolean} locked
80639      */
80640     setLocked: function(locked) {
80641         this.locked = !!locked;
80642     },
80643
80644     /**
80645      * Returns <tt>true</tt> if the specified row is selected.
80646      * @param {Record/Number} record The record or index of the record to check
80647      * @return {Boolean}
80648      */
80649     isSelected: function(record) {
80650         record = Ext.isNumber(record) ? this.store.getAt(record) : record;
80651         return this.selected.indexOf(record) !== -1;
80652     },
80653     
80654     /**
80655      * Returns true if there is a selected record.
80656      * @return {Boolean}
80657      */
80658     hasSelection: function() {
80659         return this.selected.getCount() > 0;
80660     },
80661
80662     refresh: function() {
80663         var me = this,
80664             toBeSelected = [],
80665             oldSelections = me.getSelection(),
80666             len = oldSelections.length,
80667             selection,
80668             change,
80669             i = 0,
80670             lastFocused = this.getLastFocused();
80671
80672         // check to make sure that there are no records
80673         // missing after the refresh was triggered, prune
80674         // them from what is to be selected if so
80675         for (; i < len; i++) {
80676             selection = oldSelections[i];
80677             if (!this.pruneRemoved || me.store.indexOf(selection) !== -1) {
80678                 toBeSelected.push(selection);
80679             }
80680         }
80681
80682         // there was a change from the old selected and
80683         // the new selection
80684         if (me.selected.getCount() != toBeSelected.length) {
80685             change = true;
80686         }
80687
80688         me.clearSelections();
80689         
80690         if (me.store.indexOf(lastFocused) !== -1) {
80691             // restore the last focus but supress restoring focus
80692             this.setLastFocused(lastFocused, true);
80693         }
80694
80695         if (toBeSelected.length) {
80696             // perform the selection again
80697             me.doSelect(toBeSelected, false, true);
80698         }
80699         
80700         me.maybeFireSelectionChange(change);
80701     },
80702
80703     clearSelections: function() {
80704         // reset the entire selection to nothing
80705         var me = this;
80706         me.selected.clear();
80707         me.lastSelected = null;
80708         me.setLastFocused(null);
80709     },
80710
80711     // when a record is added to a store
80712     onStoreAdd: function() {
80713
80714     },
80715
80716     // when a store is cleared remove all selections
80717     // (if there were any)
80718     onStoreClear: function() {
80719         var me = this,
80720             selected = this.selected;
80721             
80722         if (selected.getCount > 0) {
80723             selected.clear();
80724             me.lastSelected = null;
80725             me.setLastFocused(null);
80726             me.maybeFireSelectionChange(true);
80727         }
80728     },
80729
80730     // prune records from the SelectionModel if
80731     // they were selected at the time they were
80732     // removed.
80733     onStoreRemove: function(store, record) {
80734         var me = this,
80735             selected = me.selected;
80736             
80737         if (me.locked || !me.pruneRemoved) {
80738             return;
80739         }
80740
80741         if (selected.remove(record)) {
80742             if (me.lastSelected == record) {
80743                 me.lastSelected = null;
80744             }
80745             if (me.getLastFocused() == record) {
80746                 me.setLastFocused(null);
80747             }
80748             me.maybeFireSelectionChange(true);
80749         }
80750     },
80751
80752     getCount: function() {
80753         return this.selected.getCount();
80754     },
80755
80756     // cleanup.
80757     destroy: function() {
80758
80759     },
80760
80761     // if records are updated
80762     onStoreUpdate: function() {
80763
80764     },
80765
80766     // @abstract
80767     onSelectChange: function(record, isSelected, suppressEvent) {
80768
80769     },
80770
80771     // @abstract
80772     onLastFocusChanged: function(oldFocused, newFocused) {
80773
80774     },
80775
80776     // @abstract
80777     onEditorKey: function(field, e) {
80778
80779     },
80780
80781     // @abstract
80782     bindComponent: function(cmp) {
80783
80784     }
80785 });
80786 /**
80787  * @class Ext.selection.DataViewModel
80788  * @ignore
80789  */
80790 Ext.define('Ext.selection.DataViewModel', {
80791     extend: 'Ext.selection.Model',
80792     
80793     requires: ['Ext.util.KeyNav'],
80794
80795     deselectOnContainerClick: true,
80796     
80797     /**
80798      * @cfg {Boolean} enableKeyNav
80799      * 
80800      * Turns on/off keyboard navigation within the DataView. Defaults to true.
80801      */
80802     enableKeyNav: true,
80803     
80804     constructor: function(cfg){
80805         this.addEvents(
80806             /**
80807              * @event deselect
80808              * Fired after a record is deselected
80809              * @param {Ext.selection.DataViewModel} this
80810              * @param  {Ext.data.Model} record The deselected record
80811              */
80812             'deselect',
80813             
80814             /**
80815              * @event select
80816              * Fired after a record is selected
80817              * @param {Ext.selection.DataViewModel} this
80818              * @param  {Ext.data.Model} record The selected record
80819              */
80820             'select'
80821         );
80822         this.callParent(arguments);
80823     },
80824     
80825     bindComponent: function(view) {
80826         var me = this,
80827             eventListeners = {
80828                 refresh: me.refresh,
80829                 scope: me
80830             };
80831
80832         me.view = view;
80833         me.bind(view.getStore());
80834
80835         view.on(view.triggerEvent, me.onItemClick, me);
80836         view.on(view.triggerCtEvent, me.onContainerClick, me);
80837
80838         view.on(eventListeners);
80839
80840         if (me.enableKeyNav) {
80841             me.initKeyNav(view);
80842         }
80843     },
80844
80845     onItemClick: function(view, record, item, index, e) {
80846         this.selectWithEvent(record, e);
80847     },
80848
80849     onContainerClick: function() {
80850         if (this.deselectOnContainerClick) {
80851             this.deselectAll();
80852         }
80853     },
80854     
80855     initKeyNav: function(view) {
80856         var me = this;
80857         
80858         if (!view.rendered) {
80859             view.on('render', Ext.Function.bind(me.initKeyNav, me, [view], 0), me, {single: true});
80860             return;
80861         }
80862         
80863         view.el.set({
80864             tabIndex: -1
80865         });
80866         me.keyNav = Ext.create('Ext.util.KeyNav', view.el, {
80867             down: Ext.pass(me.onNavKey, [1], me),
80868             right: Ext.pass(me.onNavKey, [1], me),
80869             left: Ext.pass(me.onNavKey, [-1], me),
80870             up: Ext.pass(me.onNavKey, [-1], me),
80871             scope: me
80872         });
80873     },
80874     
80875     onNavKey: function(step) {
80876         step = step || 1;
80877         var me = this,
80878             view = me.view,
80879             selected = me.getSelection()[0],
80880             numRecords = me.view.store.getCount(),
80881             idx;
80882                 
80883         if (selected) {
80884             idx = view.indexOf(view.getNode(selected)) + step;
80885         } else {
80886             idx = 0;
80887         }
80888         
80889         if (idx < 0) {
80890             idx = numRecords - 1;
80891         } else if (idx >= numRecords) {
80892             idx = 0;
80893         }
80894         
80895         me.select(idx);
80896     },
80897
80898     // Allow the DataView to update the ui
80899     onSelectChange: function(record, isSelected, suppressEvent) {
80900         var me = this,
80901             view = me.view,
80902             allowSelect = true;
80903         
80904         if (isSelected) {
80905             if (!suppressEvent) {
80906                 allowSelect = me.fireEvent('beforeselect', me, record) !== false;
80907             }
80908             if (allowSelect) {
80909                 view.onItemSelect(record);
80910                 if (!suppressEvent) {
80911                     me.fireEvent('select', me, record);
80912                 }
80913             }
80914         } else {
80915             view.onItemDeselect(record);
80916             if (!suppressEvent) {
80917                 me.fireEvent('deselect', me, record);
80918             }
80919         }
80920     }
80921 });
80922
80923 /**
80924  * @class Ext.state.CookieProvider
80925  * @extends Ext.state.Provider
80926  * A Provider implementation which saves and retrieves state via cookies.
80927  * The CookieProvider supports the usual cookie options, such as:
80928  * <ul>
80929  * <li>{@link #path}</li>
80930  * <li>{@link #expires}</li>
80931  * <li>{@link #domain}</li>
80932  * <li>{@link #secure}</li>
80933  * </ul>
80934  <pre><code>
80935    var cp = new Ext.state.CookieProvider({
80936        path: "/cgi-bin/",
80937        expires: new Date(new Date().getTime()+(1000*60*60*24*30)), //30 days
80938        domain: "sencha.com"
80939    });
80940    Ext.state.Manager.setProvider(cp);
80941  </code></pre>
80942  
80943  
80944  * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
80945  * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
80946  * @cfg {String} domain The domain to save the cookie for.  Note that you cannot specify a different domain than
80947  * your page is on, but you can specify a sub-domain, or simply the domain itself like 'sencha.com' to include
80948  * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
80949  * domain the page is running on including the 'www' like 'www.sencha.com')
80950  * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
80951  * @constructor
80952  * Create a new CookieProvider
80953  * @param {Object} config The configuration object
80954  */
80955 Ext.define('Ext.state.CookieProvider', {
80956     extend: 'Ext.state.Provider',
80957
80958     constructor : function(config){
80959         var me = this;
80960         me.path = "/";
80961         me.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
80962         me.domain = null;
80963         me.secure = false;
80964         me.callParent(arguments);
80965         me.state = me.readCookies();
80966     },
80967     
80968     // private
80969     set : function(name, value){
80970         var me = this;
80971         
80972         if(typeof value == "undefined" || value === null){
80973             me.clear(name);
80974             return;
80975         }
80976         me.setCookie(name, value);
80977         me.callParent(arguments);
80978     },
80979
80980     // private
80981     clear : function(name){
80982         this.clearCookie(name);
80983         this.callParent(arguments);
80984     },
80985
80986     // private
80987     readCookies : function(){
80988         var cookies = {},
80989             c = document.cookie + ";",
80990             re = /\s?(.*?)=(.*?);/g,
80991             prefix = this.prefix,
80992             len = prefix.length,
80993             matches,
80994             name,
80995             value;
80996             
80997         while((matches = re.exec(c)) != null){
80998             name = matches[1];
80999             value = matches[2];
81000             if (name && name.substring(0, len) == prefix){
81001                 cookies[name.substr(len)] = this.decodeValue(value);
81002             }
81003         }
81004         return cookies;
81005     },
81006
81007     // private
81008     setCookie : function(name, value){
81009         var me = this;
81010         
81011         document.cookie = me.prefix + name + "=" + me.encodeValue(value) +
81012            ((me.expires == null) ? "" : ("; expires=" + me.expires.toGMTString())) +
81013            ((me.path == null) ? "" : ("; path=" + me.path)) +
81014            ((me.domain == null) ? "" : ("; domain=" + me.domain)) +
81015            ((me.secure == true) ? "; secure" : "");
81016     },
81017
81018     // private
81019     clearCookie : function(name){
81020         var me = this;
81021         
81022         document.cookie = me.prefix + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
81023            ((me.path == null) ? "" : ("; path=" + me.path)) +
81024            ((me.domain == null) ? "" : ("; domain=" + me.domain)) +
81025            ((me.secure == true) ? "; secure" : "");
81026     }
81027 });
81028
81029 Ext.define('Ext.state.LocalStorageProvider', {
81030     /* Begin Definitions */
81031     
81032     extend: 'Ext.state.Provider',
81033     
81034     alias: 'state.localstorage',
81035     
81036     /* End Definitions */
81037    
81038     constructor: function(){
81039         var me = this;
81040         me.callParent(arguments);
81041         me.store = me.getStorageObject();
81042         me.state = me.readLocalStorage();
81043     },
81044     
81045     readLocalStorage: function(){
81046         var store = this.store,
81047             i = 0,
81048             len = store.length,
81049             prefix = this.prefix,
81050             prefixLen = prefix.length,
81051             data = {},
81052             key;
81053             
81054         for (; i < len; ++i) {
81055             key = store.key(i);
81056             if (key.substring(0, prefixLen) == prefix) {
81057                 data[key.substr(prefixLen)] = this.decodeValue(store.getItem(key));
81058             }            
81059         }
81060         return data;
81061     },
81062     
81063     set : function(name, value){
81064         var me = this;
81065         
81066         me.clear(name);
81067         if (typeof value == "undefined" || value === null) {
81068             return;
81069         }
81070         me.store.setItem(me.prefix + name, me.encodeValue(value));
81071         me.callParent(arguments);
81072     },
81073
81074     // private
81075     clear : function(name){
81076         this.store.removeItem(this.prefix + name);
81077         this.callParent(arguments);
81078     },
81079     
81080     getStorageObject: function(){
81081         try {
81082             var supports = 'localStorage' in window && window['localStorage'] !== null;
81083             if (supports) {
81084                 return window.localStorage;
81085             }
81086         } catch (e) {
81087             return false;
81088         }
81089         Ext.Error.raise('LocalStorage is not supported by the current browser');
81090     }    
81091 });
81092
81093 /**
81094  * @class Ext.util.Point
81095  * @extends Ext.util.Region
81096  *
81097  * Represents a 2D point with x and y properties, useful for comparison and instantiation
81098  * from an event:
81099  * <pre><code>
81100  * var point = Ext.util.Point.fromEvent(e);
81101  * </code></pre>
81102  */
81103
81104 Ext.define('Ext.util.Point', {
81105
81106     /* Begin Definitions */
81107     extend: 'Ext.util.Region',
81108
81109     statics: {
81110
81111         /**
81112          * Returns a new instance of Ext.util.Point base on the pageX / pageY values of the given event
81113          * @static
81114          * @param {Event} e The event
81115          * @returns Ext.util.Point
81116          */
81117         fromEvent: function(e) {
81118             e = (e.changedTouches && e.changedTouches.length > 0) ? e.changedTouches[0] : e;
81119             return new this(e.pageX, e.pageY);
81120         }
81121     },
81122
81123     /* End Definitions */
81124
81125     constructor: function(x, y) {
81126         this.callParent([y, x, y, x]);
81127     },
81128
81129     /**
81130      * Returns a human-eye-friendly string that represents this point,
81131      * useful for debugging
81132      * @return {String}
81133      */
81134     toString: function() {
81135         return "Point[" + this.x + "," + this.y + "]";
81136     },
81137
81138     /**
81139      * Compare this point and another point
81140      * @param {Ext.util.Point/Object} The point to compare with, either an instance
81141      * of Ext.util.Point or an object with left and top properties
81142      * @return {Boolean} Returns whether they are equivalent
81143      */
81144     equals: function(p) {
81145         return (this.x == p.x && this.y == p.y);
81146     },
81147
81148     /**
81149      * Whether the given point is not away from this point within the given threshold amount.
81150      * TODO: Rename this isNear.
81151      * @param {Ext.util.Point/Object} The point to check with, either an instance
81152      * of Ext.util.Point or an object with left and top properties
81153      * @param {Object/Number} threshold Can be either an object with x and y properties or a number
81154      * @return {Boolean}
81155      */
81156     isWithin: function(p, threshold) {
81157         if (!Ext.isObject(threshold)) {
81158             threshold = {
81159                 x: threshold,
81160                 y: threshold
81161             };
81162         }
81163
81164         return (this.x <= p.x + threshold.x && this.x >= p.x - threshold.x &&
81165                 this.y <= p.y + threshold.y && this.y >= p.y - threshold.y);
81166     },
81167
81168     /**
81169      * Compare this point with another point when the x and y values of both points are rounded. E.g:
81170      * [100.3,199.8] will equals to [100, 200]
81171      * @param {Ext.util.Point/Object} The point to compare with, either an instance
81172      * of Ext.util.Point or an object with x and y properties
81173      * @return {Boolean}
81174      */
81175     roundedEquals: function(p) {
81176         return (Math.round(this.x) == Math.round(p.x) && Math.round(this.y) == Math.round(p.y));
81177     }
81178 }, function() {
81179     /**
81180      * Translate this region by the given offset amount. TODO: Either use translate or translateBy!
81181      * @param {Ext.util.Offset/Object} offset Object containing the <code>x</code> and <code>y</code> properties.
81182      * Or the x value is using the two argument form.
81183      * @param {Number} The y value unless using an Offset object.
81184      * @return {Ext.util.Region} this This Region
81185      */
81186     this.prototype.translate = Ext.util.Region.prototype.translateBy;
81187 });
81188
81189 /**
81190  * @class Ext.view.AbstractView
81191  * @extends Ext.Component
81192  * This is an abstract superclass and should not be used directly. Please see {@link Ext.view.View}.
81193  */
81194 Ext.define('Ext.view.AbstractView', {
81195     extend: 'Ext.Component',
81196     alternateClassName: 'Ext.view.AbstractView',
81197     requires: [
81198         'Ext.LoadMask',
81199         'Ext.data.StoreManager',
81200         'Ext.CompositeElementLite',
81201         'Ext.DomQuery',
81202         'Ext.selection.DataViewModel'
81203     ],
81204     
81205     inheritableStatics: {
81206         getRecord: function(node) {
81207             return this.getBoundView(node).getRecord(node);
81208         },
81209         
81210         getBoundView: function(node) {
81211             return Ext.getCmp(node.boundView);
81212         }
81213     },
81214     
81215     /**
81216      * @cfg {String/Array/Ext.XTemplate} tpl
81217      * @required
81218      * The HTML fragment or an array of fragments that will make up the template used by this DataView.  This should
81219      * be specified in the same format expected by the constructor of {@link Ext.XTemplate}.
81220      */
81221     /**
81222      * @cfg {Ext.data.Store} store
81223      * @required
81224      * The {@link Ext.data.Store} to bind this DataView to.
81225      */
81226
81227     /**
81228      * @cfg {String} itemSelector
81229      * @required
81230      * <b>This is a required setting</b>. A simple CSS selector (e.g. <tt>div.some-class</tt> or
81231      * <tt>span:first-child</tt>) that will be used to determine what nodes this DataView will be
81232      * working with. The itemSelector is used to map DOM nodes to records. As such, there should
81233      * only be one root level element that matches the selector for each record.
81234      */
81235     
81236     /**
81237      * @cfg {String} itemCls
81238      * Specifies the class to be assigned to each element in the view when used in conjunction with the
81239      * {@link #itemTpl} configuration.
81240      */
81241     itemCls: Ext.baseCSSPrefix + 'dataview-item',
81242     
81243     /**
81244      * @cfg {String/Array/Ext.XTemplate} itemTpl
81245      * The inner portion of the item template to be rendered. Follows an XTemplate
81246      * structure and will be placed inside of a tpl.
81247      */
81248
81249     /**
81250      * @cfg {String} overItemCls
81251      * A CSS class to apply to each item in the view on mouseover (defaults to undefined). 
81252      * Ensure {@link #trackOver} is set to `true` to make use of this.
81253      */
81254
81255     /**
81256      * @cfg {String} loadingText
81257      * A string to display during data load operations (defaults to undefined).  If specified, this text will be
81258      * displayed in a loading div and the view's contents will be cleared while loading, otherwise the view's
81259      * contents will continue to display normally until the new data is loaded and the contents are replaced.
81260      */
81261     loadingText: 'Loading...',
81262     
81263     /**
81264      * @cfg {String} loadingCls
81265      * The CSS class to apply to the loading message element (defaults to Ext.LoadMask.prototype.msgCls "x-mask-loading")
81266      */
81267     
81268     /**
81269      * @cfg {Boolean} loadingUseMsg
81270      * Whether or not to use the loading message.
81271      * @private
81272      */
81273     loadingUseMsg: true,
81274     
81275
81276     /**
81277      * @cfg {Number} loadingHeight
81278      * If specified, gives an explicit height for the data view when it is showing the {@link #loadingText},
81279      * if that is specified. This is useful to prevent the view's height from collapsing to zero when the
81280      * loading mask is applied and there are no other contents in the data view. Defaults to undefined.
81281      */
81282
81283     /**
81284      * @cfg {String} selectedItemCls
81285      * A CSS class to apply to each selected item in the view (defaults to 'x-view-selected').
81286      */
81287     selectedItemCls: Ext.baseCSSPrefix + 'item-selected',
81288
81289     /**
81290      * @cfg {String} emptyText
81291      * The text to display in the view when there is no data to display (defaults to '').
81292      * Note that when using local data the emptyText will not be displayed unless you set
81293      * the {@link #deferEmptyText} option to false.
81294      */
81295     emptyText: "",
81296
81297     /**
81298      * @cfg {Boolean} deferEmptyText True to defer emptyText being applied until the store's first load
81299      */
81300     deferEmptyText: true,
81301
81302     /**
81303      * @cfg {Boolean} trackOver True to enable mouseenter and mouseleave events
81304      */
81305     trackOver: false,
81306
81307     /**
81308      * @cfg {Boolean} blockRefresh Set this to true to ignore datachanged events on the bound store. This is useful if
81309      * you wish to provide custom transition animations via a plugin (defaults to false)
81310      */
81311     blockRefresh: false,
81312
81313     /**
81314      * @cfg {Boolean} disableSelection <p><tt>true</tt> to disable selection within the DataView. Defaults to <tt>false</tt>.
81315      * This configuration will lock the selection model that the DataView uses.</p>
81316      */
81317
81318
81319     //private
81320     last: false,
81321     
81322     triggerEvent: 'itemclick',
81323     triggerCtEvent: 'containerclick',
81324     
81325     addCmpEvents: function() {
81326         
81327     },
81328
81329     // private
81330     initComponent : function(){
81331         var me = this,
81332             isDef = Ext.isDefined,
81333             itemTpl = me.itemTpl,
81334             memberFn = {};
81335             
81336         if (itemTpl) {
81337             if (Ext.isArray(itemTpl)) {
81338                 // string array
81339                 itemTpl = itemTpl.join('');
81340             } else if (Ext.isObject(itemTpl)) {
81341                 // tpl instance
81342                 memberFn = Ext.apply(memberFn, itemTpl.initialConfig);
81343                 itemTpl = itemTpl.html;
81344             }
81345             
81346             if (!me.itemSelector) {
81347                 me.itemSelector = '.' + me.itemCls;
81348             }
81349             
81350             itemTpl = Ext.String.format('<tpl for="."><div class="{0}">{1}</div></tpl>', me.itemCls, itemTpl);
81351             me.tpl = Ext.create('Ext.XTemplate', itemTpl, memberFn);
81352         }
81353
81354         if (!isDef(me.tpl) || !isDef(me.itemSelector)) {
81355             Ext.Error.raise({
81356                 sourceClass: 'Ext.view.View',
81357                 tpl: me.tpl,
81358                 itemSelector: me.itemSelector,
81359                 msg: "DataView requires both tpl and itemSelector configurations to be defined."
81360             });
81361         }
81362
81363         me.callParent();
81364         if(Ext.isString(me.tpl) || Ext.isArray(me.tpl)){
81365             me.tpl = Ext.create('Ext.XTemplate', me.tpl);
81366         }
81367
81368         // backwards compat alias for overClass/selectedClass
81369         // TODO: Consider support for overCls generation Ext.Component config
81370         if (isDef(me.overCls) || isDef(me.overClass)) {
81371             if (Ext.isDefined(Ext.global.console)) {
81372                 Ext.global.console.warn('Ext.view.View: Using the deprecated overCls or overClass configuration. Use overItemCls instead.');
81373             }
81374             me.overItemCls = me.overCls || me.overClass;
81375             delete me.overCls;
81376             delete me.overClass;
81377         }
81378
81379         if (me.overItemCls) {
81380             me.trackOver = true;
81381         }
81382         
81383         if (isDef(me.selectedCls) || isDef(me.selectedClass)) {
81384             if (Ext.isDefined(Ext.global.console)) {
81385                 Ext.global.console.warn('Ext.view.View: Using the deprecated selectedCls or selectedClass configuration. Use selectedItemCls instead.');
81386             }
81387             me.selectedItemCls = me.selectedCls || me.selectedClass;
81388             delete me.selectedCls;
81389             delete me.selectedClass;
81390         }
81391         
81392         me.addEvents(
81393             /**
81394              * @event beforerefresh
81395              * Fires before the view is refreshed
81396              * @param {Ext.view.View} this The DataView object
81397              */
81398             'beforerefresh',
81399             /**
81400              * @event refresh
81401              * Fires when the view is refreshed
81402              * @param {Ext.view.View} this The DataView object
81403              */
81404             'refresh',
81405             /**
81406              * @event itemupdate
81407              * Fires when the node associated with an individual record is updated
81408              * @param {Ext.data.Model} record The model instance
81409              * @param {Number} index The index of the record/node
81410              * @param {HTMLElement} node The node that has just been updated
81411              */
81412             'itemupdate',
81413             /**
81414              * @event itemadd
81415              * Fires when the nodes associated with an recordset have been added to the underlying store
81416              * @param {Array[Ext.data.Model]} records The model instance
81417              * @param {Number} index The index at which the set of record/nodes starts
81418              * @param {Array[HTMLElement]} node The node that has just been updated
81419              */
81420             'itemadd',
81421             /**
81422              * @event itemremove
81423              * Fires when the node associated with an individual record is removed
81424              * @param {Ext.data.Model} record The model instance
81425              * @param {Number} index The index of the record/node
81426              */
81427             'itemremove'
81428         );
81429
81430         me.addCmpEvents();
81431
81432         if (me.store) {
81433             me.store = Ext.data.StoreManager.lookup(me.store);
81434         }
81435         me.all = new Ext.CompositeElementLite();
81436         me.getSelectionModel().bindComponent(me);
81437     },
81438
81439     onRender: function() {
81440         var me = this,
81441             loadingText = me.loadingText,
81442             loadingHeight = me.loadingHeight,
81443             undef;
81444
81445         me.callParent(arguments);
81446         if (loadingText) {
81447             
81448             // Attach the LoadMask to a *Component* so that it can be sensitive to resizing during long loads.
81449             // If this DataView is floating, then mask this DataView.
81450             // Otherwise, mask its owning Container (or this, if there *is* no owning Container).
81451             // LoadMask captures the element upon render.
81452             me.loadMask = Ext.create('Ext.LoadMask', me.floating ? me : me.ownerCt || me, {
81453                 msg: loadingText,
81454                 msgCls: me.loadingCls,
81455                 useMsg: me.loadingUseMsg,
81456                 listeners: {
81457                     beforeshow: function() {
81458                         me.getTargetEl().update('');
81459                         me.getSelectionModel().deselectAll();
81460                         me.all.clear();
81461                         if (loadingHeight) {
81462                             me.setCalculatedSize(undef, loadingHeight);
81463                         }
81464                     },
81465                     hide: function() {
81466                         if (loadingHeight) {
81467                             me.setHeight(me.height);
81468                         }
81469                     }
81470                 }
81471             });
81472         }
81473     },
81474
81475     getSelectionModel: function(){
81476         var me = this,
81477             mode = 'SINGLE';
81478
81479         if (!me.selModel) {
81480             me.selModel = {};
81481         }
81482
81483         if (me.simpleSelect) {
81484             mode = 'SIMPLE';
81485         } else if (me.multiSelect) {
81486             mode = 'MULTI';
81487         }
81488
81489         Ext.applyIf(me.selModel, {
81490             allowDeselect: me.allowDeselect,
81491             mode: mode
81492         });
81493
81494         if (!me.selModel.events) {
81495             me.selModel = Ext.create('Ext.selection.DataViewModel', me.selModel);
81496         }
81497
81498         if (!me.selModel.hasRelaySetup) {
81499             me.relayEvents(me.selModel, ['selectionchange', 'beforeselect', 'select', 'deselect']);
81500             me.selModel.hasRelaySetup = true;
81501         }
81502
81503         // lock the selection model if user
81504         // has disabled selection
81505         if (me.disableSelection) {
81506             me.selModel.locked = true;
81507         }
81508
81509         return me.selModel;
81510     },
81511
81512     /**
81513      * Refreshes the view by reloading the data from the store and re-rendering the template.
81514      */
81515     refresh: function() {
81516         var me = this,
81517             el,
81518             records;
81519             
81520         if (!me.rendered) {
81521             return;
81522         }
81523         
81524         me.fireEvent('beforerefresh', me);
81525         el = me.getTargetEl();
81526         records = me.store.getRange();
81527
81528         el.update('');
81529         if (records.length < 1) {
81530             if (!me.deferEmptyText || me.hasSkippedEmptyText) {
81531                 el.update(me.emptyText);
81532             }
81533             me.all.clear();
81534         } else {
81535             me.tpl.overwrite(el, me.collectData(records, 0));
81536             me.all.fill(Ext.query(me.getItemSelector(), el.dom));
81537             me.updateIndexes(0);
81538         }
81539         
81540         me.selModel.refresh();
81541         me.hasSkippedEmptyText = true;
81542         me.fireEvent('refresh', me);
81543     },
81544
81545     /**
81546      * Function which can be overridden to provide custom formatting for each Record that is used by this
81547      * DataView's {@link #tpl template} to render each node.
81548      * @param {Array/Object} data The raw data object that was used to create the Record.
81549      * @param {Number} recordIndex the index number of the Record being prepared for rendering.
81550      * @param {Record} record The Record being prepared for rendering.
81551      * @return {Array/Object} The formatted data in a format expected by the internal {@link #tpl template}'s overwrite() method.
81552      * (either an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}))
81553      */
81554     prepareData: function(data, index, record) {
81555         if (record) {    
81556             Ext.apply(data, record.getAssociatedData());            
81557         }
81558         return data;
81559     },
81560     
81561     /**
81562      * <p>Function which can be overridden which returns the data object passed to this
81563      * DataView's {@link #tpl template} to render the whole DataView.</p>
81564      * <p>This is usually an Array of data objects, each element of which is processed by an
81565      * {@link Ext.XTemplate XTemplate} which uses <tt>'&lt;tpl for="."&gt;'</tt> to iterate over its supplied
81566      * data object as an Array. However, <i>named</i> properties may be placed into the data object to
81567      * provide non-repeating data such as headings, totals etc.</p>
81568      * @param {Array} records An Array of {@link Ext.data.Model}s to be rendered into the DataView.
81569      * @param {Number} startIndex the index number of the Record being prepared for rendering.
81570      * @return {Array} An Array of data objects to be processed by a repeating XTemplate. May also
81571      * contain <i>named</i> properties.
81572      */
81573     collectData : function(records, startIndex){
81574         var r = [],
81575             i = 0,
81576             len = records.length;
81577
81578         for(; i < len; i++){
81579             r[r.length] = this.prepareData(records[i].data, startIndex + i, records[i]);
81580         }
81581
81582         return r;
81583     },
81584
81585     // private
81586     bufferRender : function(records, index){
81587         var div = document.createElement('div');
81588         this.tpl.overwrite(div, this.collectData(records, index));
81589         return Ext.query(this.getItemSelector(), div);
81590     },
81591
81592     // private
81593     onUpdate : function(ds, record){
81594         var me = this,
81595             index = me.store.indexOf(record),
81596             original,
81597             node;
81598
81599         if (index > -1){
81600             original = me.all.elements[index];
81601             node = me.bufferRender([record], index)[0];
81602
81603             me.all.replaceElement(index, node, true);
81604             me.updateIndexes(index, index);
81605
81606             // Maintain selection after update
81607             // TODO: Move to approriate event handler.
81608             me.selModel.refresh();
81609             me.fireEvent('itemupdate', record, index, node);
81610         }
81611
81612     },
81613
81614     // private
81615     onAdd : function(ds, records, index) {
81616         var me = this,
81617             nodes;
81618             
81619         if (me.all.getCount() === 0) {
81620             me.refresh();
81621             return;
81622         }
81623         
81624         nodes = me.bufferRender(records, index);
81625         me.doAdd(nodes, records, index);
81626
81627         me.selModel.refresh();
81628         me.updateIndexes(index);
81629         me.fireEvent('itemadd', records, index, nodes);
81630     },
81631
81632     doAdd: function(nodes, records, index) {
81633         var n, a = this.all.elements;
81634         if (index < this.all.getCount()) {
81635             n = this.all.item(index).insertSibling(nodes, 'before', true);
81636             a.splice.apply(a, [index, 0].concat(nodes));
81637         } 
81638         else {
81639             n = this.all.last().insertSibling(nodes, 'after', true);
81640             a.push.apply(a, nodes);
81641         }    
81642     },
81643     
81644     // private
81645     onRemove : function(ds, record, index) {
81646         var me = this;
81647         
81648         me.doRemove(record, index);
81649         me.updateIndexes(index);
81650         if (me.store.getCount() === 0){
81651             me.refresh();
81652         }
81653         me.fireEvent('itemremove', record, index);
81654     },
81655     
81656     doRemove: function(record, index) {
81657         this.all.removeElement(index, true);
81658     },
81659
81660     /**
81661      * Refreshes an individual node's data from the store.
81662      * @param {Number} index The item's data index in the store
81663      */
81664     refreshNode : function(index){
81665         this.onUpdate(this.store, this.store.getAt(index));
81666     },
81667
81668     // private
81669     updateIndexes : function(startIndex, endIndex) {
81670         var ns = this.all.elements,
81671             records = this.store.getRange();
81672         startIndex = startIndex || 0;
81673         endIndex = endIndex || ((endIndex === 0) ? 0 : (ns.length - 1));
81674         for(var i = startIndex; i <= endIndex; i++){
81675             ns[i].viewIndex = i;
81676             ns[i].viewRecordId = records[i].internalId;
81677             if (!ns[i].boundView) {
81678                 ns[i].boundView = this.id;
81679             }
81680         }
81681     },
81682
81683     /**
81684      * Returns the store associated with this DataView.
81685      * @return {Ext.data.Store} The store
81686      */
81687     getStore : function(){
81688         return this.store;
81689     },
81690
81691     /**
81692      * Changes the data store bound to this view and refreshes it.
81693      * @param {Store} store The store to bind to this view
81694      */
81695     bindStore : function(store, initial) {
81696         var me = this;
81697         
81698         if (!initial && me.store) {
81699             if (store !== me.store && me.store.autoDestroy) {
81700                 me.store.destroy();
81701             } 
81702             else {
81703                 me.mun(me.store, {
81704                     scope: me,
81705                     datachanged: me.onDataChanged,
81706                     add: me.onAdd,
81707                     remove: me.onRemove,
81708                     update: me.onUpdate,
81709                     clear: me.refresh
81710                 });
81711             }
81712             if (!store) {
81713                 if (me.loadMask) {
81714                     me.loadMask.bindStore(null);
81715                 }
81716                 me.store = null;
81717             }
81718         }
81719         if (store) {
81720             store = Ext.data.StoreManager.lookup(store);
81721             me.mon(store, {
81722                 scope: me,
81723                 datachanged: me.onDataChanged,
81724                 add: me.onAdd,
81725                 remove: me.onRemove,
81726                 update: me.onUpdate,
81727                 clear: me.refresh
81728             });
81729             if (me.loadMask) {
81730                 me.loadMask.bindStore(store);
81731             }
81732         }
81733         
81734         me.store = store;
81735         // Bind the store to our selection model
81736         me.getSelectionModel().bind(store);
81737         
81738         if (store) {
81739             me.refresh(true);
81740         }
81741     },
81742
81743     /**
81744      * @private
81745      * Calls this.refresh if this.blockRefresh is not true
81746      */
81747     onDataChanged: function() {
81748         if (this.blockRefresh !== true) {
81749             this.refresh.apply(this, arguments);
81750         }
81751     },
81752
81753     /**
81754      * Returns the template node the passed child belongs to, or null if it doesn't belong to one.
81755      * @param {HTMLElement} node
81756      * @return {HTMLElement} The template node
81757      */
81758     findItemByChild: function(node){
81759         return Ext.fly(node).findParent(this.getItemSelector(), this.getTargetEl());
81760     },
81761     
81762     /**
81763      * Returns the template node by the Ext.EventObject or null if it is not found.
81764      * @param {Ext.EventObject} e
81765      */
81766     findTargetByEvent: function(e) {
81767         return e.getTarget(this.getItemSelector(), this.getTargetEl());
81768     },
81769
81770
81771     /**
81772      * Gets the currently selected nodes.
81773      * @return {Array} An array of HTMLElements
81774      */
81775     getSelectedNodes: function(){
81776         var nodes   = [],
81777             records = this.selModel.getSelection(),
81778             ln = records.length,
81779             i  = 0;
81780
81781         for (; i < ln; i++) {
81782             nodes.push(this.getNode(records[i]));
81783         }
81784
81785         return nodes;
81786     },
81787
81788     /**
81789      * Gets an array of the records from an array of nodes
81790      * @param {Array} nodes The nodes to evaluate
81791      * @return {Array} records The {@link Ext.data.Model} objects
81792      */
81793     getRecords: function(nodes) {
81794         var records = [],
81795             i = 0,
81796             len = nodes.length,
81797             data = this.store.data;
81798
81799         for (; i < len; i++) {
81800             records[records.length] = data.getByKey(nodes[i].viewRecordId);
81801         }
81802
81803         return records;
81804     },
81805
81806     /**
81807      * Gets a record from a node
81808      * @param {Element/HTMLElement} node The node to evaluate
81809      * 
81810      * @return {Record} record The {@link Ext.data.Model} object
81811      */
81812     getRecord: function(node){
81813         return this.store.data.getByKey(Ext.getDom(node).viewRecordId);
81814     },
81815     
81816
81817     /**
81818      * Returns true if the passed node is selected, else false.
81819      * @param {HTMLElement/Number/Ext.data.Model} node The node, node index or record to check
81820      * @return {Boolean} True if selected, else false
81821      */
81822     isSelected : function(node) {
81823         // TODO: El/Idx/Record
81824         var r = this.getRecord(node);
81825         return this.selModel.isSelected(r);
81826     },
81827     
81828     /**
81829      * Selects a record instance by record instance or index.
81830      * @param {Ext.data.Model/Index} records An array of records or an index
81831      * @param {Boolean} keepExisting
81832      * @param {Boolean} suppressEvent Set to false to not fire a select event
81833      */
81834     select: function(records, keepExisting, suppressEvent) {
81835         this.selModel.select(records, keepExisting, suppressEvent);
81836     },
81837
81838     /**
81839      * Deselects a record instance by record instance or index.
81840      * @param {Ext.data.Model/Index} records An array of records or an index
81841      * @param {Boolean} suppressEvent Set to false to not fire a deselect event
81842      */
81843     deselect: function(records, suppressEvent) {
81844         this.selModel.deselect(records, suppressEvent);
81845     },
81846
81847     /**
81848      * Gets a template node.
81849      * @param {HTMLElement/String/Number/Ext.data.Model} nodeInfo An HTMLElement template node, index of a template node,
81850      * the id of a template node or the record associated with the node.
81851      * @return {HTMLElement} The node or null if it wasn't found
81852      */
81853     getNode : function(nodeInfo) {
81854         if (Ext.isString(nodeInfo)) {
81855             return document.getElementById(nodeInfo);
81856         } else if (Ext.isNumber(nodeInfo)) {
81857             return this.all.elements[nodeInfo];
81858         } else if (nodeInfo instanceof Ext.data.Model) {
81859             return this.getNodeByRecord(nodeInfo);
81860         }
81861         return nodeInfo;
81862     },
81863     
81864     /**
81865      * @private
81866      */
81867     getNodeByRecord: function(record) {
81868         var ns = this.all.elements,
81869             ln = ns.length,
81870             i = 0;
81871         
81872         for (; i < ln; i++) {
81873             if (ns[i].viewRecordId === record.internalId) {
81874                 return ns[i];
81875             }
81876         }
81877         
81878         return null;
81879     },
81880     
81881     /**
81882      * Gets a range nodes.
81883      * @param {Number} start (optional) The index of the first node in the range
81884      * @param {Number} end (optional) The index of the last node in the range
81885      * @return {Array} An array of nodes
81886      */
81887     getNodes: function(start, end) {
81888         var ns = this.all.elements,
81889             nodes = [],
81890             i;
81891
81892         start = start || 0;
81893         end = !Ext.isDefined(end) ? Math.max(ns.length - 1, 0) : end;
81894         if (start <= end) {
81895             for (i = start; i <= end && ns[i]; i++) {
81896                 nodes.push(ns[i]);
81897             }
81898         } else {
81899             for (i = start; i >= end && ns[i]; i--) {
81900                 nodes.push(ns[i]);
81901             }
81902         }
81903         return nodes;
81904     },
81905
81906     /**
81907      * Finds the index of the passed node.
81908      * @param {HTMLElement/String/Number/Record} nodeInfo An HTMLElement template node, index of a template node, the id of a template node
81909      * or a record associated with a node.
81910      * @return {Number} The index of the node or -1
81911      */
81912     indexOf: function(node) {
81913         node = this.getNode(node);
81914         if (Ext.isNumber(node.viewIndex)) {
81915             return node.viewIndex;
81916         }
81917         return this.all.indexOf(node);
81918     },
81919
81920     onDestroy : function() {
81921         var me = this;
81922         
81923         me.all.clear();
81924         me.callParent();
81925         me.bindStore(null);
81926         me.selModel.destroy();
81927     },
81928
81929     // invoked by the selection model to maintain visual UI cues
81930     onItemSelect: function(record) {
81931         var node = this.getNode(record);
81932         Ext.fly(node).addCls(this.selectedItemCls);
81933     },
81934
81935     // invoked by the selection model to maintain visual UI cues
81936     onItemDeselect: function(record) {
81937         var node = this.getNode(record);
81938         Ext.fly(node).removeCls(this.selectedItemCls);
81939     },
81940     
81941     getItemSelector: function() {
81942         return this.itemSelector;
81943     }
81944 }, function() {
81945     // all of this information is available directly
81946     // from the SelectionModel itself, the only added methods
81947     // to DataView regarding selection will perform some transformation/lookup
81948     // between HTMLElement/Nodes to records and vice versa.
81949     Ext.deprecate('extjs', '4.0', function() {
81950         Ext.view.AbstractView.override({
81951             /**
81952              * @cfg {Boolean} multiSelect
81953              * True to allow selection of more than one item at a time, false to allow selection of only a single item
81954              * at a time or no selection at all, depending on the value of {@link #singleSelect} (defaults to false).
81955              */
81956             /**
81957              * @cfg {Boolean} singleSelect
81958              * True to allow selection of exactly one item at a time, false to allow no selection at all (defaults to false).
81959              * Note that if {@link #multiSelect} = true, this value will be ignored.
81960              */
81961             /**
81962              * @cfg {Boolean} simpleSelect
81963              * True to enable multiselection by clicking on multiple items without requiring the user to hold Shift or Ctrl,
81964              * false to force the user to hold Ctrl or Shift to select more than on item (defaults to false).
81965              */
81966             
81967             /**
81968              * Gets the number of selected nodes.
81969              * @return {Number} The node count
81970              */
81971             getSelectionCount : function(){
81972                 console.warn("DataView: getSelectionCount will be removed, please interact with the Ext.selection.DataViewModel");
81973                 return this.selModel.getSelection().length;
81974             },
81975         
81976             /**
81977              * Gets an array of the selected records
81978              * @return {Array} An array of {@link Ext.data.Model} objects
81979              */
81980             getSelectedRecords : function(){
81981                 console.warn("DataView: getSelectedRecords will be removed, please interact with the Ext.selection.DataViewModel");
81982                 return this.selModel.getSelection();
81983             },
81984     
81985             select: function(records, keepExisting, supressEvents) {
81986                 console.warn("DataView: select will be removed, please access select through a DataView's SelectionModel, ie: view.getSelectionModel().select()");
81987                 var sm = this.getSelectionModel();
81988                 return sm.select.apply(sm, arguments);
81989             },
81990             
81991             clearSelections: function() {
81992                 console.warn("DataView: clearSelections will be removed, please access deselectAll through DataView's SelectionModel, ie: view.getSelectionModel().deselectAll()");
81993                 var sm = this.getSelectionModel();
81994                 return sm.deselectAll();
81995             }
81996         });    
81997     });
81998 });
81999
82000 /**
82001  * @class Ext.Action
82002  * <p>An Action is a piece of reusable functionality that can be abstracted out of any particular component so that it
82003  * can be usefully shared among multiple components.  Actions let you share handlers, configuration options and UI
82004  * updates across any components that support the Action interface (primarily {@link Ext.toolbar.Toolbar}, {@link Ext.button.Button}
82005  * and {@link Ext.menu.Menu} components).</p>
82006  * <p>Use a single Action instance as the config object for any number of UI Components which share the same configuration. The
82007  * Action not only supplies the configuration, but allows all Components based upon it to have a common set of methods
82008  * called at once through a single call to the Action.</p>
82009  * <p>Any Component that is to be configured with an Action must also support
82010  * the following methods:<ul>
82011  * <li><code>setText(string)</code></li>
82012  * <li><code>setIconCls(string)</code></li>
82013  * <li><code>setDisabled(boolean)</code></li>
82014  * <li><code>setVisible(boolean)</code></li>
82015  * <li><code>setHandler(function)</code></li></ul>.</p>
82016  * <p>This allows the Action to control its associated Components.</p>
82017  * Example usage:<br>
82018  * <pre><code>
82019 // Define the shared Action.  Each Component below will have the same
82020 // display text and icon, and will display the same message on click.
82021 var action = new Ext.Action({
82022     {@link #text}: 'Do something',
82023     {@link #handler}: function(){
82024         Ext.Msg.alert('Click', 'You did something.');
82025     },
82026     {@link #iconCls}: 'do-something',
82027     {@link #itemId}: 'myAction'
82028 });
82029
82030 var panel = new Ext.panel.Panel({
82031     title: 'Actions',
82032     width: 500,
82033     height: 300,
82034     tbar: [
82035         // Add the Action directly to a toolbar as a menu button
82036         action,
82037         {
82038             text: 'Action Menu',
82039             // Add the Action to a menu as a text item
82040             menu: [action]
82041         }
82042     ],
82043     items: [
82044         // Add the Action to the panel body as a standard button
82045         new Ext.button.Button(action)
82046     ],
82047     renderTo: Ext.getBody()
82048 });
82049
82050 // Change the text for all components using the Action
82051 action.setText('Something else');
82052
82053 // Reference an Action through a container using the itemId
82054 var btn = panel.getComponent('myAction');
82055 var aRef = btn.baseAction;
82056 aRef.setText('New text');
82057 </code></pre>
82058  * @constructor
82059  * @param {Object} config The configuration options
82060  */
82061 Ext.define('Ext.Action', {
82062
82063     /* Begin Definitions */
82064
82065     /* End Definitions */
82066
82067     /**
82068      * @cfg {String} text The text to set for all components configured by this Action (defaults to '').
82069      */
82070     /**
82071      * @cfg {String} iconCls
82072      * The CSS class selector that specifies a background image to be used as the header icon for
82073      * all components configured by this Action (defaults to '').
82074      * <p>An example of specifying a custom icon class would be something like:
82075      * </p><pre><code>
82076 // specify the property in the config for the class:
82077      ...
82078      iconCls: 'do-something'
82079
82080 // css class that specifies background image to be used as the icon image:
82081 .do-something { background-image: url(../images/my-icon.gif) 0 6px no-repeat !important; }
82082 </code></pre>
82083      */
82084     /**
82085      * @cfg {Boolean} disabled True to disable all components configured by this Action, false to enable them (defaults to false).
82086      */
82087     /**
82088      * @cfg {Boolean} hidden True to hide all components configured by this Action, false to show them (defaults to false).
82089      */
82090     /**
82091      * @cfg {Function} handler The function that will be invoked by each component tied to this Action
82092      * when the component's primary event is triggered (defaults to undefined).
82093      */
82094     /**
82095      * @cfg {String} itemId
82096      * See {@link Ext.Component}.{@link Ext.Component#itemId itemId}.
82097      */
82098     /**
82099      * @cfg {Object} scope The scope (<code><b>this</b></code> reference) in which the
82100      * <code>{@link #handler}</code> is executed. Defaults to the browser window.
82101      */
82102
82103     constructor : function(config){
82104         this.initialConfig = config;
82105         this.itemId = config.itemId = (config.itemId || config.id || Ext.id());
82106         this.items = [];
82107     },
82108
82109     // private
82110     isAction : true,
82111
82112     /**
82113      * Sets the text to be displayed by all components configured by this Action.
82114      * @param {String} text The text to display
82115      */
82116     setText : function(text){
82117         this.initialConfig.text = text;
82118         this.callEach('setText', [text]);
82119     },
82120
82121     /**
82122      * Gets the text currently displayed by all components configured by this Action.
82123      */
82124     getText : function(){
82125         return this.initialConfig.text;
82126     },
82127
82128     /**
82129      * Sets the icon CSS class for all components configured by this Action.  The class should supply
82130      * a background image that will be used as the icon image.
82131      * @param {String} cls The CSS class supplying the icon image
82132      */
82133     setIconCls : function(cls){
82134         this.initialConfig.iconCls = cls;
82135         this.callEach('setIconCls', [cls]);
82136     },
82137
82138     /**
82139      * Gets the icon CSS class currently used by all components configured by this Action.
82140      */
82141     getIconCls : function(){
82142         return this.initialConfig.iconCls;
82143     },
82144
82145     /**
82146      * Sets the disabled state of all components configured by this Action.  Shortcut method
82147      * for {@link #enable} and {@link #disable}.
82148      * @param {Boolean} disabled True to disable the component, false to enable it
82149      */
82150     setDisabled : function(v){
82151         this.initialConfig.disabled = v;
82152         this.callEach('setDisabled', [v]);
82153     },
82154
82155     /**
82156      * Enables all components configured by this Action.
82157      */
82158     enable : function(){
82159         this.setDisabled(false);
82160     },
82161
82162     /**
82163      * Disables all components configured by this Action.
82164      */
82165     disable : function(){
82166         this.setDisabled(true);
82167     },
82168
82169     /**
82170      * Returns true if the components using this Action are currently disabled, else returns false.  
82171      */
82172     isDisabled : function(){
82173         return this.initialConfig.disabled;
82174     },
82175
82176     /**
82177      * Sets the hidden state of all components configured by this Action.  Shortcut method
82178      * for <code>{@link #hide}</code> and <code>{@link #show}</code>.
82179      * @param {Boolean} hidden True to hide the component, false to show it
82180      */
82181     setHidden : function(v){
82182         this.initialConfig.hidden = v;
82183         this.callEach('setVisible', [!v]);
82184     },
82185
82186     /**
82187      * Shows all components configured by this Action.
82188      */
82189     show : function(){
82190         this.setHidden(false);
82191     },
82192
82193     /**
82194      * Hides all components configured by this Action.
82195      */
82196     hide : function(){
82197         this.setHidden(true);
82198     },
82199
82200     /**
82201      * Returns true if the components configured by this Action are currently hidden, else returns false.
82202      */
82203     isHidden : function(){
82204         return this.initialConfig.hidden;
82205     },
82206
82207     /**
82208      * Sets the function that will be called by each Component using this action when its primary event is triggered.
82209      * @param {Function} fn The function that will be invoked by the action's components.  The function
82210      * will be called with no arguments.
82211      * @param {Object} scope The scope (<code>this</code> reference) in which the function is executed. Defaults to the Component firing the event.
82212      */
82213     setHandler : function(fn, scope){
82214         this.initialConfig.handler = fn;
82215         this.initialConfig.scope = scope;
82216         this.callEach('setHandler', [fn, scope]);
82217     },
82218
82219     /**
82220      * Executes the specified function once for each Component currently tied to this Action.  The function passed
82221      * in should accept a single argument that will be an object that supports the basic Action config/method interface.
82222      * @param {Function} fn The function to execute for each component
82223      * @param {Object} scope The scope (<code>this</code> reference) in which the function is executed.  Defaults to the Component.
82224      */
82225     each : function(fn, scope){
82226         Ext.each(this.items, fn, scope);
82227     },
82228
82229     // private
82230     callEach : function(fnName, args){
82231         var cs = this.items;
82232         for(var i = 0, len = cs.length; i < len; i++){
82233             cs[i][fnName].apply(cs[i], args);
82234         }
82235     },
82236
82237     // private
82238     addComponent : function(comp){
82239         this.items.push(comp);
82240         comp.on('destroy', this.removeComponent, this);
82241     },
82242
82243     // private
82244     removeComponent : function(comp){
82245         this.items.remove(comp);
82246     },
82247
82248     /**
82249      * Executes this Action manually using the handler function specified in the original config object
82250      * or the handler function set with <code>{@link #setHandler}</code>.  Any arguments passed to this
82251      * function will be passed on to the handler function.
82252      * @param {Mixed} arg1 (optional) Variable number of arguments passed to the handler function
82253      * @param {Mixed} arg2 (optional)
82254      * @param {Mixed} etc... (optional)
82255      */
82256     execute : function(){
82257         this.initialConfig.handler.apply(this.initialConfig.scope || Ext.global, arguments);
82258     }
82259 });
82260
82261 /**
82262  * Component layout for editors
82263  * @class Ext.layout.component.Editor
82264  * @extends Ext.layout.component.Component
82265  * @private
82266  */
82267 Ext.define('Ext.layout.component.Editor', {
82268
82269     /* Begin Definitions */
82270
82271     alias: ['layout.editor'],
82272
82273     extend: 'Ext.layout.component.Component',
82274
82275     /* End Definitions */
82276
82277     onLayout: function(width, height) {
82278         var me = this,
82279             owner = me.owner,
82280             autoSize = owner.autoSize;
82281             
82282         if (autoSize === true) {
82283             autoSize = {
82284                 width: 'field',
82285                 height: 'field'    
82286             };
82287         }
82288         
82289         if (autoSize) {
82290             width = me.getDimension(owner, autoSize.width, 'Width', width);
82291             height = me.getDimension(owner, autoSize.height, 'Height', height);
82292         }
82293         me.setTargetSize(width, height);
82294         owner.field.setSize(width, height);
82295     },
82296     
82297     getDimension: function(owner, type, dimension, actual){
82298         var method = 'get' + dimension;
82299         switch (type) {
82300             case 'boundEl':
82301                 return owner.boundEl[method]();
82302             case 'field':
82303                 return owner.field[method]();
82304             default:
82305                 return actual;
82306         }
82307     }
82308 });
82309 /**
82310  * @class Ext.Editor
82311  * @extends Ext.Component
82312  *
82313  * <p>
82314  * The Editor class is used to provide inline editing for elements on the page. The editor
82315  * is backed by a {@link Ext.form.field.Field} that will be displayed to edit the underlying content.
82316  * The editor is a floating Component, when the editor is shown it is automatically aligned to
82317  * display over the top of the bound element it is editing. The Editor contains several options
82318  * for how to handle key presses:
82319  * <ul>
82320  * <li>{@link #completeOnEnter}</li>
82321  * <li>{@link #cancelOnEsc}</li>
82322  * <li>{@link #swallowKeys}</li>
82323  * </ul>
82324  * It also has options for how to use the value once the editor has been activated:
82325  * <ul>
82326  * <li>{@link #revertInvalid}</li>
82327  * <li>{@link #ignoreNoChange}</li>
82328  * <li>{@link #updateEl}</li>
82329  * </ul>
82330  * Sample usage:
82331  * </p>
82332  * <pre><code>
82333 var editor = new Ext.Editor({
82334     updateEl: true, // update the innerHTML of the bound element when editing completes
82335     field: {
82336         xtype: 'textfield'
82337     }
82338 });
82339 var el = Ext.get('my-text'); // The element to 'edit'
82340 editor.startEdit(el); // The value of the field will be taken as the innerHTML of the element.
82341  * </code></pre>
82342  * {@img Ext.Editor/Ext.Editor.png Ext.Editor component}
82343  *
82344  * @constructor
82345  * Create a new Editor
82346  * @param {Object} config The config object
82347  * @xtype editor
82348  */
82349 Ext.define('Ext.Editor', {
82350
82351     /* Begin Definitions */
82352
82353     extend: 'Ext.Component',
82354
82355     alias: 'widget.editor',
82356
82357     requires: ['Ext.layout.component.Editor'],
82358
82359     /* End Definitions */
82360
82361    componentLayout: 'editor',
82362
82363     /**
82364     * @cfg {Ext.form.field.Field} field
82365     * The Field object (or descendant) or config object for field
82366     */
82367
82368     /**
82369      * @cfg {Boolean} allowBlur
82370      * True to {@link #completeEdit complete the editing process} if in edit mode when the
82371      * field is blurred. Defaults to <tt>true</tt>.
82372      */
82373     allowBlur: true,
82374
82375     /**
82376      * @cfg {Boolean/Object} autoSize
82377      * True for the editor to automatically adopt the size of the underlying field. Otherwise, an object
82378      * can be passed to indicate where to get each dimension. The available properties are 'boundEl' and
82379      * 'field'. If a dimension is not specified, it will use the underlying height/width specified on
82380      * the editor object.
82381      * Examples:
82382      * <pre><code>
82383 autoSize: true // The editor will be sized to the height/width of the field
82384
82385 height: 21,
82386 autoSize: {
82387     width: 'boundEl' // The width will be determined by the width of the boundEl, the height from the editor (21)
82388 }
82389
82390 autoSize: {
82391     width: 'field', // Width from the field
82392     height: 'boundEl' // Height from the boundEl
82393 }
82394      * </pre></code>
82395      */
82396
82397     /**
82398      * @cfg {Boolean} revertInvalid
82399      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
82400      * validation fails (defaults to true)
82401      */
82402     revertInvalid: true,
82403
82404     /**
82405      * @cfg {Boolean} ignoreNoChange
82406      * True to skip the edit completion process (no save, no events fired) if the user completes an edit and
82407      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
82408      * will never be ignored.
82409      */
82410
82411     /**
82412      * @cfg {Boolean} hideEl
82413      * False to keep the bound element visible while the editor is displayed (defaults to true)
82414      */
82415
82416     /**
82417      * @cfg {Mixed} value
82418      * The data value of the underlying field (defaults to "")
82419      */
82420     value : '',
82421
82422     /**
82423      * @cfg {String} alignment
82424      * The position to align to (see {@link Ext.core.Element#alignTo} for more details, defaults to "c-c?").
82425      */
82426     alignment: 'c-c?',
82427
82428     /**
82429      * @cfg {Array} offsets
82430      * The offsets to use when aligning (see {@link Ext.core.Element#alignTo} for more details. Defaults to <tt>[0, 0]</tt>.
82431      */
82432     offsets: [0, 0],
82433
82434     /**
82435      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
82436      * for bottom-right shadow (defaults to "frame")
82437      */
82438     shadow : 'frame',
82439
82440     /**
82441      * @cfg {Boolean} constrain True to constrain the editor to the viewport
82442      */
82443     constrain : false,
82444
82445     /**
82446      * @cfg {Boolean} swallowKeys Handle the keydown/keypress events so they don't propagate (defaults to true)
82447      */
82448     swallowKeys : true,
82449
82450     /**
82451      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed. Defaults to <tt>true</tt>.
82452      */
82453     completeOnEnter : true,
82454
82455     /**
82456      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed. Defaults to <tt>true</tt>.
82457      */
82458     cancelOnEsc : true,
82459
82460     /**
82461      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
82462      */
82463     updateEl : false,
82464
82465     /**
82466      * @cfg {Mixed} parentEl An element to render to. Defaults to the <tt>document.body</tt>.
82467      */
82468
82469     // private overrides
82470     hidden: true,
82471     baseCls: Ext.baseCSSPrefix + 'editor',
82472
82473     initComponent : function() {
82474         var me = this,
82475             field = me.field = Ext.ComponentManager.create(me.field, 'textfield');
82476
82477         Ext.apply(field, {
82478             inEditor: true,
82479             msgTarget: field.msgTarget == 'title' ? 'title' :  'qtip'
82480         });
82481         me.mon(field, {
82482             scope: me,
82483             blur: {
82484                 fn: me.onBlur,
82485                 // slight delay to avoid race condition with startEdits (e.g. grid view refresh)
82486                 delay: 1
82487             },
82488             specialkey: me.onSpecialKey
82489         });
82490
82491         if (field.grow) {
82492             me.mon(field, 'autosize', me.onAutoSize,  me, {delay: 1});
82493         }
82494         me.floating = {
82495             constrain: me.constrain
82496         };
82497
82498         me.callParent(arguments);
82499
82500         me.addEvents(
82501             /**
82502              * @event beforestartedit
82503              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
82504              * false from the handler of this event.
82505              * @param {Ext.Editor} this
82506              * @param {Ext.core.Element} boundEl The underlying element bound to this editor
82507              * @param {Mixed} value The field value being set
82508              */
82509             'beforestartedit',
82510             /**
82511              * @event startedit
82512              * Fires when this editor is displayed
82513              * @param {Ext.Editor} this
82514              * @param {Ext.core.Element} boundEl The underlying element bound to this editor
82515              * @param {Mixed} value The starting field value
82516              */
82517             'startedit',
82518             /**
82519              * @event beforecomplete
82520              * Fires after a change has been made to the field, but before the change is reflected in the underlying
82521              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
82522              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
82523              * event will not fire since no edit actually occurred.
82524              * @param {Editor} this
82525              * @param {Mixed} value The current field value
82526              * @param {Mixed} startValue The original field value
82527              */
82528             'beforecomplete',
82529             /**
82530              * @event complete
82531              * Fires after editing is complete and any changed value has been written to the underlying field.
82532              * @param {Ext.Editor} this
82533              * @param {Mixed} value The current field value
82534              * @param {Mixed} startValue The original field value
82535              */
82536             'complete',
82537             /**
82538              * @event canceledit
82539              * Fires after editing has been canceled and the editor's value has been reset.
82540              * @param {Ext.Editor} this
82541              * @param {Mixed} value The user-entered field value that was discarded
82542              * @param {Mixed} startValue The original field value that was set back into the editor after cancel
82543              */
82544             'canceledit',
82545             /**
82546              * @event specialkey
82547              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
82548              * {@link Ext.EventObject#getKey} to determine which key was pressed.
82549              * @param {Ext.Editor} this
82550              * @param {Ext.form.field.Field} The field attached to this editor
82551              * @param {Ext.EventObject} event The event object
82552              */
82553             'specialkey'
82554         );
82555     },
82556
82557     // private
82558     onAutoSize: function(){
82559         this.doComponentLayout();
82560     },
82561
82562     // private
82563     onRender : function(ct, position) {
82564         var me = this,
82565             field = me.field;
82566
82567         me.callParent(arguments);
82568
82569         field.render(me.el);
82570         //field.hide();
82571         // Ensure the field doesn't get submitted as part of any form
82572         field.inputEl.dom.name = '';
82573         if (me.swallowKeys) {
82574             field.inputEl.swallowEvent([
82575                 'keypress', // *** Opera
82576                 'keydown'   // *** all other browsers
82577             ]);
82578         }
82579     },
82580
82581     // private
82582     onSpecialKey : function(field, event) {
82583         var me = this,
82584             key = event.getKey(),
82585             complete = me.completeOnEnter && key == event.ENTER,
82586             cancel = me.cancelOnEsc && key == event.ESC;
82587
82588         if (complete || cancel) {
82589             event.stopEvent();
82590             // Must defer this slightly to prevent exiting edit mode before the field's own
82591             // key nav can handle the enter key, e.g. selecting an item in a combobox list
82592             Ext.defer(function() {
82593                 if (complete) {
82594                     me.completeEdit();
82595                 } else {
82596                     me.cancelEdit();
82597                 }
82598                 if (field.triggerBlur) {
82599                     field.triggerBlur();
82600                 }
82601             }, 10);
82602         }
82603
82604         this.fireEvent('specialkey', this, field, event);
82605     },
82606
82607     /**
82608      * Starts the editing process and shows the editor.
82609      * @param {Mixed} el The element to edit
82610      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
82611       * to the innerHTML of el.
82612      */
82613     startEdit : function(el, value) {
82614         var me = this,
82615             field = me.field;
82616
82617         me.completeEdit();
82618         me.boundEl = Ext.get(el);
82619         value = Ext.isDefined(value) ? value : me.boundEl.dom.innerHTML;
82620
82621         if (!me.rendered) {
82622             me.render(me.parentEl || document.body);
82623         }
82624
82625         if (me.fireEvent('beforestartedit', me, me.boundEl, value) !== false) {
82626             me.startValue = value;
82627             me.show();
82628             field.reset();
82629             field.setValue(value);
82630             me.realign(true);
82631             field.focus(false, 10);
82632             if (field.autoSize) {
82633                 field.autoSize();
82634             }
82635             me.editing = true;
82636         }
82637     },
82638
82639     /**
82640      * Realigns the editor to the bound field based on the current alignment config value.
82641      * @param {Boolean} autoSize (optional) True to size the field to the dimensions of the bound element.
82642      */
82643     realign : function(autoSize) {
82644         var me = this;
82645         if (autoSize === true) {
82646             me.doComponentLayout();
82647         }
82648         me.alignTo(me.boundEl, me.alignment, me.offsets);
82649     },
82650
82651     /**
82652      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
82653      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
82654      */
82655     completeEdit : function(remainVisible) {
82656         var me = this,
82657             field = me.field,
82658             value;
82659
82660         if (!me.editing) {
82661             return;
82662         }
82663
82664         // Assert combo values first
82665         if (field.assertValue) {
82666             field.assertValue();
82667         }
82668
82669         value = me.getValue();
82670         if (!field.isValid()) {
82671             if (me.revertInvalid !== false) {
82672                 me.cancelEdit(remainVisible);
82673             }
82674             return;
82675         }
82676
82677         if (String(value) === String(me.startValue) && me.ignoreNoChange) {
82678             me.hideEdit(remainVisible);
82679             return;
82680         }
82681
82682         if (me.fireEvent('beforecomplete', me, value, me.startValue) !== false) {
82683             // Grab the value again, may have changed in beforecomplete
82684             value = me.getValue();
82685             if (me.updateEl && me.boundEl) {
82686                 me.boundEl.update(value);
82687             }
82688             me.hideEdit(remainVisible);
82689             me.fireEvent('complete', me, value, me.startValue);
82690         }
82691     },
82692
82693     // private
82694     onShow : function() {
82695         var me = this;
82696
82697         me.callParent(arguments);
82698         if (me.hideEl !== false) {
82699             me.boundEl.hide();
82700         }
82701         me.fireEvent("startedit", me.boundEl, me.startValue);
82702     },
82703
82704     /**
82705      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
82706      * reverted to the original starting value.
82707      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
82708      * cancel (defaults to false)
82709      */
82710     cancelEdit : function(remainVisible) {
82711         var me = this,
82712             startValue = me.startValue,
82713             value;
82714
82715         if (me.editing) {
82716             value = me.getValue();
82717             me.setValue(startValue);
82718             me.hideEdit(remainVisible);
82719             me.fireEvent('canceledit', me, value, startValue);
82720         }
82721     },
82722
82723     // private
82724     hideEdit: function(remainVisible) {
82725         if (remainVisible !== true) {
82726             this.editing = false;
82727             this.hide();
82728         }
82729     },
82730
82731     // private
82732     onBlur : function() {
82733         var me = this;
82734
82735         // selectSameEditor flag allows the same editor to be started without onBlur firing on itself
82736         if(me.allowBlur === true && me.editing && me.selectSameEditor !== true) {
82737             me.completeEdit();
82738         }
82739     },
82740
82741     // private
82742     onHide : function() {
82743         var me = this,
82744             field = me.field;
82745
82746         if (me.editing) {
82747             me.completeEdit();
82748             return;
82749         }
82750         field.blur();
82751         if (field.collapse) {
82752             field.collapse();
82753         }
82754
82755         //field.hide();
82756         if (me.hideEl !== false) {
82757             me.boundEl.show();
82758         }
82759         me.callParent(arguments);
82760     },
82761
82762     /**
82763      * Sets the data value of the editor
82764      * @param {Mixed} value Any valid value supported by the underlying field
82765      */
82766     setValue : function(value) {
82767         this.field.setValue(value);
82768     },
82769
82770     /**
82771      * Gets the data value of the editor
82772      * @return {Mixed} The data value
82773      */
82774     getValue : function() {
82775         return this.field.getValue();
82776     },
82777
82778     beforeDestroy : function() {
82779         var me = this;
82780
82781         Ext.destroy(me.field);
82782         delete me.field;
82783         delete me.parentEl;
82784         delete me.boundEl;
82785
82786         me.callParent(arguments);
82787     }
82788 });
82789 /**
82790  * @class Ext.Img
82791  * @extends Ext.Component
82792  *
82793  * Simple helper class for easily creating image components. This simply renders an image tag to the DOM
82794  * with the configured src.
82795  *
82796  * {@img Ext.Img/Ext.Img.png Ext.Img component}
82797  *
82798  * ## Example usage: 
82799  *
82800  *     var changingImage = Ext.create('Ext.Img', {
82801  *         src: 'http://www.sencha.com/img/20110215-feat-html5.png',
82802  *         renderTo: Ext.getBody()
82803  *     });
82804  *      
82805  *     // change the src of the image programmatically
82806  *     changingImage.setSrc('http://www.sencha.com/img/20110215-feat-perf.png');
82807 */
82808 Ext.define('Ext.Img', {
82809     extend: 'Ext.Component',
82810     alias: ['widget.image', 'widget.imagecomponent'],
82811     /** @cfg {String} src The image src */
82812     src: '',
82813
82814     getElConfig: function() {
82815         return {
82816             tag: 'img',
82817             src: this.src
82818         };
82819     },
82820     
82821     /**
82822      * Updates the {@link #src} of the image
82823      */
82824     setSrc: function(src) {
82825         var me = this,
82826             img = me.el;
82827         me.src = src;
82828         if (img) {
82829             img.dom.src = src;
82830         }
82831     }
82832 });
82833
82834 /**
82835  * @class Ext.Layer
82836  * @extends Ext.core.Element
82837  * An extended {@link Ext.core.Element} object that supports a shadow and shim, constrain to viewport and
82838  * automatic maintaining of shadow/shim positions.
82839  * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
82840  * @cfg {String/Boolean} shadow True to automatically create an {@link Ext.Shadow}, or a string indicating the
82841  * shadow's display {@link Ext.Shadow#mode}. False to disable the shadow. (defaults to false)
82842  * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: 'div', cls: 'x-layer'}).
82843  * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
82844  * @cfg {String} cls CSS class to add to the element
82845  * @cfg {Number} zindex Starting z-index (defaults to 11000)
82846  * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 4)
82847  * @cfg {Boolean} useDisplay
82848  * Defaults to use css offsets to hide the Layer. Specify <tt>true</tt>
82849  * to use css style <tt>'display:none;'</tt> to hide the Layer.
82850  * @cfg {String} visibilityCls The CSS class name to add in order to hide this Layer if this layer
82851  * is configured with <code>{@link #hideMode}: 'asclass'</code>
82852  * @cfg {String} hideMode
82853  * A String which specifies how this Layer will be hidden.
82854  * Values may be<div class="mdetail-params"><ul>
82855  * <li><code>'display'</code> : The Component will be hidden using the <code>display: none</code> style.</li>
82856  * <li><code>'visibility'</code> : The Component will be hidden using the <code>visibility: hidden</code> style.</li>
82857  * <li><code>'offsets'</code> : The Component will be hidden by absolutely positioning it out of the visible area of the document. This
82858  * is useful when a hidden Component must maintain measurable dimensions. Hiding using <code>display</code> results
82859  * in a Component having zero dimensions.</li></ul></div>
82860  * @constructor
82861  * @param {Object} config An object with config options.
82862  * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
82863  */
82864 Ext.define('Ext.Layer', {
82865     uses: ['Ext.Shadow'],
82866
82867     // shims are shared among layer to keep from having 100 iframes
82868     statics: {
82869         shims: []
82870     },
82871
82872     extend: 'Ext.core.Element',
82873
82874     constructor: function(config, existingEl) {
82875         config = config || {};
82876         var me = this,
82877             dh = Ext.core.DomHelper,
82878             cp = config.parentEl,
82879             pel = cp ? Ext.getDom(cp) : document.body,
82880         hm = config.hideMode;
82881
82882         if (existingEl) {
82883             me.dom = Ext.getDom(existingEl);
82884         }
82885         if (!me.dom) {
82886             me.dom = dh.append(pel, config.dh || {
82887                 tag: 'div',
82888                 cls: Ext.baseCSSPrefix + 'layer'
82889             });
82890         } else {
82891             me.addCls(Ext.baseCSSPrefix + 'layer');
82892             if (!me.dom.parentNode) {
82893                 pel.appendChild(me.dom);
82894             }
82895         }
82896
82897         if (config.cls) {
82898             me.addCls(config.cls);
82899         }
82900         me.constrain = config.constrain !== false;
82901
82902         // Allow Components to pass their hide mode down to the Layer if they are floating.
82903         // Otherwise, allow useDisplay to override the default hiding method which is visibility.
82904         // TODO: Have ExtJS's Element implement visibilityMode by using classes as in Mobile.
82905         if (hm) {
82906             me.setVisibilityMode(Ext.core.Element[hm.toUpperCase()]);
82907             if (me.visibilityMode == Ext.core.Element.ASCLASS) {
82908                 me.visibilityCls = config.visibilityCls;
82909             }
82910         } else if (config.useDisplay) {
82911             me.setVisibilityMode(Ext.core.Element.DISPLAY);
82912         } else {
82913             me.setVisibilityMode(Ext.core.Element.VISIBILITY);
82914         }
82915
82916         if (config.id) {
82917             me.id = me.dom.id = config.id;
82918         } else {
82919             me.id = Ext.id(me.dom);
82920         }
82921         me.position('absolute');
82922         if (config.shadow) {
82923             me.shadowOffset = config.shadowOffset || 4;
82924             me.shadow = Ext.create('Ext.Shadow', {
82925                 offset: me.shadowOffset,
82926                 mode: config.shadow
82927             });
82928             me.disableShadow();
82929         } else {
82930             me.shadowOffset = 0;
82931         }
82932         me.useShim = config.shim !== false && Ext.useShims;
82933         if (config.hidden === true) {
82934             me.hide();
82935         } else {
82936             this.show();
82937         }
82938     },
82939
82940     getZIndex: function() {
82941         return parseInt((this.getShim() || this).getStyle('z-index'), 10);
82942     },
82943
82944     getShim: function() {
82945         var me = this,
82946             shim, pn;
82947
82948         if (!me.useShim) {
82949             return null;
82950         }
82951         if (!me.shim) {
82952             shim = me.self.shims.shift();
82953             if (!shim) {
82954                 shim = me.createShim();
82955                 shim.enableDisplayMode('block');
82956                 shim.hide();
82957             }
82958             pn = me.dom.parentNode;
82959             if (shim.dom.parentNode != pn) {
82960                 pn.insertBefore(shim.dom, me.dom);
82961             }
82962             me.shim = shim;
82963         }
82964         return me.shim;
82965     },
82966
82967     hideShim: function() {
82968         if (this.shim) {
82969             this.shim.setDisplayed(false);
82970             this.self.shims.push(this.shim);
82971             delete this.shim;
82972         }
82973     },
82974
82975     disableShadow: function() {
82976         if (this.shadow) {
82977             this.shadowDisabled = true;
82978             this.shadow.hide();
82979             this.lastShadowOffset = this.shadowOffset;
82980             this.shadowOffset = 0;
82981         }
82982     },
82983
82984     enableShadow: function(show) {
82985         if (this.shadow) {
82986             this.shadowDisabled = false;
82987             this.shadowOffset = this.lastShadowOffset;
82988             delete this.lastShadowOffset;
82989             if (show) {
82990                 this.sync(true);
82991             }
82992         }
82993     },
82994
82995     /**
82996      * @private
82997      * <p>Synchronize this Layer's associated elements, the shadow, and possibly the shim.</p>
82998      * <p>This code can execute repeatedly in milliseconds,
82999      * eg: dragging a Component configured liveDrag: true, or which has no ghost method
83000      * so code size was sacrificed for efficiency (e.g. no getBox/setBox, no XY calls)</p>
83001      * @param {Boolean} doShow Pass true to ensure that the shadow is shown.
83002      */
83003     sync: function(doShow) {
83004         var me = this,
83005             shadow = me.shadow,
83006             shadowPos, shimStyle, shadowSize;
83007
83008         if (!this.updating && this.isVisible() && (shadow || this.useShim)) {
83009             var shim = this.getShim(),
83010                 l = this.getLeft(true),
83011                 t = this.getTop(true),
83012                 w = this.getWidth(),
83013                 h = this.getHeight(),
83014                 shimIndex;
83015
83016             if (shadow && !this.shadowDisabled) {
83017                 if (doShow && !shadow.isVisible()) {
83018                     shadow.show(this);
83019                 } else {
83020                     shadow.realign(l, t, w, h);
83021                 }
83022                 if (shim) {
83023                     // TODO: Determine how the shims zIndex is above the layer zIndex at this point
83024                     shimIndex = shim.getStyle('z-index');
83025                     if (shimIndex > me.zindex) {
83026                         me.shim.setStyle('z-index', me.zindex - 2);
83027                     }
83028                     shim.show();
83029                     // fit the shim behind the shadow, so it is shimmed too
83030                     if (shadow.isVisible()) {
83031                         shadowPos = shadow.el.getXY();
83032                         shimStyle = shim.dom.style;
83033                         shadowSize = shadow.el.getSize();
83034                         shimStyle.left = (shadowPos[0]) + 'px';
83035                         shimStyle.top = (shadowPos[1]) + 'px';
83036                         shimStyle.width = (shadowSize.width) + 'px';
83037                         shimStyle.height = (shadowSize.height) + 'px';
83038                     } else {
83039                         shim.setSize(w, h);
83040                         shim.setLeftTop(l, t);
83041                     }
83042                 }
83043             } else if (shim) {
83044                 // TODO: Determine how the shims zIndex is above the layer zIndex at this point
83045                 shimIndex = shim.getStyle('z-index');
83046                 if (shimIndex > me.zindex) {
83047                     me.shim.setStyle('z-index', me.zindex - 2);
83048                 }
83049                 shim.show();
83050                 shim.setSize(w, h);
83051                 shim.setLeftTop(l, t);
83052             }
83053         }
83054         return this;
83055     },
83056
83057     remove: function() {
83058         this.hideUnders();
83059         this.callParent();
83060     },
83061
83062     // private
83063     beginUpdate: function() {
83064         this.updating = true;
83065     },
83066
83067     // private
83068     endUpdate: function() {
83069         this.updating = false;
83070         this.sync(true);
83071     },
83072
83073     // private
83074     hideUnders: function() {
83075         if (this.shadow) {
83076             this.shadow.hide();
83077         }
83078         this.hideShim();
83079     },
83080
83081     // private
83082     constrainXY: function() {
83083         if (this.constrain) {
83084             var vw = Ext.core.Element.getViewWidth(),
83085                 vh = Ext.core.Element.getViewHeight(),
83086                 s = Ext.getDoc().getScroll(),
83087                 xy = this.getXY(),
83088                 x = xy[0],
83089                 y = xy[1],
83090                 so = this.shadowOffset,
83091                 w = this.dom.offsetWidth + so,
83092                 h = this.dom.offsetHeight + so,
83093                 moved = false; // only move it if it needs it
83094             // first validate right/bottom
83095             if ((x + w) > vw + s.left) {
83096                 x = vw - w - so;
83097                 moved = true;
83098             }
83099             if ((y + h) > vh + s.top) {
83100                 y = vh - h - so;
83101                 moved = true;
83102             }
83103             // then make sure top/left isn't negative
83104             if (x < s.left) {
83105                 x = s.left;
83106                 moved = true;
83107             }
83108             if (y < s.top) {
83109                 y = s.top;
83110                 moved = true;
83111             }
83112             if (moved) {
83113                 Ext.Layer.superclass.setXY.call(this, [x, y]);
83114                 this.sync();
83115             }
83116         }
83117         return this;
83118     },
83119
83120     getConstrainOffset: function() {
83121         return this.shadowOffset;
83122     },
83123
83124     // overridden Element method
83125     setVisible: function(visible, animate, duration, callback, easing) {
83126         var me = this,
83127             cb;
83128
83129         // post operation processing
83130         cb = function() {
83131             if (visible) {
83132                 me.sync(true);
83133             }
83134             if (callback) {
83135                 callback();
83136             }
83137         };
83138
83139         // Hide shadow and shim if hiding
83140         if (!visible) {
83141             this.hideUnders(true);
83142         }
83143         this.callParent([visible, animate, duration, callback, easing]);
83144         if (!animate) {
83145             cb();
83146         }
83147         return this;
83148     },
83149
83150     // private
83151     beforeFx: function() {
83152         this.beforeAction();
83153         return this.callParent(arguments);
83154     },
83155
83156     // private
83157     afterFx: function() {
83158         this.callParent(arguments);
83159         this.sync(this.isVisible());
83160     },
83161
83162     // private
83163     beforeAction: function() {
83164         if (!this.updating && this.shadow) {
83165             this.shadow.hide();
83166         }
83167     },
83168
83169     // overridden Element method
83170     setLeft: function(left) {
83171         this.callParent(arguments);
83172         return this.sync();
83173     },
83174
83175     setTop: function(top) {
83176         this.callParent(arguments);
83177         return this.sync();
83178     },
83179
83180     setLeftTop: function(left, top) {
83181         this.callParent(arguments);
83182         return this.sync();
83183     },
83184
83185     setXY: function(xy, animate, duration, callback, easing) {
83186
83187         // Callback will restore shadow state and call the passed callback
83188         callback = this.createCB(callback);
83189
83190         this.fixDisplay();
83191         this.beforeAction();
83192         this.callParent([xy, animate, duration, callback, easing]);
83193         if (!animate) {
83194             callback();
83195         }
83196         return this;
83197     },
83198
83199     // private
83200     createCB: function(callback) {
83201         var me = this,
83202             showShadow = me.shadow && me.shadow.isVisible();
83203
83204         return function() {
83205             me.constrainXY();
83206             me.sync(showShadow);
83207             if (callback) {
83208                 callback();
83209             }
83210         };
83211     },
83212
83213     // overridden Element method
83214     setX: function(x, animate, duration, callback, easing) {
83215         this.setXY([x, this.getY()], animate, duration, callback, easing);
83216         return this;
83217     },
83218
83219     // overridden Element method
83220     setY: function(y, animate, duration, callback, easing) {
83221         this.setXY([this.getX(), y], animate, duration, callback, easing);
83222         return this;
83223     },
83224
83225     // overridden Element method
83226     setSize: function(w, h, animate, duration, callback, easing) {
83227         // Callback will restore shadow state and call the passed callback
83228         callback = this.createCB(callback);
83229
83230         this.beforeAction();
83231         this.callParent([w, h, animate, duration, callback, easing]);
83232         if (!animate) {
83233             callback();
83234         }
83235         return this;
83236     },
83237
83238     // overridden Element method
83239     setWidth: function(w, animate, duration, callback, easing) {
83240         // Callback will restore shadow state and call the passed callback
83241         callback = this.createCB(callback);
83242
83243         this.beforeAction();
83244         this.callParent([w, animate, duration, callback, easing]);
83245         if (!animate) {
83246             callback();
83247         }
83248         return this;
83249     },
83250
83251     // overridden Element method
83252     setHeight: function(h, animate, duration, callback, easing) {
83253         // Callback will restore shadow state and call the passed callback
83254         callback = this.createCB(callback);
83255
83256         this.beforeAction();
83257         this.callParent([h, animate, duration, callback, easing]);
83258         if (!animate) {
83259             callback();
83260         }
83261         return this;
83262     },
83263
83264     // overridden Element method
83265     setBounds: function(x, y, width, height, animate, duration, callback, easing) {
83266         // Callback will restore shadow state and call the passed callback
83267         callback = this.createCB(callback);
83268
83269         this.beforeAction();
83270         if (!animate) {
83271             Ext.Layer.superclass.setXY.call(this, [x, y]);
83272             Ext.Layer.superclass.setSize.call(this, width, height);
83273             callback();
83274         } else {
83275             this.callParent([x, y, width, height, animate, duration, callback, easing]);
83276         }
83277         return this;
83278     },
83279
83280     /**
83281      * <p>Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
83282      * incremented depending upon the presence of a shim or a shadow in so that it always shows above those two associated elements.</p>
83283      * <p>Any shim, will be assigned the passed z-index. A shadow will be assigned the next highet z-index, and the Layer's
83284      * element will receive the highest  z-index.
83285      * @param {Number} zindex The new z-index to set
83286      * @return {this} The Layer
83287      */
83288     setZIndex: function(zindex) {
83289         this.zindex = zindex;
83290         if (this.getShim()) {
83291             this.shim.setStyle('z-index', zindex++);
83292         }
83293         if (this.shadow) {
83294             this.shadow.setZIndex(zindex++);
83295         }
83296         this.setStyle('z-index', zindex);
83297         return this;
83298     }
83299 });
83300
83301 /**
83302  * @class Ext.layout.component.ProgressBar
83303  * @extends Ext.layout.component.Component
83304  * @private
83305  */
83306
83307 Ext.define('Ext.layout.component.ProgressBar', {
83308
83309     /* Begin Definitions */
83310
83311     alias: ['layout.progressbar'],
83312
83313     extend: 'Ext.layout.component.Component',
83314
83315     /* End Definitions */
83316
83317     type: 'progressbar',
83318
83319     onLayout: function(width, height) {
83320         var me = this,
83321             owner = me.owner,
83322             textEl = owner.textEl;
83323         
83324         me.setElementSize(owner.el, width, height);
83325         textEl.setWidth(owner.el.getWidth(true));
83326         
83327         me.callParent([width, height]);
83328         
83329         owner.updateProgress(owner.value);
83330     }
83331 });
83332 /**
83333  * @class Ext.ProgressBar
83334  * @extends Ext.Component
83335  * <p>An updateable progress bar component.  The progress bar supports two different modes: manual and automatic.</p>
83336  * <p>In manual mode, you are responsible for showing, updating (via {@link #updateProgress}) and clearing the
83337  * progress bar as needed from your own code.  This method is most appropriate when you want to show progress
83338  * throughout an operation that has predictable points of interest at which you can update the control.</p>
83339  * <p>In automatic mode, you simply call {@link #wait} and let the progress bar run indefinitely, only clearing it
83340  * once the operation is complete.  You can optionally have the progress bar wait for a specific amount of time
83341  * and then clear itself.  Automatic mode is most appropriate for timed operations or asynchronous operations in
83342  * which you have no need for indicating intermediate progress.</p>
83343  * {@img Ext.ProgressBar/Ext.ProgressBar.png Ext.ProgressBar component}
83344  * Example Usage:
83345      var p = Ext.create('Ext.ProgressBar', {
83346        renderTo: Ext.getBody(),
83347        width: 300
83348     });
83349
83350     //Wait for 5 seconds, then update the status el (progress bar will auto-reset)
83351     p.wait({
83352        interval: 500, //bar will move fast!
83353        duration: 50000,
83354        increment: 15,
83355        text: 'Updating...',
83356        scope: this,
83357        fn: function(){
83358           p.updateText('Done!');
83359        }
83360     });
83361  * @cfg {Float} value A floating point value between 0 and 1 (e.g., .5, defaults to 0)
83362  * @cfg {String} text The progress bar text (defaults to '')
83363  * @cfg {Mixed} textEl The element to render the progress text to (defaults to the progress
83364  * bar's internal text element)
83365  * @cfg {String} id The progress bar element's id (defaults to an auto-generated id)
83366  * @xtype progressbar
83367  */
83368 Ext.define('Ext.ProgressBar', {
83369     extend: 'Ext.Component',
83370     alias: 'widget.progressbar',
83371
83372     requires: [
83373         'Ext.Template',
83374         'Ext.CompositeElement',
83375         'Ext.TaskManager',
83376         'Ext.layout.component.ProgressBar'
83377     ],
83378
83379     uses: ['Ext.fx.Anim'],
83380    /**
83381     * @cfg {String} baseCls
83382     * The base CSS class to apply to the progress bar's wrapper element (defaults to 'x-progress')
83383     */
83384     baseCls: Ext.baseCSSPrefix + 'progress',
83385
83386     config: {
83387         /**
83388         * @cfg {Boolean} animate
83389         * True to animate the progress bar during transitions (defaults to false)
83390         */
83391         animate: false,
83392
83393         /**
83394          * @cfg {String} text The text shown in the progress bar (defaults to '')
83395          */
83396         text: ''
83397     },
83398
83399     // private
83400     waitTimer: null,
83401
83402     renderTpl: [
83403         '<div class="{baseCls}-text {baseCls}-text-back">',
83404             '<div>&#160;</div>',
83405         '</div>',
83406         '<div class="{baseCls}-bar">',
83407             '<div class="{baseCls}-text">',
83408                 '<div>&#160;</div>',
83409             '</div>',
83410         '</div>'
83411     ],
83412
83413     componentLayout: 'progressbar',
83414
83415     // private
83416     initComponent: function() {
83417         this.callParent();
83418
83419         this.renderSelectors = Ext.apply(this.renderSelectors || {}, {
83420             textTopEl: '.' + this.baseCls + '-text',
83421             textBackEl: '.' + this.baseCls + '-text-back',
83422             bar: '.' + this.baseCls + '-bar'
83423         });
83424
83425         this.addEvents(
83426             /**
83427              * @event update
83428              * Fires after each update interval
83429              * @param {Ext.ProgressBar} this
83430              * @param {Number} The current progress value
83431              * @param {String} The current progress text
83432              */
83433             "update"
83434         );
83435     },
83436
83437     afterRender : function() {
83438         var me = this;
83439
83440         me.textEl = me.textEl ? Ext.get(me.textEl) : me.el.select('.' + me.baseCls + '-text');
83441
83442         this.callParent(arguments);
83443
83444         if (me.value) {
83445             me.updateProgress(me.value, me.text);
83446         }
83447         else {
83448             me.updateText(me.text);
83449         }
83450     },
83451
83452     /**
83453      * Updates the progress bar value, and optionally its text.  If the text argument is not specified,
83454      * any existing text value will be unchanged.  To blank out existing text, pass ''.  Note that even
83455      * if the progress bar value exceeds 1, it will never automatically reset -- you are responsible for
83456      * determining when the progress is complete and calling {@link #reset} to clear and/or hide the control.
83457      * @param {Float} value (optional) A floating point value between 0 and 1 (e.g., .5, defaults to 0)
83458      * @param {String} text (optional) The string to display in the progress text element (defaults to '')
83459      * @param {Boolean} animate (optional) Whether to animate the transition of the progress bar. If this value is
83460      * not specified, the default for the class is used (default to false)
83461      * @return {Ext.ProgressBar} this
83462      */
83463     updateProgress: function(value, text, animate) {
83464         var newWidth;
83465         this.value = value || 0;
83466         if (text) {
83467             this.updateText(text);
83468         }
83469         if (this.rendered && !this.isDestroyed) {
83470             newWidth = Math.floor(this.value * this.el.getWidth(true));
83471             if (Ext.isForcedBorderBox) {
83472                 newWidth += this.bar.getBorderWidth("lr");
83473             }
83474             if (animate === true || (animate !== false && this.animate)) {
83475                 this.bar.stopAnimation();
83476                 this.bar.animate(Ext.apply({
83477                     to: {
83478                         width: newWidth + 'px'
83479                     }
83480                 }, this.animate));
83481             } else {
83482                 this.bar.setWidth(newWidth);
83483             }
83484         }
83485         this.fireEvent('update', this, this.value, text);
83486         return this;
83487     },
83488
83489     /**
83490      * Updates the progress bar text.  If specified, textEl will be updated, otherwise the progress
83491      * bar itself will display the updated text.
83492      * @param {String} text (optional) The string to display in the progress text element (defaults to '')
83493      * @return {Ext.ProgressBar} this
83494      */
83495     updateText: function(text) {
83496         this.text = text;
83497         if (this.rendered) {
83498             this.textEl.update(this.text);
83499         }
83500         return this;
83501     },
83502
83503     applyText : function(text) {
83504         this.updateText(text);
83505     },
83506
83507     /**
83508          * Initiates an auto-updating progress bar.  A duration can be specified, in which case the progress
83509          * bar will automatically reset after a fixed amount of time and optionally call a callback function
83510          * if specified.  If no duration is passed in, then the progress bar will run indefinitely and must
83511          * be manually cleared by calling {@link #reset}.  The wait method accepts a config object with
83512          * the following properties:
83513          * <pre>
83514     Property   Type          Description
83515     ---------- ------------  ----------------------------------------------------------------------
83516     duration   Number        The length of time in milliseconds that the progress bar should
83517                              run before resetting itself (defaults to undefined, in which case it
83518                              will run indefinitely until reset is called)
83519     interval   Number        The length of time in milliseconds between each progress update
83520                              (defaults to 1000 ms)
83521     animate    Boolean       Whether to animate the transition of the progress bar. If this value is
83522                              not specified, the default for the class is used.
83523     increment  Number        The number of progress update segments to display within the progress
83524                              bar (defaults to 10).  If the bar reaches the end and is still
83525                              updating, it will automatically wrap back to the beginning.
83526     text       String        Optional text to display in the progress bar element (defaults to '').
83527     fn         Function      A callback function to execute after the progress bar finishes auto-
83528                              updating.  The function will be called with no arguments.  This function
83529                              will be ignored if duration is not specified since in that case the
83530                              progress bar can only be stopped programmatically, so any required function
83531                              should be called by the same code after it resets the progress bar.
83532     scope      Object        The scope that is passed to the callback function (only applies when
83533                              duration and fn are both passed).
83534     </pre>
83535              *
83536              * Example usage:
83537              * <pre><code>
83538     var p = new Ext.ProgressBar({
83539        renderTo: 'my-el'
83540     });
83541
83542     //Wait for 5 seconds, then update the status el (progress bar will auto-reset)
83543     var p = Ext.create('Ext.ProgressBar', {
83544        renderTo: Ext.getBody(),
83545        width: 300
83546     });
83547
83548     //Wait for 5 seconds, then update the status el (progress bar will auto-reset)
83549     p.wait({
83550        interval: 500, //bar will move fast!
83551        duration: 50000,
83552        increment: 15,
83553        text: 'Updating...',
83554        scope: this,
83555        fn: function(){
83556           p.updateText('Done!');
83557        }
83558     });
83559
83560     //Or update indefinitely until some async action completes, then reset manually
83561     p.wait();
83562     myAction.on('complete', function(){
83563         p.reset();
83564         p.updateText('Done!');
83565     });
83566     </code></pre>
83567          * @param {Object} config (optional) Configuration options
83568          * @return {Ext.ProgressBar} this
83569          */
83570     wait: function(o) {
83571         if (!this.waitTimer) {
83572             var scope = this;
83573             o = o || {};
83574             this.updateText(o.text);
83575             this.waitTimer = Ext.TaskManager.start({
83576                 run: function(i){
83577                     var inc = o.increment || 10;
83578                     i -= 1;
83579                     this.updateProgress(((((i+inc)%inc)+1)*(100/inc))*0.01, null, o.animate);
83580                 },
83581                 interval: o.interval || 1000,
83582                 duration: o.duration,
83583                 onStop: function(){
83584                     if (o.fn) {
83585                         o.fn.apply(o.scope || this);
83586                     }
83587                     this.reset();
83588                 },
83589                 scope: scope
83590             });
83591         }
83592         return this;
83593     },
83594
83595     /**
83596      * Returns true if the progress bar is currently in a {@link #wait} operation
83597      * @return {Boolean} True if waiting, else false
83598      */
83599     isWaiting: function(){
83600         return this.waitTimer !== null;
83601     },
83602
83603     /**
83604      * Resets the progress bar value to 0 and text to empty string.  If hide = true, the progress
83605      * bar will also be hidden (using the {@link #hideMode} property internally).
83606      * @param {Boolean} hide (optional) True to hide the progress bar (defaults to false)
83607      * @return {Ext.ProgressBar} this
83608      */
83609     reset: function(hide){
83610         this.updateProgress(0);
83611         this.clearTimer();
83612         if (hide === true) {
83613             this.hide();
83614         }
83615         return this;
83616     },
83617
83618     // private
83619     clearTimer: function(){
83620         if (this.waitTimer) {
83621             this.waitTimer.onStop = null; //prevent recursion
83622             Ext.TaskManager.stop(this.waitTimer);
83623             this.waitTimer = null;
83624         }
83625     },
83626
83627     onDestroy: function(){
83628         this.clearTimer();
83629         if (this.rendered) {
83630             if (this.textEl.isComposite) {
83631                 this.textEl.clear();
83632             }
83633             Ext.destroyMembers(this, 'textEl', 'progressBar', 'textTopEl');
83634         }
83635         this.callParent();
83636     }
83637 });
83638
83639 /**
83640  * @class Ext.ShadowPool
83641  * @extends Object
83642  * Private utility class that manages the internal Shadow cache
83643  * @private
83644  */
83645 Ext.define('Ext.ShadowPool', {
83646     singleton: true,
83647     requires: ['Ext.core.DomHelper'],
83648
83649     markup: function() {
83650         if (Ext.supports.CSS3BoxShadow) {
83651             return '<div class="' + Ext.baseCSSPrefix + 'css-shadow" role="presentation"></div>';
83652         } else if (Ext.isIE) {
83653             return '<div class="' + Ext.baseCSSPrefix + 'ie-shadow" role="presentation"></div>';
83654         } else {
83655             return '<div class="' + Ext.baseCSSPrefix + 'frame-shadow" role="presentation">' +
83656                 '<div class="xst" role="presentation">' +
83657                     '<div class="xstl" role="presentation"></div>' +
83658                     '<div class="xstc" role="presentation"></div>' +
83659                     '<div class="xstr" role="presentation"></div>' +
83660                 '</div>' +
83661                 '<div class="xsc" role="presentation">' +
83662                     '<div class="xsml" role="presentation"></div>' +
83663                     '<div class="xsmc" role="presentation"></div>' +
83664                     '<div class="xsmr" role="presentation"></div>' +
83665                 '</div>' +
83666                 '<div class="xsb" role="presentation">' +
83667                     '<div class="xsbl" role="presentation"></div>' +
83668                     '<div class="xsbc" role="presentation"></div>' +
83669                     '<div class="xsbr" role="presentation"></div>' +
83670                 '</div>' +
83671             '</div>';
83672         }
83673     }(),
83674
83675     shadows: [],
83676
83677     pull: function() {
83678         var sh = this.shadows.shift();
83679         if (!sh) {
83680             sh = Ext.get(Ext.core.DomHelper.insertHtml("beforeBegin", document.body.firstChild, this.markup));
83681             sh.autoBoxAdjust = false;
83682         }
83683         return sh;
83684     },
83685
83686     push: function(sh) {
83687         this.shadows.push(sh);
83688     },
83689     
83690     reset: function() {
83691         Ext.Array.each(this.shadows, function(shadow) {
83692             shadow.remove();
83693         });
83694         this.shadows = [];
83695     }
83696 });
83697 /**
83698  * @class Ext.Shadow
83699  * Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
83700  * and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
83701  * functionality that can also provide the same shadow effect, see the {@link Ext.Layer} class.
83702  * @constructor
83703  * Create a new Shadow
83704  * @param {Object} config The config object
83705  */
83706 Ext.define('Ext.Shadow', {
83707     requires: ['Ext.ShadowPool'],
83708
83709     constructor: function(config) {
83710         Ext.apply(this, config);
83711         if (typeof this.mode != "string") {
83712             this.mode = this.defaultMode;
83713         }
83714         var offset = this.offset,
83715             adjusts = {
83716                 h: 0
83717             },
83718             rad = Math.floor(this.offset / 2);
83719
83720         switch (this.mode.toLowerCase()) {
83721             // all this hideous nonsense calculates the various offsets for shadows
83722             case "drop":
83723                 if (Ext.supports.CSS3BoxShadow) {
83724                     adjusts.w = adjusts.h = -offset;
83725                     adjusts.l = adjusts.t = offset;
83726                 } else {
83727                     adjusts.w = 0;
83728                     adjusts.l = adjusts.t = offset;
83729                     adjusts.t -= 1;
83730                     if (Ext.isIE) {
83731                         adjusts.l -= offset + rad;
83732                         adjusts.t -= offset + rad;
83733                         adjusts.w -= rad;
83734                         adjusts.h -= rad;
83735                         adjusts.t += 1;
83736                     }
83737                 }
83738                 break;
83739             case "sides":
83740                 if (Ext.supports.CSS3BoxShadow) {
83741                     adjusts.h -= offset;
83742                     adjusts.t = offset;
83743                     adjusts.l = adjusts.w = 0;
83744                 } else {
83745                     adjusts.w = (offset * 2);
83746                     adjusts.l = -offset;
83747                     adjusts.t = offset - 1;
83748                     if (Ext.isIE) {
83749                         adjusts.l -= (offset - rad);
83750                         adjusts.t -= offset + rad;
83751                         adjusts.l += 1;
83752                         adjusts.w -= (offset - rad) * 2;
83753                         adjusts.w -= rad + 1;
83754                         adjusts.h -= 1;
83755                     }
83756                 }
83757                 break;
83758             case "frame":
83759                 if (Ext.supports.CSS3BoxShadow) {
83760                     adjusts.l = adjusts.w = adjusts.t = 0;
83761                 } else {
83762                     adjusts.w = adjusts.h = (offset * 2);
83763                     adjusts.l = adjusts.t = -offset;
83764                     adjusts.t += 1;
83765                     adjusts.h -= 2;
83766                     if (Ext.isIE) {
83767                         adjusts.l -= (offset - rad);
83768                         adjusts.t -= (offset - rad);
83769                         adjusts.l += 1;
83770                         adjusts.w -= (offset + rad + 1);
83771                         adjusts.h -= (offset + rad);
83772                         adjusts.h += 1;
83773                     }
83774                     break;
83775                 }
83776         }
83777         this.adjusts = adjusts;
83778     },
83779
83780     /**
83781      * @cfg {String} mode
83782      * The shadow display mode.  Supports the following options:<div class="mdetail-params"><ul>
83783      * <li><b><tt>sides</tt></b> : Shadow displays on both sides and bottom only</li>
83784      * <li><b><tt>frame</tt></b> : Shadow displays equally on all four sides</li>
83785      * <li><b><tt>drop</tt></b> : Traditional bottom-right drop shadow</li>
83786      * </ul></div>
83787      */
83788     /**
83789      * @cfg {String} offset
83790      * The number of pixels to offset the shadow from the element (defaults to <tt>4</tt>)
83791      */
83792     offset: 4,
83793
83794     // private
83795     defaultMode: "drop",
83796
83797     /**
83798      * Displays the shadow under the target element
83799      * @param {Mixed} targetEl The id or element under which the shadow should display
83800      */
83801     show: function(target) {
83802         target = Ext.get(target);
83803         if (!this.el) {
83804             this.el = Ext.ShadowPool.pull();
83805             if (this.el.dom.nextSibling != target.dom) {
83806                 this.el.insertBefore(target);
83807             }
83808         }
83809         this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10) - 1);
83810         if (Ext.isIE && !Ext.supports.CSS3BoxShadow) {
83811             this.el.dom.style.filter = "progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius=" + (this.offset) + ")";
83812         }
83813         this.realign(
83814             target.getLeft(true),
83815             target.getTop(true),
83816             target.getWidth(),
83817             target.getHeight()
83818         );
83819         this.el.dom.style.display = "block";
83820     },
83821
83822     /**
83823      * Returns true if the shadow is visible, else false
83824      */
83825     isVisible: function() {
83826         return this.el ? true: false;
83827     },
83828
83829     /**
83830      * Direct alignment when values are already available. Show must be called at least once before
83831      * calling this method to ensure it is initialized.
83832      * @param {Number} left The target element left position
83833      * @param {Number} top The target element top position
83834      * @param {Number} width The target element width
83835      * @param {Number} height The target element height
83836      */
83837     realign: function(l, t, targetWidth, targetHeight) {
83838         if (!this.el) {
83839             return;
83840         }
83841         var adjusts = this.adjusts,
83842             d = this.el.dom,
83843             targetStyle = d.style,
83844             shadowWidth,
83845             shadowHeight,
83846             cn,
83847             sww, 
83848             sws, 
83849             shs;
83850
83851         targetStyle.left = (l + adjusts.l) + "px";
83852         targetStyle.top = (t + adjusts.t) + "px";
83853         shadowWidth = Math.max(targetWidth + adjusts.w, 0);
83854         shadowHeight = Math.max(targetHeight + adjusts.h, 0);
83855         sws = shadowWidth + "px";
83856         shs = shadowHeight + "px";
83857         if (targetStyle.width != sws || targetStyle.height != shs) {
83858             targetStyle.width = sws;
83859             targetStyle.height = shs;
83860             if (Ext.supports.CSS3BoxShadow) {
83861                 targetStyle.boxShadow = '0 0 ' + this.offset + 'px 0 #888';
83862             } else {
83863
83864                 // Adjust the 9 point framed element to poke out on the required sides
83865                 if (!Ext.isIE) {
83866                     cn = d.childNodes;
83867                     sww = Math.max(0, (shadowWidth - 12)) + "px";
83868                     cn[0].childNodes[1].style.width = sww;
83869                     cn[1].childNodes[1].style.width = sww;
83870                     cn[2].childNodes[1].style.width = sww;
83871                     cn[1].style.height = Math.max(0, (shadowHeight - 12)) + "px";
83872                 }
83873             }
83874         }
83875     },
83876
83877     /**
83878      * Hides this shadow
83879      */
83880     hide: function() {
83881         if (this.el) {
83882             this.el.dom.style.display = "none";
83883             Ext.ShadowPool.push(this.el);
83884             delete this.el;
83885         }
83886     },
83887
83888     /**
83889      * Adjust the z-index of this shadow
83890      * @param {Number} zindex The new z-index
83891      */
83892     setZIndex: function(z) {
83893         this.zIndex = z;
83894         if (this.el) {
83895             this.el.setStyle("z-index", z);
83896         }
83897     }
83898 });
83899 /**
83900  * @class Ext.button.Split
83901  * @extends Ext.button.Button
83902  * A split button that provides a built-in dropdown arrow that can fire an event separately from the default
83903  * click event of the button.  Typically this would be used to display a dropdown menu that provides additional
83904  * options to the primary button action, but any custom handler can provide the arrowclick implementation.  
83905  * {@img Ext.button.Split/Ext.button.Split.png Ext.button.Split component}
83906  * Example usage:
83907  * <pre><code>
83908 // display a dropdown menu:
83909     Ext.create('Ext.button.Split', {
83910         renderTo: 'button-ct', // the container id
83911         text: 'Options',
83912         handler: optionsHandler, // handle a click on the button itself
83913         menu: new Ext.menu.Menu({
83914         items: [
83915                 // these items will render as dropdown menu items when the arrow is clicked:
83916                 {text: 'Item 1', handler: item1Handler},
83917                 {text: 'Item 2', handler: item2Handler}
83918         ]
83919         })
83920     });
83921
83922 // Instead of showing a menu, you provide any type of custom
83923 // functionality you want when the dropdown arrow is clicked:
83924     Ext.create('Ext.button.Split', {
83925         renderTo: 'button-ct',
83926         text: 'Options',
83927         handler: optionsHandler,
83928         arrowHandler: myCustomHandler
83929     });
83930 </code></pre>
83931  * @cfg {Function} arrowHandler A function called when the arrow button is clicked (can be used instead of click event)
83932  * @cfg {String} arrowTooltip The title attribute of the arrow
83933  * @constructor
83934  * Create a new menu button
83935  * @param {Object} config The config object
83936  * @xtype splitbutton
83937  */
83938
83939 Ext.define('Ext.button.Split', {
83940
83941     /* Begin Definitions */
83942
83943     alias: 'widget.splitbutton',
83944
83945     extend: 'Ext.button.Button',
83946     alternateClassName: 'Ext.SplitButton',
83947
83948     // private
83949     arrowCls      : 'split',
83950     split         : true,
83951
83952     // private
83953     initComponent : function(){
83954         this.callParent();
83955         /**
83956          * @event arrowclick
83957          * Fires when this button's arrow is clicked
83958          * @param {MenuButton} this
83959          * @param {EventObject} e The click event
83960          */
83961         this.addEvents("arrowclick");
83962     },
83963
83964      /**
83965      * Sets this button's arrow click handler.
83966      * @param {Function} handler The function to call when the arrow is clicked
83967      * @param {Object} scope (optional) Scope for the function passed above
83968      */
83969     setArrowHandler : function(handler, scope){
83970         this.arrowHandler = handler;
83971         this.scope = scope;
83972     },
83973
83974     // private
83975     onClick : function(e, t) {
83976         var me = this;
83977         
83978         e.preventDefault();
83979         if (!me.disabled) {
83980             if (me.overMenuTrigger) {
83981                 if (me.menu && !me.menu.isVisible() && !me.ignoreNextClick) {
83982                     me.showMenu();
83983                 }
83984                 me.fireEvent("arrowclick", me, e);
83985                 if (me.arrowHandler) {
83986                     me.arrowHandler.call(me.scope || me, me, e);
83987                 }
83988             } else {
83989                 if (me.enableToggle) {
83990                     me.toggle();
83991                 }
83992                 me.fireEvent("click", me, e);
83993                 if (me.handler) {
83994                     me.handler.call(me.scope || me, me, e);
83995                 }
83996                 me.onBlur();
83997             }
83998         }
83999     }
84000 });
84001 /**
84002  * @class Ext.button.Cycle
84003  * @extends Ext.button.Split
84004  * A specialized SplitButton that contains a menu of {@link Ext.menu.CheckItem} elements.  The button automatically
84005  * cycles through each menu item on click, raising the button's {@link #change} event (or calling the button's
84006  * {@link #changeHandler} function, if supplied) for the active menu item. Clicking on the arrow section of the
84007  * button displays the dropdown menu just like a normal SplitButton.  
84008  * {@img Ext.button.Cycle/Ext.button.Cycle.png Ext.button.Cycle component}
84009  * Example usage:
84010  * <pre><code>
84011     Ext.create('Ext.button.Cycle', {
84012         showText: true,
84013         prependText: 'View as ',
84014         renderTo: Ext.getBody(),
84015         menu: {
84016             id: 'view-type-menu',
84017             items: [{
84018                 text:'text only',
84019                 iconCls:'view-text',
84020                 checked:true
84021             },{
84022                 text:'HTML',
84023                 iconCls:'view-html'
84024             }]
84025         },
84026         changeHandler:function(cycleBtn, activeItem){
84027             Ext.Msg.alert('Change View', activeItem.text);
84028         }
84029     });
84030 </code></pre>
84031  * @constructor
84032  * Create a new split button
84033  * @param {Object} config The config object
84034  * @xtype cycle
84035  */
84036
84037 Ext.define('Ext.button.Cycle', {
84038
84039     /* Begin Definitions */
84040
84041     alias: 'widget.cycle',
84042
84043     extend: 'Ext.button.Split',
84044     alternateClassName: 'Ext.CycleButton',
84045
84046     /* End Definitions */
84047
84048     /**
84049      * @cfg {Array} items <p>Deprecated as of 4.0. Use the {@link #menu} config instead. All menu items will be created
84050      * as {@link Ext.menu.CheckItem CheckItem}s.</p>
84051      * <p>An array of {@link Ext.menu.CheckItem} <b>config</b> objects to be used when creating the
84052      * button's menu items (e.g., {text:'Foo', iconCls:'foo-icon'})
84053      */
84054     /**
84055      * @cfg {Boolean} showText True to display the active item's text as the button text (defaults to false).
84056      * The Button will show its configured {@link #text} if this. config is omitted.
84057      */
84058     /**
84059      * @cfg {String} prependText A static string to prepend before the active item's text when displayed as the
84060      * button's text (only applies when showText = true, defaults to '')
84061      */
84062     /**
84063      * @cfg {Function} changeHandler A callback function that will be invoked each time the active menu
84064      * item in the button's menu has changed.  If this callback is not supplied, the SplitButton will instead
84065      * fire the {@link #change} event on active item change.  The changeHandler function will be called with the
84066      * following argument list: (SplitButton this, Ext.menu.CheckItem item)
84067      */
84068     /**
84069      * @cfg {String} forceIcon A css class which sets an image to be used as the static icon for this button.  This
84070      * icon will always be displayed regardless of which item is selected in the dropdown list.  This overrides the 
84071      * default behavior of changing the button's icon to match the selected item's icon on change.
84072      */
84073     /**
84074      * @property menu
84075      * @type Menu
84076      * The {@link Ext.menu.Menu Menu} object used to display the {@link Ext.menu.CheckItem CheckItems} representing the available choices.
84077      */
84078
84079     // private
84080     getButtonText: function(item) {
84081         var me = this,
84082             text = '';
84083
84084         if (item && me.showText === true) {
84085             if (me.prependText) {
84086                 text += me.prependText;
84087             }
84088             text += item.text;
84089             return text;
84090         }
84091         return me.text;
84092     },
84093
84094     /**
84095      * Sets the button's active menu item.
84096      * @param {Ext.menu.CheckItem} item The item to activate
84097      * @param {Boolean} suppressEvent True to prevent the button's change event from firing (defaults to false)
84098      */
84099     setActiveItem: function(item, suppressEvent) {
84100         var me = this;
84101
84102         if (!Ext.isObject(item)) {
84103             item = me.menu.getComponent(item);
84104         }
84105         if (item) {
84106             if (!me.rendered) {
84107                 me.text = me.getButtonText(item);
84108                 me.iconCls = item.iconCls;
84109             } else {
84110                 me.setText(me.getButtonText(item));
84111                 me.setIconCls(item.iconCls);
84112             }
84113             me.activeItem = item;
84114             if (!item.checked) {
84115                 item.setChecked(true, false);
84116             }
84117             if (me.forceIcon) {
84118                 me.setIconCls(me.forceIcon);
84119             }
84120             if (!suppressEvent) {
84121                 me.fireEvent('change', me, item);
84122             }
84123         }
84124     },
84125
84126     /**
84127      * Gets the currently active menu item.
84128      * @return {Ext.menu.CheckItem} The active item
84129      */
84130     getActiveItem: function() {
84131         return this.activeItem;
84132     },
84133
84134     // private
84135     initComponent: function() {
84136         var me = this,
84137             checked = 0,
84138             items;
84139
84140         me.addEvents(
84141             /**
84142              * @event change
84143              * Fires after the button's active menu item has changed.  Note that if a {@link #changeHandler} function
84144              * is set on this CycleButton, it will be called instead on active item change and this change event will
84145              * not be fired.
84146              * @param {Ext.button.Cycle} this
84147              * @param {Ext.menu.CheckItem} item The menu item that was selected
84148              */
84149             "change"
84150         );
84151
84152         if (me.changeHandler) {
84153             me.on('change', me.changeHandler, me.scope || me);
84154             delete me.changeHandler;
84155         }
84156
84157         // Allow them to specify a menu config which is a standard Button config.
84158         // Remove direct use of "items" in 5.0.
84159         items = (me.menu.items||[]).concat(me.items||[]);
84160         me.menu = Ext.applyIf({
84161             cls: Ext.baseCSSPrefix + 'cycle-menu',
84162             items: []
84163         }, me.menu);
84164
84165         // Convert all items to CheckItems
84166         Ext.each(items, function(item, i) {
84167             item = Ext.applyIf({
84168                 group: me.id,
84169                 itemIndex: i,
84170                 checkHandler: me.checkHandler,
84171                 scope: me,
84172                 checked: item.checked || false
84173             }, item);
84174             me.menu.items.push(item);
84175             if (item.checked) {
84176                 checked = i;
84177             }
84178         });
84179         me.itemCount = me.menu.items.length;
84180         me.callParent(arguments);
84181         me.on('click', me.toggleSelected, me);
84182         me.setActiveItem(checked, me);
84183
84184         // If configured with a fixed width, the cycling will center a different child item's text each click. Prevent this.
84185         if (me.width && me.showText) {
84186             me.addCls(Ext.baseCSSPrefix + 'cycle-fixed-width');
84187         }
84188     },
84189
84190     // private
84191     checkHandler: function(item, pressed) {
84192         if (pressed) {
84193             this.setActiveItem(item);
84194         }
84195     },
84196
84197     /**
84198      * This is normally called internally on button click, but can be called externally to advance the button's
84199      * active item programmatically to the next one in the menu.  If the current item is the last one in the menu
84200      * the active item will be set to the first item in the menu.
84201      */
84202     toggleSelected: function() {
84203         var me = this,
84204             m = me.menu,
84205             checkItem;
84206
84207         checkItem = me.activeItem.next(':not([disabled])') || m.items.getAt(0);
84208         checkItem.setChecked(true);
84209     }
84210 });
84211 /**
84212  * @class Ext.container.ButtonGroup
84213  * @extends Ext.panel.Panel
84214  * <p>Provides a container for arranging a group of related Buttons in a tabular manner.</p>
84215  * Example usage:
84216  * {@img Ext.container.ButtonGroup/Ext.container.ButtonGroup.png Ext.container.ButtonGroup component}
84217  * <pre><code>
84218     Ext.create('Ext.panel.Panel', {
84219         title: 'Panel with ButtonGroup',
84220         width: 300,
84221         height:200,
84222         renderTo: document.body,
84223         html: 'HTML Panel Content',
84224         tbar: [{
84225             xtype: 'buttongroup',
84226             columns: 3,
84227             title: 'Clipboard',
84228             items: [{
84229                 text: 'Paste',
84230                 scale: 'large',
84231                 rowspan: 3,
84232                 iconCls: 'add',
84233                 iconAlign: 'top',
84234                 cls: 'x-btn-as-arrow'
84235             },{
84236                 xtype:'splitbutton',
84237                 text: 'Menu Button',
84238                 scale: 'large',
84239                 rowspan: 3,
84240                 iconCls: 'add',
84241                 iconAlign: 'top',
84242                 arrowAlign:'bottom',
84243                 menu: [{text: 'Menu Item 1'}]
84244             },{
84245                 xtype:'splitbutton', text: 'Cut', iconCls: 'add16', menu: [{text: 'Cut Menu Item'}]
84246             },{
84247                 text: 'Copy', iconCls: 'add16'
84248             },{
84249                 text: 'Format', iconCls: 'add16'
84250             }]
84251         }]
84252     });
84253  * </code></pre>
84254  * @constructor
84255  * Create a new ButtonGroup.
84256  * @param {Object} config The config object
84257  * @xtype buttongroup
84258  */
84259 Ext.define('Ext.container.ButtonGroup', {
84260     extend: 'Ext.panel.Panel',
84261     alias: 'widget.buttongroup',
84262     alternateClassName: 'Ext.ButtonGroup',
84263
84264     /**
84265      * @cfg {Number} columns The <tt>columns</tt> configuration property passed to the
84266      * {@link #layout configured layout manager}. See {@link Ext.layout.container.Table#columns}.
84267      */
84268
84269     /**
84270      * @cfg {String} baseCls  Defaults to <tt>'x-btn-group'</tt>.  See {@link Ext.panel.Panel#baseCls}.
84271      */
84272     baseCls: Ext.baseCSSPrefix + 'btn-group',
84273
84274     /**
84275      * @cfg {Object} layout  Defaults to <tt>'table'</tt>.  See {@link Ext.container.Container#layout}.
84276      */
84277     layout: {
84278         type: 'table'
84279     },
84280
84281     defaultType: 'button',
84282
84283     /**
84284      * @cfg {Boolean} frame  Defaults to <tt>true</tt>.  See {@link Ext.panel.Panel#frame}.
84285      */
84286     frame: true,
84287     
84288     frameHeader: false,
84289     
84290     internalDefaults: {removeMode: 'container', hideParent: true},
84291
84292     initComponent : function(){
84293         // Copy the component's columns config to the layout if specified
84294         var me = this,
84295             cols = me.columns;
84296
84297         me.noTitleCls = me.baseCls + '-notitle';
84298         if (cols) {
84299             me.layout = Ext.apply({}, {columns: cols}, me.layout);
84300         }
84301
84302         if (!me.title) {
84303             me.addCls(me.noTitleCls);
84304         }
84305         me.callParent(arguments);
84306     },
84307
84308     afterLayout: function() {
84309         var me = this;
84310         
84311         me.callParent(arguments);
84312
84313         // Pugly hack for a pugly browser:
84314         // If not an explicitly set width, then size the width to match the inner table
84315         if (me.layout.table && (Ext.isIEQuirks || Ext.isIE6) && !me.width) {
84316             var t = me.getTargetEl();
84317             t.setWidth(me.layout.table.offsetWidth + t.getPadding('lr'));
84318         }
84319     },
84320
84321     afterRender: function() {
84322         var me = this;
84323         
84324         //we need to add an addition item in here so the ButtonGroup title is centered
84325         if (me.header) {
84326             me.header.insert(0, {
84327                 xtype: 'component',
84328                 ui   : me.ui,
84329                 html : '&nbsp;',
84330                 flex : 1
84331             });
84332         }
84333         
84334         me.callParent(arguments);
84335     },
84336     
84337     // private
84338     onBeforeAdd: function(component) {
84339         if (component.is('button')) {
84340             component.ui = component.ui + '-toolbar';
84341         }
84342         this.callParent(arguments);
84343     },
84344
84345     //private
84346     applyDefaults: function(c) {
84347         if (!Ext.isString(c)) {
84348             c = this.callParent(arguments);
84349             var d = this.internalDefaults;
84350             if (c.events) {
84351                 Ext.applyIf(c.initialConfig, d);
84352                 Ext.apply(c, d);
84353             } else {
84354                 Ext.applyIf(c, d);
84355             }
84356         }
84357         return c;
84358     }
84359
84360     /**
84361      * @cfg {Array} tools  @hide
84362      */
84363     /**
84364      * @cfg {Boolean} collapsible  @hide
84365      */
84366     /**
84367      * @cfg {Boolean} collapseMode  @hide
84368      */
84369     /**
84370      * @cfg {Boolean} animCollapse  @hide
84371      */
84372     /**
84373      * @cfg {Boolean} closable  @hide
84374      */
84375 });
84376
84377 /**
84378  * @class Ext.container.Viewport
84379  * @extends Ext.container.Container
84380
84381 A specialized container representing the viewable application area (the browser viewport).
84382
84383 The Viewport renders itself to the document body, and automatically sizes itself to the size of
84384 the browser viewport and manages window resizing. There may only be one Viewport created
84385 in a page.
84386
84387 Like any {@link Ext.container.Container Container}, a Viewport will only perform sizing and positioning
84388 on its child Components if you configure it with a {@link #layout}.
84389
84390 A Common layout used with Viewports is {@link Ext.layout.container.Border border layout}, but if the
84391 required layout is simpler, a different layout should be chosen.
84392
84393 For example, to simply make a single child item occupy all available space, use {@link Ext.layout.container.Fit fit layout}.
84394
84395 To display one "active" item at full size from a choice of several child items, use {@link Ext.layout.container.Card card layout}.
84396
84397 Inner layouts are available by virtue of the fact that all {@link Ext.panel.Panel Panel}s
84398 added to the Viewport, either through its {@link #items}, or through the items, or the {@link #add}
84399 method of any of its child Panels may themselves have a layout.
84400
84401 The Viewport does not provide scrolling, so child Panels within the Viewport should provide
84402 for scrolling if needed using the {@link #autoScroll} config.
84403 {@img Ext.container.Viewport/Ext.container.Viewport.png Ext.container.Viewport component}
84404 An example showing a classic application border layout:
84405
84406     Ext.create('Ext.container.Viewport', {
84407         layout: 'border',
84408         renderTo: Ext.getBody(),
84409         items: [{
84410             region: 'north',
84411             html: '<h1 class="x-panel-header">Page Title</h1>',
84412             autoHeight: true,
84413             border: false,
84414             margins: '0 0 5 0'
84415         }, {
84416             region: 'west',
84417             collapsible: true,
84418             title: 'Navigation',
84419             width: 150
84420             // could use a TreePanel or AccordionLayout for navigational items
84421         }, {
84422             region: 'south',
84423             title: 'South Panel',
84424             collapsible: true,
84425             html: 'Information goes here',
84426             split: true,
84427             height: 100,
84428             minHeight: 100
84429         }, {
84430             region: 'east',
84431             title: 'East Panel',
84432             collapsible: true,
84433             split: true,
84434             width: 150
84435         }, {
84436             region: 'center',
84437             xtype: 'tabpanel', // TabPanel itself has no title
84438             activeTab: 0,      // First tab active by default
84439             items: {
84440                 title: 'Default Tab',
84441                 html: 'The first tab\'s content. Others may be added dynamically'
84442             }
84443         }]
84444     });
84445
84446  * @constructor
84447  * Create a new Viewport
84448  * @param {Object} config The config object
84449  * @markdown
84450  * @xtype viewport
84451  */
84452 Ext.define('Ext.container.Viewport', {
84453     extend: 'Ext.container.Container',
84454     alias: 'widget.viewport',
84455     requires: ['Ext.EventManager'],
84456     alternateClassName: 'Ext.Viewport',
84457
84458     /*
84459      * Privatize config options which, if used, would interfere with the
84460      * correct operation of the Viewport as the sole manager of the
84461      * layout of the document body.
84462      */
84463     /**
84464      * @cfg {Mixed} applyTo @hide
84465      */
84466     /**
84467      * @cfg {Boolean} allowDomMove @hide
84468      */
84469     /**
84470      * @cfg {Boolean} hideParent @hide
84471      */
84472     /**
84473      * @cfg {Mixed} renderTo @hide
84474      */
84475     /**
84476      * @cfg {Boolean} hideParent @hide
84477      */
84478     /**
84479      * @cfg {Number} height @hide
84480      */
84481     /**
84482      * @cfg {Number} width @hide
84483      */
84484     /**
84485      * @cfg {Boolean} autoHeight @hide
84486      */
84487     /**
84488      * @cfg {Boolean} autoWidth @hide
84489      */
84490     /**
84491      * @cfg {Boolean} deferHeight @hide
84492      */
84493     /**
84494      * @cfg {Boolean} monitorResize @hide
84495      */
84496
84497     isViewport: true,
84498
84499     ariaRole: 'application',
84500     initComponent : function() {
84501         var me = this,
84502             html = Ext.fly(document.body.parentNode),
84503             el;
84504         me.callParent(arguments);
84505         html.addCls(Ext.baseCSSPrefix + 'viewport');
84506         if (me.autoScroll) {
84507             html.setStyle('overflow', 'auto');
84508         }
84509         me.el = el = Ext.getBody();
84510         el.setHeight = Ext.emptyFn;
84511         el.setWidth = Ext.emptyFn;
84512         el.setSize = Ext.emptyFn;
84513         el.dom.scroll = 'no';
84514         me.allowDomMove = false;
84515         //this.autoWidth = true;
84516         //this.autoHeight = true;
84517         Ext.EventManager.onWindowResize(me.fireResize, me);
84518         me.renderTo = me.el;
84519     },
84520
84521     fireResize : function(w, h){
84522         // setSize is the single entry point to layouts
84523         this.setSize(w, h);
84524         //this.fireEvent('resize', this, w, h, w, h);
84525     }
84526 });
84527
84528 /*
84529  * This is a derivative of the similarly named class in the YUI Library.
84530  * The original license:
84531  * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
84532  * Code licensed under the BSD License:
84533  * http://developer.yahoo.net/yui/license.txt
84534  */
84535
84536
84537 /**
84538  * @class Ext.dd.DDTarget
84539  * A DragDrop implementation that does not move, but can be a drop
84540  * target.  You would get the same result by simply omitting implementation
84541  * for the event callbacks, but this way we reduce the processing cost of the
84542  * event listener and the callbacks.
84543  * @extends Ext.dd.DragDrop
84544  * @constructor
84545  * @param {String} id the id of the element that is a drop target
84546  * @param {String} sGroup the group of related DragDrop objects
84547  * @param {object} config an object containing configurable attributes
84548  *                 Valid properties for DDTarget in addition to those in
84549  *                 DragDrop:
84550  *                    none
84551  */
84552 Ext.define('Ext.dd.DDTarget', {
84553     extend: 'Ext.dd.DragDrop',
84554     constructor: function(id, sGroup, config) {
84555         if (id) {
84556             this.initTarget(id, sGroup, config);
84557         }
84558     },
84559
84560     /**
84561      * @hide
84562      * Overridden and disabled. A DDTarget does not support being dragged.
84563      * @method
84564      */
84565     getDragEl: Ext.emptyFn,
84566     /**
84567      * @hide
84568      * Overridden and disabled. A DDTarget does not support being dragged.
84569      * @method
84570      */
84571     isValidHandleChild: Ext.emptyFn,
84572     /**
84573      * @hide
84574      * Overridden and disabled. A DDTarget does not support being dragged.
84575      * @method
84576      */
84577     startDrag: Ext.emptyFn,
84578     /**
84579      * @hide
84580      * Overridden and disabled. A DDTarget does not support being dragged.
84581      * @method
84582      */
84583     endDrag: Ext.emptyFn,
84584     /**
84585      * @hide
84586      * Overridden and disabled. A DDTarget does not support being dragged.
84587      * @method
84588      */
84589     onDrag: Ext.emptyFn,
84590     /**
84591      * @hide
84592      * Overridden and disabled. A DDTarget does not support being dragged.
84593      * @method
84594      */
84595     onDragDrop: Ext.emptyFn,
84596     /**
84597      * @hide
84598      * Overridden and disabled. A DDTarget does not support being dragged.
84599      * @method
84600      */
84601     onDragEnter: Ext.emptyFn,
84602     /**
84603      * @hide
84604      * Overridden and disabled. A DDTarget does not support being dragged.
84605      * @method
84606      */
84607     onDragOut: Ext.emptyFn,
84608     /**
84609      * @hide
84610      * Overridden and disabled. A DDTarget does not support being dragged.
84611      * @method
84612      */
84613     onDragOver: Ext.emptyFn,
84614     /**
84615      * @hide
84616      * Overridden and disabled. A DDTarget does not support being dragged.
84617      * @method
84618      */
84619     onInvalidDrop: Ext.emptyFn,
84620     /**
84621      * @hide
84622      * Overridden and disabled. A DDTarget does not support being dragged.
84623      * @method
84624      */
84625     onMouseDown: Ext.emptyFn,
84626     /**
84627      * @hide
84628      * Overridden and disabled. A DDTarget does not support being dragged.
84629      * @method
84630      */
84631     onMouseUp: Ext.emptyFn,
84632     /**
84633      * @hide
84634      * Overridden and disabled. A DDTarget does not support being dragged.
84635      * @method
84636      */
84637     setXConstraint: Ext.emptyFn,
84638     /**
84639      * @hide
84640      * Overridden and disabled. A DDTarget does not support being dragged.
84641      * @method
84642      */
84643     setYConstraint: Ext.emptyFn,
84644     /**
84645      * @hide
84646      * Overridden and disabled. A DDTarget does not support being dragged.
84647      * @method
84648      */
84649     resetConstraints: Ext.emptyFn,
84650     /**
84651      * @hide
84652      * Overridden and disabled. A DDTarget does not support being dragged.
84653      * @method
84654      */
84655     clearConstraints: Ext.emptyFn,
84656     /**
84657      * @hide
84658      * Overridden and disabled. A DDTarget does not support being dragged.
84659      * @method
84660      */
84661     clearTicks: Ext.emptyFn,
84662     /**
84663      * @hide
84664      * Overridden and disabled. A DDTarget does not support being dragged.
84665      * @method
84666      */
84667     setInitPosition: Ext.emptyFn,
84668     /**
84669      * @hide
84670      * Overridden and disabled. A DDTarget does not support being dragged.
84671      * @method
84672      */
84673     setDragElId: Ext.emptyFn,
84674     /**
84675      * @hide
84676      * Overridden and disabled. A DDTarget does not support being dragged.
84677      * @method
84678      */
84679     setHandleElId: Ext.emptyFn,
84680     /**
84681      * @hide
84682      * Overridden and disabled. A DDTarget does not support being dragged.
84683      * @method
84684      */
84685     setOuterHandleElId: Ext.emptyFn,
84686     /**
84687      * @hide
84688      * Overridden and disabled. A DDTarget does not support being dragged.
84689      * @method
84690      */
84691     addInvalidHandleClass: Ext.emptyFn,
84692     /**
84693      * @hide
84694      * Overridden and disabled. A DDTarget does not support being dragged.
84695      * @method
84696      */
84697     addInvalidHandleId: Ext.emptyFn,
84698     /**
84699      * @hide
84700      * Overridden and disabled. A DDTarget does not support being dragged.
84701      * @method
84702      */
84703     addInvalidHandleType: Ext.emptyFn,
84704     /**
84705      * @hide
84706      * Overridden and disabled. A DDTarget does not support being dragged.
84707      * @method
84708      */
84709     removeInvalidHandleClass: Ext.emptyFn,
84710     /**
84711      * @hide
84712      * Overridden and disabled. A DDTarget does not support being dragged.
84713      * @method
84714      */
84715     removeInvalidHandleId: Ext.emptyFn,
84716     /**
84717      * @hide
84718      * Overridden and disabled. A DDTarget does not support being dragged.
84719      * @method
84720      */
84721     removeInvalidHandleType: Ext.emptyFn,
84722
84723     toString: function() {
84724         return ("DDTarget " + this.id);
84725     }
84726 });
84727 /**
84728  * @class Ext.dd.DragTracker
84729  * A DragTracker listens for drag events on an Element and fires events at the start and end of the drag,
84730  * as well as during the drag. This is useful for components such as {@link Ext.slider.Multi}, where there is
84731  * an element that can be dragged around to change the Slider's value.
84732  * DragTracker provides a series of template methods that should be overridden to provide functionality
84733  * in response to detected drag operations. These are onBeforeStart, onStart, onDrag and onEnd.
84734  * See {@link Ext.slider.Multi}'s initEvents function for an example implementation.
84735  */
84736 Ext.define('Ext.dd.DragTracker', {
84737
84738     uses: ['Ext.util.Region'],
84739
84740     mixins: {
84741         observable: 'Ext.util.Observable'
84742     },
84743
84744     /**
84745      * @property active
84746      * @type Boolean
84747      * Read-only property indicated whether the user is currently dragging this
84748      * tracker.
84749      */
84750     active: false,
84751
84752     /**
84753      * @property dragTarget
84754      * @type HtmlElement
84755      * <p><b>Only valid during drag operations. Read-only.</b></p>
84756      * <p>The element being dragged.</p>
84757      * <p>If the {@link #delegate} option is used, this will be the delegate element which was mousedowned.</p>
84758      */
84759
84760     /**
84761      * @cfg {Boolean} trackOver
84762      * <p>Defaults to <code>false</code>. Set to true to fire mouseover and mouseout events when the mouse enters or leaves the target element.</p>
84763      * <p>This is implicitly set when an {@link #overCls} is specified.</p>
84764      * <b>If the {@link #delegate} option is used, these events fire only when a delegate element is entered of left.</b>.
84765      */
84766     trackOver: false,
84767
84768     /**
84769      * @cfg {String} overCls
84770      * <p>A CSS class to add to the DragTracker's target element when the element (or, if the {@link #delegate} option is used,
84771      * when a delegate element) is mouseovered.</p>
84772      * <b>If the {@link #delegate} option is used, these events fire only when a delegate element is entered of left.</b>.
84773      */
84774
84775     /**
84776      * @cfg {Ext.util.Region/Element} constrainTo
84777      * <p>A {@link Ext.util.Region Region} (Or an element from which a Region measurement will be read) which is used to constrain
84778      * the result of the {@link #getOffset} call.</p>
84779      * <p>This may be set any time during the DragTracker's lifecycle to set a dynamic constraining region.</p>
84780      */
84781
84782     /**
84783      * @cfg {Number} tolerance
84784      * Number of pixels the drag target must be moved before dragging is
84785      * considered to have started. Defaults to <code>5</code>.
84786      */
84787     tolerance: 5,
84788
84789     /**
84790      * @cfg {Boolean/Number} autoStart
84791      * Defaults to <code>false</code>. Specify <code>true</code> to defer trigger start by 1000 ms.
84792      * Specify a Number for the number of milliseconds to defer trigger start.
84793      */
84794     autoStart: false,
84795
84796     /**
84797      * @cfg {String} delegate
84798      * Optional. <p>A {@link Ext.DomQuery DomQuery} selector which identifies child elements within the DragTracker's encapsulating
84799      * Element which are the tracked elements. This limits tracking to only begin when the matching elements are mousedowned.</p>
84800      * <p>This may also be a specific child element within the DragTracker's encapsulating element to use as the tracked element.</p>
84801      */
84802
84803     /**
84804      * @cfg {Boolean} preventDefault
84805      * Specify <code>false</code> to enable default actions on onMouseDown events. Defaults to <code>true</code>.
84806      */
84807
84808     /**
84809      * @cfg {Boolean} stopEvent
84810      * Specify <code>true</code> to stop the <code>mousedown</code> event from bubbling to outer listeners from the target element (or its delegates). Defaults to <code>false</code>.
84811      */
84812
84813     constructor : function(config){
84814         Ext.apply(this, config);
84815         this.addEvents(
84816             /**
84817              * @event mouseover <p><b>Only available when {@link #trackOver} is <code>true</code></b></p>
84818              * <p>Fires when the mouse enters the DragTracker's target element (or if {@link #delegate} is
84819              * used, when the mouse enters a delegate element).</p>
84820              * @param {Object} this
84821              * @param {Object} e event object
84822              * @param {HtmlElement} target The element mouseovered.
84823              */
84824             'mouseover',
84825
84826             /**
84827              * @event mouseout <p><b>Only available when {@link #trackOver} is <code>true</code></b></p>
84828              * <p>Fires when the mouse exits the DragTracker's target element (or if {@link #delegate} is
84829              * used, when the mouse exits a delegate element).</p>
84830              * @param {Object} this
84831              * @param {Object} e event object
84832              */
84833             'mouseout',
84834
84835             /**
84836              * @event mousedown <p>Fires when the mouse button is pressed down, but before a drag operation begins. The
84837              * drag operation begins after either the mouse has been moved by {@link #tolerance} pixels, or after
84838              * the {@link #autoStart} timer fires.</p>
84839              * <p>Return false to veto the drag operation.</p>
84840              * @param {Object} this
84841              * @param {Object} e event object
84842              */
84843             'mousedown',
84844
84845             /**
84846              * @event mouseup
84847              * @param {Object} this
84848              * @param {Object} e event object
84849              */
84850             'mouseup',
84851
84852             /**
84853              * @event mousemove Fired when the mouse is moved. Returning false cancels the drag operation.
84854              * @param {Object} this
84855              * @param {Object} e event object
84856              */
84857             'mousemove',
84858
84859             /**
84860              * @event dragstart
84861              * @param {Object} this
84862              * @param {Object} e event object
84863              */
84864             'dragstart',
84865
84866             /**
84867              * @event dragend
84868              * @param {Object} this
84869              * @param {Object} e event object
84870              */
84871             'dragend',
84872
84873             /**
84874              * @event drag
84875              * @param {Object} this
84876              * @param {Object} e event object
84877              */
84878             'drag'
84879         );
84880
84881         this.dragRegion = Ext.create('Ext.util.Region', 0,0,0,0);
84882
84883         if (this.el) {
84884             this.initEl(this.el);
84885         }
84886
84887         // Dont pass the config so that it is not applied to 'this' again
84888         this.mixins.observable.constructor.call(this);
84889         if (this.disabled) {
84890             this.disable();
84891         }
84892
84893     },
84894
84895     /**
84896      * Initializes the DragTracker on a given element.
84897      * @param {Ext.core.Element/HTMLElement} el The element
84898      */
84899     initEl: function(el) {
84900         this.el = Ext.get(el);
84901
84902         // The delegate option may also be an element on which to listen
84903         this.handle = Ext.get(this.delegate);
84904
84905         // If delegate specified an actual element to listen on, we do not use the delegate listener option
84906         this.delegate = this.handle ? undefined : this.delegate;
84907
84908         if (!this.handle) {
84909             this.handle = this.el;
84910         }
84911
84912         // Add a mousedown listener which reacts only on the elements targeted by the delegate config.
84913         // We process mousedown to begin tracking.
84914         this.mon(this.handle, {
84915             mousedown: this.onMouseDown,
84916             delegate: this.delegate,
84917             scope: this
84918         });
84919
84920         // If configured to do so, track mouse entry and exit into the target (or delegate).
84921         // The mouseover and mouseout CANNOT be replaced with mouseenter and mouseleave
84922         // because delegate cannot work with those pseudoevents. Entry/exit checking is done in the handler.
84923         if (this.trackOver || this.overCls) {
84924             this.mon(this.handle, {
84925                 mouseover: this.onMouseOver,
84926                 mouseout: this.onMouseOut,
84927                 delegate: this.delegate,
84928                 scope: this
84929             });
84930         }
84931     },
84932
84933     disable: function() {
84934         this.disabled = true;
84935     },
84936
84937     enable: function() {
84938         this.disabled = false;
84939     },
84940
84941     destroy : function() {
84942         this.clearListeners();
84943         delete this.el;
84944     },
84945
84946     // When the pointer enters a tracking element, fire a mouseover if the mouse entered from outside.
84947     // This is mouseenter functionality, but we cannot use mouseenter because we are using "delegate" to filter mouse targets
84948     onMouseOver: function(e, target) {
84949         var me = this;
84950         if (!me.disabled) {
84951             if (Ext.EventManager.contains(e) || me.delegate) {
84952                 me.mouseIsOut = false;
84953                 if (me.overCls) {
84954                     me.el.addCls(me.overCls);
84955                 }
84956                 me.fireEvent('mouseover', me, e, me.delegate ? e.getTarget(me.delegate, target) : me.handle);
84957             }
84958         }
84959     },
84960
84961     // When the pointer exits a tracking element, fire a mouseout.
84962     // This is mouseleave functionality, but we cannot use mouseleave because we are using "delegate" to filter mouse targets
84963     onMouseOut: function(e) {
84964         if (this.mouseIsDown) {
84965             this.mouseIsOut = true;
84966         } else {
84967             if (this.overCls) {
84968                 this.el.removeCls(this.overCls);
84969             }
84970             this.fireEvent('mouseout', this, e);
84971         }
84972     },
84973
84974     onMouseDown: function(e, target){
84975         // If this is disabled, or the mousedown has been processed by an upstream DragTracker, return
84976         if (this.disabled ||e.dragTracked) {
84977             return;
84978         }
84979
84980         // This information should be available in mousedown listener and onBeforeStart implementations
84981         this.dragTarget = this.delegate ? target : this.handle.dom;
84982         this.startXY = this.lastXY = e.getXY();
84983         this.startRegion = Ext.fly(this.dragTarget).getRegion();
84984
84985         if (this.fireEvent('mousedown', this, e) !== false && this.onBeforeStart(e) !== false) {
84986
84987             // Track when the mouse is down so that mouseouts while the mouse is down are not processed.
84988             // The onMouseOut method will only ever be called after mouseup.
84989             this.mouseIsDown = true;
84990
84991             // Flag for downstream DragTracker instances that the mouse is being tracked.
84992             e.dragTracked = true;
84993
84994             if (this.preventDefault !== false) {
84995                 e.preventDefault();
84996             }
84997             Ext.getDoc().on({
84998                 scope: this,
84999                 mouseup: this.onMouseUp,
85000                 mousemove: this.onMouseMove,
85001                 selectstart: this.stopSelect
85002             });
85003             if (this.autoStart) {
85004                 this.timer =  Ext.defer(this.triggerStart, this.autoStart === true ? 1000 : this.autoStart, this, [e]);
85005             }
85006         }
85007     },
85008
85009     onMouseMove: function(e, target){
85010         // BrowserBug: IE hack to see if button was released outside of window.
85011         // Needed in IE6-9 in quirks and strictmode
85012         if (this.active && Ext.isIE && !e.browserEvent.button) {
85013             e.preventDefault();
85014             this.onMouseUp(e);
85015             return;
85016         }
85017
85018         e.preventDefault();
85019         var xy = e.getXY(),
85020             s = this.startXY;
85021
85022         this.lastXY = xy;
85023         if (!this.active) {
85024             if (Math.max(Math.abs(s[0]-xy[0]), Math.abs(s[1]-xy[1])) > this.tolerance) {
85025                 this.triggerStart(e);
85026             } else {
85027                 return;
85028             }
85029         }
85030
85031         // Returning false from a mousemove listener deactivates 
85032         if (this.fireEvent('mousemove', this, e) === false) {
85033             this.onMouseUp(e);
85034         } else {
85035             this.onDrag(e);
85036             this.fireEvent('drag', this, e);
85037         }
85038     },
85039
85040     onMouseUp: function(e) {
85041         // Clear the flag which ensures onMouseOut fires only after the mouse button
85042         // is lifted if the mouseout happens *during* a drag.
85043         this.mouseIsDown = false;
85044
85045         // Remove flag from event singleton
85046         delete e.dragTracked;
85047
85048         // If we mouseouted the el *during* the drag, the onMouseOut method will not have fired. Ensure that it gets processed.
85049         if (this.mouseIsOut) {
85050             this.mouseIsOut = false;
85051             this.onMouseOut(e);
85052         }
85053         e.preventDefault();
85054         this.fireEvent('mouseup', this, e);
85055         this.endDrag(e);
85056     },
85057
85058     /**
85059      * @private
85060      * Stop the drag operation, and remove active mouse listeners.
85061      */
85062     endDrag: function(e) {
85063         var doc = Ext.getDoc(),
85064         wasActive = this.active;
85065
85066         doc.un('mousemove', this.onMouseMove, this);
85067         doc.un('mouseup', this.onMouseUp, this);
85068         doc.un('selectstart', this.stopSelect, this);
85069         this.clearStart();
85070         this.active = false;
85071         if (wasActive) {
85072             this.onEnd(e);
85073             this.fireEvent('dragend', this, e);
85074         }
85075         // Private property calculated when first required and only cached during a drag
85076         delete this._constrainRegion;
85077     },
85078
85079     triggerStart: function(e) {
85080         this.clearStart();
85081         this.active = true;
85082         this.onStart(e);
85083         this.fireEvent('dragstart', this, e);
85084     },
85085
85086     clearStart : function() {
85087         if (this.timer) {
85088             clearTimeout(this.timer);
85089             delete this.timer;
85090         }
85091     },
85092
85093     stopSelect : function(e) {
85094         e.stopEvent();
85095         return false;
85096     },
85097
85098     /**
85099      * Template method which should be overridden by each DragTracker instance. Called when the user first clicks and
85100      * holds the mouse button down. Return false to disallow the drag
85101      * @param {Ext.EventObject} e The event object
85102      */
85103     onBeforeStart : function(e) {
85104
85105     },
85106
85107     /**
85108      * Template method which should be overridden by each DragTracker instance. Called when a drag operation starts
85109      * (e.g. the user has moved the tracked element beyond the specified tolerance)
85110      * @param {Ext.EventObject} e The event object
85111      */
85112     onStart : function(xy) {
85113
85114     },
85115
85116     /**
85117      * Template method which should be overridden by each DragTracker instance. Called whenever a drag has been detected.
85118      * @param {Ext.EventObject} e The event object
85119      */
85120     onDrag : function(e) {
85121
85122     },
85123
85124     /**
85125      * Template method which should be overridden by each DragTracker instance. Called when a drag operation has been completed
85126      * (e.g. the user clicked and held the mouse down, dragged the element and then released the mouse button)
85127      * @param {Ext.EventObject} e The event object
85128      */
85129     onEnd : function(e) {
85130
85131     },
85132
85133     /**
85134      * </p>Returns the drag target. This is usually the DragTracker's encapsulating element.</p>
85135      * <p>If the {@link #delegate} option is being used, this may be a child element which matches the
85136      * {@link #delegate} selector.</p>
85137      * @return {Ext.core.Element} The element currently being tracked.
85138      */
85139     getDragTarget : function(){
85140         return this.dragTarget;
85141     },
85142
85143     /**
85144      * @private
85145      * @returns {Element} The DragTracker's encapsulating element.
85146      */
85147     getDragCt : function(){
85148         return this.el;
85149     },
85150
85151     /**
85152      * @private
85153      * Return the Region into which the drag operation is constrained.
85154      * Either the XY pointer itself can be constrained, or the dragTarget element
85155      * The private property _constrainRegion is cached until onMouseUp
85156      */
85157     getConstrainRegion: function() {
85158         if (this.constrainTo) {
85159             if (this.constrainTo instanceof Ext.util.Region) {
85160                 return this.constrainTo;
85161             }
85162             if (!this._constrainRegion) {
85163                 this._constrainRegion = Ext.fly(this.constrainTo).getViewRegion();
85164             }
85165         } else {
85166             if (!this._constrainRegion) {
85167                 this._constrainRegion = this.getDragCt().getViewRegion();
85168             }
85169         }
85170         return this._constrainRegion;
85171     },
85172
85173     getXY : function(constrain){
85174         return constrain ? this.constrainModes[constrain].call(this, this.lastXY) : this.lastXY;
85175     },
85176
85177     /**
85178      * <p>Returns the X, Y offset of the current mouse position from the mousedown point.</p>
85179      * <p>This method may optionally constrain the real offset values, and returns a point coerced in one
85180      * of two modes:</p><ul>
85181      * <li><code>point</code><div class="sub-desc">The current mouse position is coerced into the
85182      * {@link #constrainRegion}, and the resulting position is returned.</div></li>
85183      * <li><code>dragTarget</code><div class="sub-desc">The new {@link Ext.util.Region Region} of the
85184      * {@link #getDragTarget dragTarget} is calculated based upon the current mouse position, and then
85185      * coerced into the {@link #constrainRegion}. The returned mouse position is then adjusted by the
85186      * same delta as was used to coerce the region.</div></li>
85187      * </ul>
85188      * @param constrainMode {String} Optional. If omitted the true mouse position is returned. May be passed
85189      * as <code>'point'</code> or <code>'dragTarget'. See above.</code>.
85190      * @returns {Array} The <code>X, Y</code> offset from the mousedown point, optionally constrained.
85191      */
85192     getOffset : function(constrain){
85193         var xy = this.getXY(constrain),
85194             s = this.startXY;
85195
85196         return [xy[0]-s[0], xy[1]-s[1]];
85197     },
85198
85199     constrainModes: {
85200         // Constrain the passed point to within the constrain region
85201         point: function(xy) {
85202             var dr = this.dragRegion,
85203                 constrainTo = this.getConstrainRegion();
85204
85205             // No constraint
85206             if (!constrainTo) {
85207                 return xy;
85208             }
85209
85210             dr.x = dr.left = dr[0] = dr.right = xy[0];
85211             dr.y = dr.top = dr[1] = dr.bottom = xy[1];
85212             dr.constrainTo(constrainTo);
85213
85214             return [dr.left, dr.top];
85215         },
85216
85217         // Constrain the dragTarget to within the constrain region. Return the passed xy adjusted by the same delta.
85218         dragTarget: function(xy) {
85219             var s = this.startXY,
85220                 dr = this.startRegion.copy(),
85221                 constrainTo = this.getConstrainRegion(),
85222                 adjust;
85223
85224             // No constraint
85225             if (!constrainTo) {
85226                 return xy;
85227             }
85228
85229             // See where the passed XY would put the dragTarget if translated by the unconstrained offset.
85230             // If it overflows, we constrain the passed XY to bring the potential
85231             // region back within the boundary.
85232             dr.translateBy.apply(dr, [xy[0]-s[0], xy[1]-s[1]]);
85233
85234             // Constrain the X coordinate by however much the dragTarget overflows
85235             if (dr.right > constrainTo.right) {
85236                 xy[0] += adjust = (constrainTo.right - dr.right);    // overflowed the right
85237                 dr.left += adjust;
85238             }
85239             if (dr.left < constrainTo.left) {
85240                 xy[0] += (constrainTo.left - dr.left);      // overflowed the left
85241             }
85242
85243             // Constrain the X coordinate by however much the dragTarget overflows
85244             if (dr.bottom > constrainTo.bottom) {
85245                 xy[1] += adjust = (constrainTo.bottom - dr.bottom);  // overflowed the bottom
85246                 dr.top += adjust;
85247             }
85248             if (dr.top < constrainTo.top) {
85249                 xy[1] += (constrainTo.top - dr.top);        // overflowed the top
85250             }
85251             return xy;
85252         }
85253     }
85254 });
85255 /**
85256  * @class Ext.dd.DragZone
85257  * @extends Ext.dd.DragSource
85258  * <p>This class provides a container DD instance that allows dragging of multiple child source nodes.</p>
85259  * <p>This class does not move the drag target nodes, but a proxy element which may contain
85260  * any DOM structure you wish. The DOM element to show in the proxy is provided by either a
85261  * provided implementation of {@link #getDragData}, or by registered draggables registered with {@link Ext.dd.Registry}</p>
85262  * <p>If you wish to provide draggability for an arbitrary number of DOM nodes, each of which represent some
85263  * application object (For example nodes in a {@link Ext.view.View DataView}) then use of this class
85264  * is the most efficient way to "activate" those nodes.</p>
85265  * <p>By default, this class requires that draggable child nodes are registered with {@link Ext.dd.Registry}.
85266  * However a simpler way to allow a DragZone to manage any number of draggable elements is to configure
85267  * the DragZone with  an implementation of the {@link #getDragData} method which interrogates the passed
85268  * mouse event to see if it has taken place within an element, or class of elements. This is easily done
85269  * by using the event's {@link Ext.EventObject#getTarget getTarget} method to identify a node based on a
85270  * {@link Ext.DomQuery} selector. For example, to make the nodes of a DataView draggable, use the following
85271  * technique. Knowledge of the use of the DataView is required:</p><pre><code>
85272 myDataView.on('render', function(v) {
85273     myDataView.dragZone = new Ext.dd.DragZone(v.getEl(), {
85274
85275 //      On receipt of a mousedown event, see if it is within a DataView node.
85276 //      Return a drag data object if so.
85277         getDragData: function(e) {
85278
85279 //          Use the DataView's own itemSelector (a mandatory property) to
85280 //          test if the mousedown is within one of the DataView's nodes.
85281             var sourceEl = e.getTarget(v.itemSelector, 10);
85282
85283 //          If the mousedown is within a DataView node, clone the node to produce
85284 //          a ddel element for use by the drag proxy. Also add application data
85285 //          to the returned data object.
85286             if (sourceEl) {
85287                 d = sourceEl.cloneNode(true);
85288                 d.id = Ext.id();
85289                 return {
85290                     ddel: d,
85291                     sourceEl: sourceEl,
85292                     repairXY: Ext.fly(sourceEl).getXY(),
85293                     sourceStore: v.store,
85294                     draggedRecord: v.{@link Ext.view.View#getRecord getRecord}(sourceEl)
85295                 }
85296             }
85297         },
85298
85299 //      Provide coordinates for the proxy to slide back to on failed drag.
85300 //      This is the original XY coordinates of the draggable element captured
85301 //      in the getDragData method.
85302         getRepairXY: function() {
85303             return this.dragData.repairXY;
85304         }
85305     });
85306 });</code></pre>
85307  * See the {@link Ext.dd.DropZone DropZone} documentation for details about building a DropZone which
85308  * cooperates with this DragZone.
85309  * @constructor
85310  * @param {Mixed} el The container element
85311  * @param {Object} config
85312  */
85313 Ext.define('Ext.dd.DragZone', {
85314
85315     extend: 'Ext.dd.DragSource',
85316
85317     constructor : function(el, config){
85318         this.callParent([el, config]);
85319         if (this.containerScroll) {
85320             Ext.dd.ScrollManager.register(this.el);
85321         }
85322     },
85323
85324     /**
85325      * This property contains the data representing the dragged object. This data is set up by the implementation
85326      * of the {@link #getDragData} method. It must contain a <tt>ddel</tt> property, but can contain
85327      * any other data according to the application's needs.
85328      * @type Object
85329      * @property dragData
85330      */
85331
85332     /**
85333      * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
85334      * for auto scrolling during drag operations.
85335      */
85336
85337     /**
85338      * Called when a mousedown occurs in this container. Looks in {@link Ext.dd.Registry}
85339      * for a valid target to drag based on the mouse down. Override this method
85340      * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
85341      * object has a "ddel" attribute (with an HTML Element) for other functions to work.
85342      * @param {EventObject} e The mouse down event
85343      * @return {Object} The dragData
85344      */
85345     getDragData : function(e){
85346         return Ext.dd.Registry.getHandleFromEvent(e);
85347     },
85348
85349     /**
85350      * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
85351      * this.dragData.ddel
85352      * @param {Number} x The x position of the click on the dragged object
85353      * @param {Number} y The y position of the click on the dragged object
85354      * @return {Boolean} true to continue the drag, false to cancel
85355      */
85356     onInitDrag : function(x, y){
85357         this.proxy.update(this.dragData.ddel.cloneNode(true));
85358         this.onStartDrag(x, y);
85359         return true;
85360     },
85361
85362     /**
85363      * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
85364      */
85365     afterRepair : function(){
85366         var me = this;
85367         if (Ext.enableFx) {
85368             Ext.fly(me.dragData.ddel).highlight(me.repairHighlightColor);
85369         }
85370         me.dragging = false;
85371     },
85372
85373     /**
85374      * Called before a repair of an invalid drop to get the XY to animate to. By default returns
85375      * the XY of this.dragData.ddel
85376      * @param {EventObject} e The mouse up event
85377      * @return {Array} The xy location (e.g. [100, 200])
85378      */
85379     getRepairXY : function(e){
85380         return Ext.core.Element.fly(this.dragData.ddel).getXY();
85381     },
85382
85383     destroy : function(){
85384         this.callParent();
85385         if (this.containerScroll) {
85386             Ext.dd.ScrollManager.unregister(this.el);
85387         }
85388     }
85389 });
85390
85391 /**
85392  * @class Ext.dd.ScrollManager
85393  * <p>Provides automatic scrolling of overflow regions in the page during drag operations.</p>
85394  * <p>The ScrollManager configs will be used as the defaults for any scroll container registered with it,
85395  * but you can also override most of the configs per scroll container by adding a
85396  * <tt>ddScrollConfig</tt> object to the target element that contains these properties: {@link #hthresh},
85397  * {@link #vthresh}, {@link #increment} and {@link #frequency}.  Example usage:
85398  * <pre><code>
85399 var el = Ext.get('scroll-ct');
85400 el.ddScrollConfig = {
85401     vthresh: 50,
85402     hthresh: -1,
85403     frequency: 100,
85404     increment: 200
85405 };
85406 Ext.dd.ScrollManager.register(el);
85407 </code></pre>
85408  * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
85409  * @singleton
85410  */
85411 Ext.define('Ext.dd.ScrollManager', {
85412     singleton: true,
85413     requires: [
85414         'Ext.dd.DragDropManager'
85415     ],
85416
85417     constructor: function() {
85418         var ddm = Ext.dd.DragDropManager;
85419         ddm.fireEvents = Ext.Function.createSequence(ddm.fireEvents, this.onFire, this);
85420         ddm.stopDrag = Ext.Function.createSequence(ddm.stopDrag, this.onStop, this);
85421         this.doScroll = Ext.Function.bind(this.doScroll, this);
85422         this.ddmInstance = ddm;
85423         this.els = {};
85424         this.dragEl = null;
85425         this.proc = {};
85426     },
85427
85428     onStop: function(e){
85429         var sm = Ext.dd.ScrollManager;
85430         sm.dragEl = null;
85431         sm.clearProc();
85432     },
85433
85434     triggerRefresh: function() {
85435         if (this.ddmInstance.dragCurrent) {
85436             this.ddmInstance.refreshCache(this.ddmInstance.dragCurrent.groups);
85437         }
85438     },
85439
85440     doScroll: function() {
85441         if (this.ddmInstance.dragCurrent) {
85442             var proc   = this.proc,
85443                 procEl = proc.el,
85444                 ddScrollConfig = proc.el.ddScrollConfig,
85445                 inc = ddScrollConfig ? ddScrollConfig.increment : this.increment;
85446
85447             if (!this.animate) {
85448                 if (procEl.scroll(proc.dir, inc)) {
85449                     this.triggerRefresh();
85450                 }
85451             } else {
85452                 procEl.scroll(proc.dir, inc, true, this.animDuration, this.triggerRefresh);
85453             }
85454         }
85455     },
85456
85457     clearProc: function() {
85458         var proc = this.proc;
85459         if (proc.id) {
85460             clearInterval(proc.id);
85461         }
85462         proc.id = 0;
85463         proc.el = null;
85464         proc.dir = "";
85465     },
85466
85467     startProc: function(el, dir) {
85468         this.clearProc();
85469         this.proc.el = el;
85470         this.proc.dir = dir;
85471         var group = el.ddScrollConfig ? el.ddScrollConfig.ddGroup : undefined,
85472             freq  = (el.ddScrollConfig && el.ddScrollConfig.frequency)
85473                   ? el.ddScrollConfig.frequency
85474                   : this.frequency;
85475
85476         if (group === undefined || this.ddmInstance.dragCurrent.ddGroup == group) {
85477             this.proc.id = setInterval(this.doScroll, freq);
85478         }
85479     },
85480
85481     onFire: function(e, isDrop) {
85482         if (isDrop || !this.ddmInstance.dragCurrent) {
85483             return;
85484         }
85485         if (!this.dragEl || this.dragEl != this.ddmInstance.dragCurrent) {
85486             this.dragEl = this.ddmInstance.dragCurrent;
85487             // refresh regions on drag start
85488             this.refreshCache();
85489         }
85490
85491         var xy = e.getXY(),
85492             pt = e.getPoint(),
85493             proc = this.proc,
85494             els = this.els;
85495
85496         for (var id in els) {
85497             var el = els[id], r = el._region;
85498             var c = el.ddScrollConfig ? el.ddScrollConfig : this;
85499             if (r && r.contains(pt) && el.isScrollable()) {
85500                 if (r.bottom - pt.y <= c.vthresh) {
85501                     if(proc.el != el){
85502                         this.startProc(el, "down");
85503                     }
85504                     return;
85505                 }else if (r.right - pt.x <= c.hthresh) {
85506                     if (proc.el != el) {
85507                         this.startProc(el, "left");
85508                     }
85509                     return;
85510                 } else if(pt.y - r.top <= c.vthresh) {
85511                     if (proc.el != el) {
85512                         this.startProc(el, "up");
85513                     }
85514                     return;
85515                 } else if(pt.x - r.left <= c.hthresh) {
85516                     if (proc.el != el) {
85517                         this.startProc(el, "right");
85518                     }
85519                     return;
85520                 }
85521             }
85522         }
85523         this.clearProc();
85524     },
85525
85526     /**
85527      * Registers new overflow element(s) to auto scroll
85528      * @param {Mixed/Array} el The id of or the element to be scrolled or an array of either
85529      */
85530     register : function(el){
85531         if (Ext.isArray(el)) {
85532             for(var i = 0, len = el.length; i < len; i++) {
85533                     this.register(el[i]);
85534             }
85535         } else {
85536             el = Ext.get(el);
85537             this.els[el.id] = el;
85538         }
85539     },
85540
85541     /**
85542      * Unregisters overflow element(s) so they are no longer scrolled
85543      * @param {Mixed/Array} el The id of or the element to be removed or an array of either
85544      */
85545     unregister : function(el){
85546         if(Ext.isArray(el)){
85547             for (var i = 0, len = el.length; i < len; i++) {
85548                 this.unregister(el[i]);
85549             }
85550         }else{
85551             el = Ext.get(el);
85552             delete this.els[el.id];
85553         }
85554     },
85555
85556     /**
85557      * The number of pixels from the top or bottom edge of a container the pointer needs to be to
85558      * trigger scrolling (defaults to 25)
85559      * @type Number
85560      */
85561     vthresh : 25,
85562     /**
85563      * The number of pixels from the right or left edge of a container the pointer needs to be to
85564      * trigger scrolling (defaults to 25)
85565      * @type Number
85566      */
85567     hthresh : 25,
85568
85569     /**
85570      * The number of pixels to scroll in each scroll increment (defaults to 100)
85571      * @type Number
85572      */
85573     increment : 100,
85574
85575     /**
85576      * The frequency of scrolls in milliseconds (defaults to 500)
85577      * @type Number
85578      */
85579     frequency : 500,
85580
85581     /**
85582      * True to animate the scroll (defaults to true)
85583      * @type Boolean
85584      */
85585     animate: true,
85586
85587     /**
85588      * The animation duration in seconds -
85589      * MUST BE less than Ext.dd.ScrollManager.frequency! (defaults to .4)
85590      * @type Number
85591      */
85592     animDuration: 0.4,
85593
85594     /**
85595      * The named drag drop {@link Ext.dd.DragSource#ddGroup group} to which this container belongs (defaults to undefined).
85596      * If a ddGroup is specified, then container scrolling will only occur when a dragged object is in the same ddGroup.
85597      * @type String
85598      */
85599     ddGroup: undefined,
85600
85601     /**
85602      * Manually trigger a cache refresh.
85603      */
85604     refreshCache : function(){
85605         var els = this.els,
85606             id;
85607         for (id in els) {
85608             if(typeof els[id] == 'object'){ // for people extending the object prototype
85609                 els[id]._region = els[id].getRegion();
85610             }
85611         }
85612     }
85613 });
85614
85615 /**
85616  * @class Ext.dd.DropTarget
85617  * @extends Ext.dd.DDTarget
85618  * A simple class that provides the basic implementation needed to make any element a drop target that can have
85619  * draggable items dropped onto it.  The drop has no effect until an implementation of notifyDrop is provided.
85620  * @constructor
85621  * @param {Mixed} el The container element
85622  * @param {Object} config
85623  */
85624 Ext.define('Ext.dd.DropTarget', {
85625     extend: 'Ext.dd.DDTarget',
85626     requires: ['Ext.dd.ScrollManager'],
85627
85628     constructor : function(el, config){
85629         this.el = Ext.get(el);
85630
85631         Ext.apply(this, config);
85632
85633         if(this.containerScroll){
85634             Ext.dd.ScrollManager.register(this.el);
85635         }
85636
85637         this.callParent([this.el.dom, this.ddGroup || this.group,
85638               {isTarget: true}]);
85639     },
85640
85641     /**
85642      * @cfg {String} ddGroup
85643      * A named drag drop group to which this object belongs.  If a group is specified, then this object will only
85644      * interact with other drag drop objects in the same group (defaults to undefined).
85645      */
85646     /**
85647      * @cfg {String} overClass
85648      * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
85649      */
85650     /**
85651      * @cfg {String} dropAllowed
85652      * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
85653      */
85654     dropAllowed : Ext.baseCSSPrefix + 'dd-drop-ok',
85655     /**
85656      * @cfg {String} dropNotAllowed
85657      * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
85658      */
85659     dropNotAllowed : Ext.baseCSSPrefix + 'dd-drop-nodrop',
85660
85661     // private
85662     isTarget : true,
85663
85664     // private
85665     isNotifyTarget : true,
85666
85667     /**
85668      * The function a {@link Ext.dd.DragSource} calls once to notify this drop target that the source is now over the
85669      * target.  This default implementation adds the CSS class specified by overClass (if any) to the drop element
85670      * and returns the dropAllowed config value.  This method should be overridden if drop validation is required.
85671      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
85672      * @param {Event} e The event
85673      * @param {Object} data An object containing arbitrary data supplied by the drag source
85674      * @return {String} status The CSS class that communicates the drop status back to the source so that the
85675      * underlying {@link Ext.dd.StatusProxy} can be updated
85676      */
85677     notifyEnter : function(dd, e, data){
85678         if(this.overClass){
85679             this.el.addCls(this.overClass);
85680         }
85681         return this.dropAllowed;
85682     },
85683
85684     /**
85685      * The function a {@link Ext.dd.DragSource} calls continuously while it is being dragged over the target.
85686      * This method will be called on every mouse movement while the drag source is over the drop target.
85687      * This default implementation simply returns the dropAllowed config value.
85688      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
85689      * @param {Event} e The event
85690      * @param {Object} data An object containing arbitrary data supplied by the drag source
85691      * @return {String} status The CSS class that communicates the drop status back to the source so that the
85692      * underlying {@link Ext.dd.StatusProxy} can be updated
85693      */
85694     notifyOver : function(dd, e, data){
85695         return this.dropAllowed;
85696     },
85697
85698     /**
85699      * The function a {@link Ext.dd.DragSource} calls once to notify this drop target that the source has been dragged
85700      * out of the target without dropping.  This default implementation simply removes the CSS class specified by
85701      * overClass (if any) from the drop element.
85702      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
85703      * @param {Event} e The event
85704      * @param {Object} data An object containing arbitrary data supplied by the drag source
85705      */
85706     notifyOut : function(dd, e, data){
85707         if(this.overClass){
85708             this.el.removeCls(this.overClass);
85709         }
85710     },
85711
85712     /**
85713      * The function a {@link Ext.dd.DragSource} calls once to notify this drop target that the dragged item has
85714      * been dropped on it.  This method has no default implementation and returns false, so you must provide an
85715      * implementation that does something to process the drop event and returns true so that the drag source's
85716      * repair action does not run.
85717      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
85718      * @param {Event} e The event
85719      * @param {Object} data An object containing arbitrary data supplied by the drag source
85720      * @return {Boolean} False if the drop was invalid.
85721      */
85722     notifyDrop : function(dd, e, data){
85723         return false;
85724     },
85725
85726     destroy : function(){
85727         this.callParent();
85728         if(this.containerScroll){
85729             Ext.dd.ScrollManager.unregister(this.el);
85730         }
85731     }
85732 });
85733
85734 /**
85735  * @class Ext.dd.Registry
85736  * Provides easy access to all drag drop components that are registered on a page.  Items can be retrieved either
85737  * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
85738  * @singleton
85739  */
85740 Ext.define('Ext.dd.Registry', {
85741     singleton: true,
85742     constructor: function() {
85743         this.elements = {}; 
85744         this.handles = {}; 
85745         this.autoIdSeed = 0;
85746     },
85747     
85748     getId: function(el, autogen){
85749         if(typeof el == "string"){
85750             return el;
85751         }
85752         var id = el.id;
85753         if(!id && autogen !== false){
85754             id = "extdd-" + (++this.autoIdSeed);
85755             el.id = id;
85756         }
85757         return id;
85758     },
85759     
85760     /**
85761      * Resgister a drag drop element
85762      * @param {String/HTMLElement} element The id or DOM node to register
85763      * @param {Object} data (optional) An custom data object that will be passed between the elements that are involved
85764      * in drag drop operations.  You can populate this object with any arbitrary properties that your own code
85765      * knows how to interpret, plus there are some specific properties known to the Registry that should be
85766      * populated in the data object (if applicable):
85767      * <pre>
85768 Value      Description<br />
85769 ---------  ------------------------------------------<br />
85770 handles    Array of DOM nodes that trigger dragging<br />
85771            for the element being registered<br />
85772 isHandle   True if the element passed in triggers<br />
85773            dragging itself, else false
85774 </pre>
85775      */
85776     register : function(el, data){
85777         data = data || {};
85778         if (typeof el == "string") {
85779             el = document.getElementById(el);
85780         }
85781         data.ddel = el;
85782         this.elements[this.getId(el)] = data;
85783         if (data.isHandle !== false) {
85784             this.handles[data.ddel.id] = data;
85785         }
85786         if (data.handles) {
85787             var hs = data.handles;
85788             for (var i = 0, len = hs.length; i < len; i++) {
85789                 this.handles[this.getId(hs[i])] = data;
85790             }
85791         }
85792     },
85793
85794     /**
85795      * Unregister a drag drop element
85796      * @param {String/HTMLElement} element The id or DOM node to unregister
85797      */
85798     unregister : function(el){
85799         var id = this.getId(el, false);
85800         var data = this.elements[id];
85801         if(data){
85802             delete this.elements[id];
85803             if(data.handles){
85804                 var hs = data.handles;
85805                 for (var i = 0, len = hs.length; i < len; i++) {
85806                     delete this.handles[this.getId(hs[i], false)];
85807                 }
85808             }
85809         }
85810     },
85811
85812     /**
85813      * Returns the handle registered for a DOM Node by id
85814      * @param {String/HTMLElement} id The DOM node or id to look up
85815      * @return {Object} handle The custom handle data
85816      */
85817     getHandle : function(id){
85818         if(typeof id != "string"){ // must be element?
85819             id = id.id;
85820         }
85821         return this.handles[id];
85822     },
85823
85824     /**
85825      * Returns the handle that is registered for the DOM node that is the target of the event
85826      * @param {Event} e The event
85827      * @return {Object} handle The custom handle data
85828      */
85829     getHandleFromEvent : function(e){
85830         var t = e.getTarget();
85831         return t ? this.handles[t.id] : null;
85832     },
85833
85834     /**
85835      * Returns a custom data object that is registered for a DOM node by id
85836      * @param {String/HTMLElement} id The DOM node or id to look up
85837      * @return {Object} data The custom data
85838      */
85839     getTarget : function(id){
85840         if(typeof id != "string"){ // must be element?
85841             id = id.id;
85842         }
85843         return this.elements[id];
85844     },
85845
85846     /**
85847      * Returns a custom data object that is registered for the DOM node that is the target of the event
85848      * @param {Event} e The event
85849      * @return {Object} data The custom data
85850      */
85851     getTargetFromEvent : function(e){
85852         var t = e.getTarget();
85853         return t ? this.elements[t.id] || this.handles[t.id] : null;
85854     }
85855 });
85856 /**
85857  * @class Ext.dd.DropZone
85858  * @extends Ext.dd.DropTarget
85859
85860 This class provides a container DD instance that allows dropping on multiple child target nodes.
85861
85862 By default, this class requires that child nodes accepting drop are registered with {@link Ext.dd.Registry}.
85863 However a simpler way to allow a DropZone to manage any number of target elements is to configure the
85864 DropZone with an implementation of {@link #getTargetFromEvent} which interrogates the passed
85865 mouse event to see if it has taken place within an element, or class of elements. This is easily done
85866 by using the event's {@link Ext.EventObject#getTarget getTarget} method to identify a node based on a
85867 {@link Ext.DomQuery} selector.
85868
85869 Once the DropZone has detected through calling getTargetFromEvent, that the mouse is over
85870 a drop target, that target is passed as the first parameter to {@link #onNodeEnter}, {@link #onNodeOver},
85871 {@link #onNodeOut}, {@link #onNodeDrop}. You may configure the instance of DropZone with implementations
85872 of these methods to provide application-specific behaviour for these events to update both
85873 application state, and UI state.
85874
85875 For example to make a GridPanel a cooperating target with the example illustrated in
85876 {@link Ext.dd.DragZone DragZone}, the following technique might be used:
85877
85878     myGridPanel.on('render', function() {
85879         myGridPanel.dropZone = new Ext.dd.DropZone(myGridPanel.getView().scroller, {
85880
85881             // If the mouse is over a grid row, return that node. This is
85882             // provided as the "target" parameter in all "onNodeXXXX" node event handling functions
85883             getTargetFromEvent: function(e) {
85884                 return e.getTarget(myGridPanel.getView().rowSelector);
85885             },
85886
85887             // On entry into a target node, highlight that node.
85888             onNodeEnter : function(target, dd, e, data){ 
85889                 Ext.fly(target).addCls('my-row-highlight-class');
85890             },
85891
85892             // On exit from a target node, unhighlight that node.
85893             onNodeOut : function(target, dd, e, data){ 
85894                 Ext.fly(target).removeCls('my-row-highlight-class');
85895             },
85896
85897             // While over a target node, return the default drop allowed class which
85898             // places a "tick" icon into the drag proxy.
85899             onNodeOver : function(target, dd, e, data){ 
85900                 return Ext.dd.DropZone.prototype.dropAllowed;
85901             },
85902
85903             // On node drop we can interrogate the target to find the underlying
85904             // application object that is the real target of the dragged data.
85905             // In this case, it is a Record in the GridPanel's Store.
85906             // We can use the data set up by the DragZone's getDragData method to read
85907             // any data we decided to attach in the DragZone's getDragData method.
85908             onNodeDrop : function(target, dd, e, data){
85909                 var rowIndex = myGridPanel.getView().findRowIndex(target);
85910                 var r = myGridPanel.getStore().getAt(rowIndex);
85911                 Ext.Msg.alert('Drop gesture', 'Dropped Record id ' + data.draggedRecord.id +
85912                     ' on Record id ' + r.id);
85913                 return true;
85914             }
85915         });
85916     }
85917
85918 See the {@link Ext.dd.DragZone DragZone} documentation for details about building a DragZone which
85919 cooperates with this DropZone.
85920
85921  * @constructor
85922  * @param {Mixed} el The container element
85923  * @param {Object} config
85924  * @markdown
85925  */
85926 Ext.define('Ext.dd.DropZone', {
85927     extend: 'Ext.dd.DropTarget',
85928     requires: ['Ext.dd.Registry'],
85929
85930     /**
85931      * Returns a custom data object associated with the DOM node that is the target of the event.  By default
85932      * this looks up the event target in the {@link Ext.dd.Registry}, although you can override this method to
85933      * provide your own custom lookup.
85934      * @param {Event} e The event
85935      * @return {Object} data The custom data
85936      */
85937     getTargetFromEvent : function(e){
85938         return Ext.dd.Registry.getTargetFromEvent(e);
85939     },
85940
85941     /**
85942      * Called when the DropZone determines that a {@link Ext.dd.DragSource} has entered a drop node
85943      * that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}.
85944      * This method has no default implementation and should be overridden to provide
85945      * node-specific processing if necessary.
85946      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from 
85947      * {@link #getTargetFromEvent} for this node)
85948      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
85949      * @param {Event} e The event
85950      * @param {Object} data An object containing arbitrary data supplied by the drag source
85951      */
85952     onNodeEnter : function(n, dd, e, data){
85953         
85954     },
85955
85956     /**
85957      * Called while the DropZone determines that a {@link Ext.dd.DragSource} is over a drop node
85958      * that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}.
85959      * The default implementation returns this.dropNotAllowed, so it should be
85960      * overridden to provide the proper feedback.
85961      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
85962      * {@link #getTargetFromEvent} for this node)
85963      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
85964      * @param {Event} e The event
85965      * @param {Object} data An object containing arbitrary data supplied by the drag source
85966      * @return {String} status The CSS class that communicates the drop status back to the source so that the
85967      * underlying {@link Ext.dd.StatusProxy} can be updated
85968      */
85969     onNodeOver : function(n, dd, e, data){
85970         return this.dropAllowed;
85971     },
85972
85973     /**
85974      * Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dragged out of
85975      * the drop node without dropping.  This method has no default implementation and should be overridden to provide
85976      * node-specific processing if necessary.
85977      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
85978      * {@link #getTargetFromEvent} for this node)
85979      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
85980      * @param {Event} e The event
85981      * @param {Object} data An object containing arbitrary data supplied by the drag source
85982      */
85983     onNodeOut : function(n, dd, e, data){
85984         
85985     },
85986
85987     /**
85988      * Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped onto
85989      * the drop node.  The default implementation returns false, so it should be overridden to provide the
85990      * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
85991      * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
85992      * {@link #getTargetFromEvent} for this node)
85993      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
85994      * @param {Event} e The event
85995      * @param {Object} data An object containing arbitrary data supplied by the drag source
85996      * @return {Boolean} True if the drop was valid, else false
85997      */
85998     onNodeDrop : function(n, dd, e, data){
85999         return false;
86000     },
86001
86002     /**
86003      * Called while the DropZone determines that a {@link Ext.dd.DragSource} is being dragged over it,
86004      * but not over any of its registered drop nodes.  The default implementation returns this.dropNotAllowed, so
86005      * it should be overridden to provide the proper feedback if necessary.
86006      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
86007      * @param {Event} e The event
86008      * @param {Object} data An object containing arbitrary data supplied by the drag source
86009      * @return {String} status The CSS class that communicates the drop status back to the source so that the
86010      * underlying {@link Ext.dd.StatusProxy} can be updated
86011      */
86012     onContainerOver : function(dd, e, data){
86013         return this.dropNotAllowed;
86014     },
86015
86016     /**
86017      * Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped on it,
86018      * but not on any of its registered drop nodes.  The default implementation returns false, so it should be
86019      * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
86020      * be able to accept drops.  It should return true when valid so that the drag source's repair action does not run.
86021      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
86022      * @param {Event} e The event
86023      * @param {Object} data An object containing arbitrary data supplied by the drag source
86024      * @return {Boolean} True if the drop was valid, else false
86025      */
86026     onContainerDrop : function(dd, e, data){
86027         return false;
86028     },
86029
86030     /**
86031      * The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source is now over
86032      * the zone.  The default implementation returns this.dropNotAllowed and expects that only registered drop
86033      * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
86034      * you should override this method and provide a custom implementation.
86035      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
86036      * @param {Event} e The event
86037      * @param {Object} data An object containing arbitrary data supplied by the drag source
86038      * @return {String} status The CSS class that communicates the drop status back to the source so that the
86039      * underlying {@link Ext.dd.StatusProxy} can be updated
86040      */
86041     notifyEnter : function(dd, e, data){
86042         return this.dropNotAllowed;
86043     },
86044
86045     /**
86046      * The function a {@link Ext.dd.DragSource} calls continuously while it is being dragged over the drop zone.
86047      * This method will be called on every mouse movement while the drag source is over the drop zone.
86048      * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
86049      * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
86050      * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
86051      * registered node, it will call {@link #onContainerOver}.
86052      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
86053      * @param {Event} e The event
86054      * @param {Object} data An object containing arbitrary data supplied by the drag source
86055      * @return {String} status The CSS class that communicates the drop status back to the source so that the
86056      * underlying {@link Ext.dd.StatusProxy} can be updated
86057      */
86058     notifyOver : function(dd, e, data){
86059         var n = this.getTargetFromEvent(e);
86060         if(!n) { // not over valid drop target
86061             if(this.lastOverNode){
86062                 this.onNodeOut(this.lastOverNode, dd, e, data);
86063                 this.lastOverNode = null;
86064             }
86065             return this.onContainerOver(dd, e, data);
86066         }
86067         if(this.lastOverNode != n){
86068             if(this.lastOverNode){
86069                 this.onNodeOut(this.lastOverNode, dd, e, data);
86070             }
86071             this.onNodeEnter(n, dd, e, data);
86072             this.lastOverNode = n;
86073         }
86074         return this.onNodeOver(n, dd, e, data);
86075     },
86076
86077     /**
86078      * The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source has been dragged
86079      * out of the zone without dropping.  If the drag source is currently over a registered node, the notification
86080      * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
86081      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
86082      * @param {Event} e The event
86083      * @param {Object} data An object containing arbitrary data supplied by the drag zone
86084      */
86085     notifyOut : function(dd, e, data){
86086         if(this.lastOverNode){
86087             this.onNodeOut(this.lastOverNode, dd, e, data);
86088             this.lastOverNode = null;
86089         }
86090     },
86091
86092     /**
86093      * The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the dragged item has
86094      * been dropped on it.  The drag zone will look up the target node based on the event passed in, and if there
86095      * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
86096      * otherwise it will call {@link #onContainerDrop}.
86097      * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
86098      * @param {Event} e The event
86099      * @param {Object} data An object containing arbitrary data supplied by the drag source
86100      * @return {Boolean} False if the drop was invalid.
86101      */
86102     notifyDrop : function(dd, e, data){
86103         if(this.lastOverNode){
86104             this.onNodeOut(this.lastOverNode, dd, e, data);
86105             this.lastOverNode = null;
86106         }
86107         var n = this.getTargetFromEvent(e);
86108         return n ?
86109             this.onNodeDrop(n, dd, e, data) :
86110             this.onContainerDrop(dd, e, data);
86111     },
86112
86113     // private
86114     triggerCacheRefresh : function() {
86115         Ext.dd.DDM.refreshCache(this.groups);
86116     }
86117 });
86118 /**
86119  * @class Ext.flash.Component
86120  * @extends Ext.Component
86121  *
86122  * A simple Component for displaying an Adobe Flash SWF movie. The movie will be sized and can participate
86123  * in layout like any other Component.
86124  *
86125  * This component requires the third-party SWFObject library version 2.2 or above. It is not included within
86126  * the ExtJS distribution, so you will have to include it into your page manually in order to use this component.
86127  * The SWFObject library can be downloaded from the [SWFObject project page](http://code.google.com/p/swfobject)
86128  * and then simply import it into the head of your HTML document:
86129  *
86130  *     <script type="text/javascript" src="path/to/local/swfobject.js"></script>
86131  *
86132  * ## Configuration
86133  *
86134  * This component allows several options for configuring how the target Flash movie is embedded. The most
86135  * important is the required {@link #url} which points to the location of the Flash movie to load. Other
86136  * configurations include:
86137  *
86138  * - {@link #backgroundColor}
86139  * - {@link #wmode}
86140  * - {@link #flashVars}
86141  * - {@link #flashParams}
86142  * - {@link #flashAttributes}
86143  *
86144  * ## Example usage:
86145  *
86146  *     var win = Ext.widget('window', {
86147  *         title: "It's a tiger!",
86148  *         layout: 'fit',
86149  *         width: 300,
86150  *         height: 300,
86151  *         x: 20,
86152  *         y: 20,
86153  *         resizable: true,
86154  *         items: {
86155  *             xtype: 'flash',
86156  *             url: 'tiger.swf'
86157  *         }
86158  *     });
86159  *     win.show();
86160  *
86161  * ## Express Install
86162  *
86163  * Adobe provides a tool called [Express Install](http://www.adobe.com/devnet/flashplayer/articles/express_install.html)
86164  * that offers users an easy way to upgrade their Flash player. If you wish to make use of this, you should set
86165  * the static EXPRESS\_INSTALL\_URL property to the location of your Express Install SWF file:
86166  *
86167  *     Ext.flash.Component.EXPRESS_INSTALL_URL = 'path/to/local/expressInstall.swf';
86168  *
86169  * @constructor
86170  * Creates a new Ext.flash.Component instance.
86171  * @param {Object} config The component configuration.
86172  *
86173  * @xtype flash
86174  * @docauthor Jason Johnston <jason@sencha.com>
86175  */
86176 Ext.define('Ext.flash.Component', {
86177     extend: 'Ext.Component',
86178     alternateClassName: 'Ext.FlashComponent',
86179     alias: 'widget.flash',
86180
86181     /**
86182      * @cfg {String} flashVersion
86183      * Indicates the version the flash content was published for. Defaults to <tt>'9.0.115'</tt>.
86184      */
86185     flashVersion : '9.0.115',
86186
86187     /**
86188      * @cfg {String} backgroundColor
86189      * The background color of the SWF movie. Defaults to <tt>'#ffffff'</tt>.
86190      */
86191     backgroundColor: '#ffffff',
86192
86193     /**
86194      * @cfg {String} wmode
86195      * The wmode of the flash object. This can be used to control layering. Defaults to <tt>'opaque'</tt>.
86196      * Set to 'transparent' to ignore the {@link #backgroundColor} and make the background of the Flash
86197      * movie transparent.
86198      */
86199     wmode: 'opaque',
86200
86201     /**
86202      * @cfg {Object} flashVars
86203      * A set of key value pairs to be passed to the flash object as flash variables. Defaults to <tt>undefined</tt>.
86204      */
86205
86206     /**
86207      * @cfg {Object} flashParams
86208      * A set of key value pairs to be passed to the flash object as parameters. Possible parameters can be found here:
86209      * http://kb2.adobe.com/cps/127/tn_12701.html Defaults to <tt>undefined</tt>.
86210      */
86211
86212     /**
86213      * @cfg {Object} flashAttributes
86214      * A set of key value pairs to be passed to the flash object as attributes. Defaults to <tt>undefined</tt>.
86215      */
86216
86217     /**
86218      * @cfg {String} url
86219      * The URL of the SWF file to include. Required.
86220      */
86221
86222     /**
86223      * @cfg {String/Number} swfWidth The width of the embedded SWF movie inside the component. Defaults to "100%"
86224      * so that the movie matches the width of the component.
86225      */
86226     swfWidth: '100%',
86227
86228     /**
86229      * @cfg {String/Number} swfHeight The height of the embedded SWF movie inside the component. Defaults to "100%"
86230      * so that the movie matches the height of the component.
86231      */
86232     swfHeight: '100%',
86233
86234     /**
86235      * @cfg {Boolean} expressInstall
86236      * True to prompt the user to install flash if not installed. Note that this uses
86237      * Ext.FlashComponent.EXPRESS_INSTALL_URL, which should be set to the local resource. Defaults to <tt>false</tt>.
86238      */
86239     expressInstall: false,
86240
86241     /**
86242      * @property swf
86243      * @type {Ext.core.Element}
86244      * A reference to the object or embed element into which the SWF file is loaded. Only
86245      * populated after the component is rendered and the SWF has been successfully embedded.
86246      */
86247
86248     // Have to create a placeholder div with the swfId, which SWFObject will replace with the object/embed element.
86249     renderTpl: ['<div id="{swfId}"></div>'],
86250
86251     initComponent: function() {
86252         if (!('swfobject' in window)) {
86253             Ext.Error.raise('The SWFObject library is not loaded. Ext.flash.Component requires SWFObject version 2.2 or later: http://code.google.com/p/swfobject/');
86254         }
86255         if (!this.url) {
86256             Ext.Error.raise('The "url" config is required for Ext.flash.Component');
86257         }
86258
86259         this.callParent();
86260         this.addEvents(
86261             /**
86262              * @event success
86263              * Fired when the Flash movie has been successfully embedded
86264              * @param {Ext.flash.Component} this
86265              */
86266             'success',
86267
86268             /**
86269              * @event failure
86270              * Fired when the Flash movie embedding fails
86271              * @param {Ext.flash.Component} this
86272              */
86273             'failure'
86274         );
86275     },
86276
86277     onRender: function() {
86278         var me = this,
86279             params, vars, undef,
86280             swfId = me.getSwfId();
86281
86282         me.renderData.swfId = swfId;
86283
86284         me.callParent(arguments);
86285
86286         params = Ext.apply({
86287             allowScriptAccess: 'always',
86288             bgcolor: me.backgroundColor,
86289             wmode: me.wmode
86290         }, me.flashParams);
86291
86292         vars = Ext.apply({
86293             allowedDomain: document.location.hostname
86294         }, me.flashVars);
86295
86296         new swfobject.embedSWF(
86297             me.url,
86298             swfId,
86299             me.swfWidth,
86300             me.swfHeight,
86301             me.flashVersion,
86302             me.expressInstall ? me.statics.EXPRESS_INSTALL_URL : undef,
86303             vars,
86304             params,
86305             me.flashAttributes,
86306             Ext.bind(me.swfCallback, me)
86307         );
86308     },
86309
86310     /**
86311      * @private
86312      * The callback method for handling an embedding success or failure by SWFObject
86313      * @param {Object} e The event object passed by SWFObject - see http://code.google.com/p/swfobject/wiki/api
86314      */
86315     swfCallback: function(e) {
86316         var me = this;
86317         if (e.success) {
86318             me.swf = Ext.get(e.ref);
86319             me.onSuccess();
86320             me.fireEvent('success', me);
86321         } else {
86322             me.onFailure();
86323             me.fireEvent('failure', me);
86324         }
86325     },
86326
86327     /**
86328      * Retrieve the id of the SWF object/embed element
86329      */
86330     getSwfId: function() {
86331         return this.swfId || (this.swfId = "extswf" + this.getAutoId());
86332     },
86333
86334     onSuccess: function() {
86335         // swfobject forces visiblity:visible on the swf element, which prevents it 
86336         // from getting hidden when an ancestor is given visibility:hidden.
86337         this.swf.setStyle('visibility', 'inherit');
86338     },
86339
86340     onFailure: Ext.emptyFn,
86341
86342     beforeDestroy: function() {
86343         var me = this,
86344             swf = me.swf;
86345         if (swf) {
86346             swfobject.removeSWF(me.getSwfId());
86347             Ext.destroy(swf);
86348             delete me.swf;
86349         }
86350         me.callParent();
86351     },
86352
86353     statics: {
86354         /**
86355          * Sets the url for installing flash if it doesn't exist. This should be set to a local resource.
86356          * See http://www.adobe.com/devnet/flashplayer/articles/express_install.html for details.
86357          * @static
86358          * @type String
86359          */
86360         EXPRESS_INSTALL_URL: 'http:/' + '/swfobject.googlecode.com/svn/trunk/swfobject/expressInstall.swf'
86361     }
86362 });
86363
86364 /**
86365  * @class Ext.form.action.Action
86366  * @extends Ext.Base
86367  * <p>The subclasses of this class provide actions to perform upon {@link Ext.form.Basic Form}s.</p>
86368  * <p>Instances of this class are only created by a {@link Ext.form.Basic Form} when
86369  * the Form needs to perform an action such as submit or load. The Configuration options
86370  * listed for this class are set through the Form's action methods: {@link Ext.form.Basic#submit submit},
86371  * {@link Ext.form.Basic#load load} and {@link Ext.form.Basic#doAction doAction}</p>
86372  * <p>The instance of Action which performed the action is passed to the success
86373  * and failure callbacks of the Form's action methods ({@link Ext.form.Basic#submit submit},
86374  * {@link Ext.form.Basic#load load} and {@link Ext.form.Basic#doAction doAction}),
86375  * and to the {@link Ext.form.Basic#actioncomplete actioncomplete} and
86376  * {@link Ext.form.Basic#actionfailed actionfailed} event handlers.</p>
86377  * @constructor
86378  * @param {Object} config The configuration for this instance.
86379  */
86380 Ext.define('Ext.form.action.Action', {
86381     alternateClassName: 'Ext.form.Action',
86382
86383     /**
86384      * @cfg {Ext.form.Basic} form The {@link Ext.form.Basic BasicForm} instance that
86385      * is invoking this Action. Required.
86386      */
86387
86388     /**
86389      * @cfg {String} url The URL that the Action is to invoke. Will default to the {@link Ext.form.Basic#url url}
86390      * configured on the {@link #form}.
86391      */
86392
86393     /**
86394      * @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be
86395      * {@link Ext.form.Basic#reset reset} on Action success. If specified, this happens
86396      * before the {@link #success} callback is called and before the Form's
86397      * {@link Ext.form.Basic#actioncomplete actioncomplete} event fires.
86398      */
86399
86400     /**
86401      * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the
86402      * {@link Ext.form.Basic#method BasicForm's method}, or 'POST' if not specified.
86403      */
86404
86405     /**
86406      * @cfg {Object/String} params <p>Extra parameter values to pass. These are added to the Form's
86407      * {@link Ext.form.Basic#baseParams} and passed to the specified URL along with the Form's
86408      * input fields.</p>
86409      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode Ext.Object.toQueryString}.</p>
86410      */
86411
86412     /**
86413      * @cfg {Object} headers <p>Extra headers to be sent in the AJAX request for submit and load actions. See
86414      * {@link Ext.data.Connection#headers}.</p>
86415      */
86416
86417     /**
86418      * @cfg {Number} timeout The number of seconds to wait for a server response before
86419      * failing with the {@link #failureType} as {@link Ext.form.action.Action#CONNECT_FAILURE}. If not specified,
86420      * defaults to the configured <tt>{@link Ext.form.Basic#timeout timeout}</tt> of the
86421      * {@link #form}.
86422      */
86423
86424     /**
86425      * @cfg {Function} success The function to call when a valid success return packet is received.
86426      * The function is passed the following parameters:<ul class="mdetail-params">
86427      * <li><b>form</b> : Ext.form.Basic<div class="sub-desc">The form that requested the action</div></li>
86428      * <li><b>action</b> : Ext.form.action.Action<div class="sub-desc">The Action class. The {@link #result}
86429      * property of this object may be examined to perform custom postprocessing.</div></li>
86430      * </ul>
86431      */
86432
86433     /**
86434      * @cfg {Function} failure The function to call when a failure packet was received, or when an
86435      * error ocurred in the Ajax communication.
86436      * The function is passed the following parameters:<ul class="mdetail-params">
86437      * <li><b>form</b> : Ext.form.Basic<div class="sub-desc">The form that requested the action</div></li>
86438      * <li><b>action</b> : Ext.form.action.Action<div class="sub-desc">The Action class. If an Ajax
86439      * error ocurred, the failure type will be in {@link #failureType}. The {@link #result}
86440      * property of this object may be examined to perform custom postprocessing.</div></li>
86441      * </ul>
86442      */
86443
86444     /**
86445      * @cfg {Object} scope The scope in which to call the configured <tt>success</tt> and <tt>failure</tt>
86446      * callback functions (the <tt>this</tt> reference for the callback functions).
86447      */
86448
86449     /**
86450      * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.window.MessageBox#wait}
86451      * during the time the action is being processed.
86452      */
86453
86454     /**
86455      * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.window.MessageBox#wait}
86456      * during the time the action is being processed.
86457      */
86458
86459     /**
86460      * @cfg {Boolean} submitEmptyText If set to <tt>true</tt>, the emptyText value will be sent with the form
86461      * when it is submitted. Defaults to <tt>true</tt>.
86462      */
86463
86464     /**
86465      * @property type
86466      * The type of action this Action instance performs.
86467      * Currently only "submit" and "load" are supported.
86468      * @type {String}
86469      */
86470
86471     /**
86472      * The type of failure detected will be one of these: {@link Ext.form.action.Action#CLIENT_INVALID},
86473      * {@link Ext.form.action.Action#SERVER_INVALID}, {@link Ext.form.action.Action#CONNECT_FAILURE}, or
86474      * {@link Ext.form.action.Action#LOAD_FAILURE}.  Usage:
86475      * <pre><code>
86476 var fp = new Ext.form.Panel({
86477 ...
86478 buttons: [{
86479     text: 'Save',
86480     formBind: true,
86481     handler: function(){
86482         if(fp.getForm().isValid()){
86483             fp.getForm().submit({
86484                 url: 'form-submit.php',
86485                 waitMsg: 'Submitting your data...',
86486                 success: function(form, action){
86487                     // server responded with success = true
86488                     var result = action.{@link #result};
86489                 },
86490                 failure: function(form, action){
86491                     if (action.{@link #failureType} === {@link Ext.form.action.Action#CONNECT_FAILURE}) {
86492                         Ext.Msg.alert('Error',
86493                             'Status:'+action.{@link #response}.status+': '+
86494                             action.{@link #response}.statusText);
86495                     }
86496                     if (action.failureType === {@link Ext.form.action.Action#SERVER_INVALID}){
86497                         // server responded with success = false
86498                         Ext.Msg.alert('Invalid', action.{@link #result}.errormsg);
86499                     }
86500                 }
86501             });
86502         }
86503     }
86504 },{
86505     text: 'Reset',
86506     handler: function(){
86507         fp.getForm().reset();
86508     }
86509 }]
86510      * </code></pre>
86511      * @property failureType
86512      * @type {String}
86513      */
86514
86515     /**
86516      * The raw XMLHttpRequest object used to perform the action.
86517      * @property response
86518      * @type {Object}
86519      */
86520
86521     /**
86522      * The decoded response object containing a boolean <tt>success</tt> property and
86523      * other, action-specific properties.
86524      * @property result
86525      * @type {Object}
86526      */
86527
86528
86529
86530     constructor: function(config) {
86531         if (config) {
86532             Ext.apply(this, config);
86533         }
86534
86535         // Normalize the params option to an Object
86536         var params = config.params;
86537         if (Ext.isString(params)) {
86538             this.params = Ext.Object.fromQueryString(params);
86539         }
86540     },
86541
86542     /**
86543      * Invokes this action using the current configuration.
86544      */
86545     run: Ext.emptyFn,
86546
86547     /**
86548      * @private
86549      * @method onSuccess
86550      * Callback method that gets invoked when the action completes successfully. Must be implemented by subclasses.
86551      * @param {Object} response
86552      */
86553
86554     /**
86555      * @private
86556      * @method handleResponse
86557      * Handles the raw response and builds a result object from it. Must be implemented by subclasses.
86558      * @param {Object} response
86559      */
86560
86561     /**
86562      * @private
86563      * Handles a failure response.
86564      * @param {Object} response
86565      */
86566     onFailure : function(response){
86567         this.response = response;
86568         this.failureType = Ext.form.action.Action.CONNECT_FAILURE;
86569         this.form.afterAction(this, false);
86570     },
86571
86572     /**
86573      * @private
86574      * Validates that a response contains either responseText or responseXML and invokes
86575      * {@link #handleResponse} to build the result object.
86576      * @param {Object} response The raw response object.
86577      * @return {Object/Boolean} result The result object as built by handleResponse, or <tt>true</tt> if
86578      *                         the response had empty responseText and responseXML.
86579      */
86580     processResponse : function(response){
86581         this.response = response;
86582         if (!response.responseText && !response.responseXML) {
86583             return true;
86584         }
86585         return (this.result = this.handleResponse(response));
86586     },
86587
86588     /**
86589      * @private
86590      * Build the URL for the AJAX request. Used by the standard AJAX submit and load actions.
86591      * @return {String} The URL.
86592      */
86593     getUrl: function() {
86594         return this.url || this.form.url;
86595     },
86596
86597     /**
86598      * @private
86599      * Determine the HTTP method to be used for the request.
86600      * @return {String} The HTTP method
86601      */
86602     getMethod: function() {
86603         return (this.method || this.form.method || 'POST').toUpperCase();
86604     },
86605
86606     /**
86607      * @private
86608      * Get the set of parameters specified in the BasicForm's baseParams and/or the params option.
86609      * Items in params override items of the same name in baseParams.
86610      * @return {Object} the full set of parameters
86611      */
86612     getParams: function() {
86613         return Ext.apply({}, this.params, this.form.baseParams);
86614     },
86615
86616     /**
86617      * @private
86618      * Creates a callback object.
86619      */
86620     createCallback: function() {
86621         var me = this,
86622             undef,
86623             form = me.form;
86624         return {
86625             success: me.onSuccess,
86626             failure: me.onFailure,
86627             scope: me,
86628             timeout: (this.timeout * 1000) || (form.timeout * 1000),
86629             upload: form.fileUpload ? me.onSuccess : undef
86630         };
86631     },
86632
86633     statics: {
86634         /**
86635          * @property CLIENT_INVALID
86636          * Failure type returned when client side validation of the Form fails
86637          * thus aborting a submit action. Client side validation is performed unless
86638          * {@link Ext.form.action.Submit#clientValidation} is explicitly set to <tt>false</tt>.
86639          * @type {String}
86640          * @static
86641          */
86642         CLIENT_INVALID: 'client',
86643
86644         /**
86645          * @property SERVER_INVALID
86646          * <p>Failure type returned when server side processing fails and the {@link #result}'s
86647          * <tt>success</tt> property is set to <tt>false</tt>.</p>
86648          * <p>In the case of a form submission, field-specific error messages may be returned in the
86649          * {@link #result}'s <tt>errors</tt> property.</p>
86650          * @type {String}
86651          * @static
86652          */
86653         SERVER_INVALID: 'server',
86654
86655         /**
86656          * @property CONNECT_FAILURE
86657          * Failure type returned when a communication error happens when attempting
86658          * to send a request to the remote server. The {@link #response} may be examined to
86659          * provide further information.
86660          * @type {String}
86661          * @static
86662          */
86663         CONNECT_FAILURE: 'connect',
86664
86665         /**
86666          * @property LOAD_FAILURE
86667          * Failure type returned when the response's <tt>success</tt>
86668          * property is set to <tt>false</tt>, or no field values are returned in the response's
86669          * <tt>data</tt> property.
86670          * @type {String}
86671          * @static
86672          */
86673         LOAD_FAILURE: 'load'
86674
86675
86676     }
86677 });
86678
86679 /**
86680  * @class Ext.form.action.Submit
86681  * @extends Ext.form.action.Action
86682  * <p>A class which handles submission of data from {@link Ext.form.Basic Form}s
86683  * and processes the returned response.</p>
86684  * <p>Instances of this class are only created by a {@link Ext.form.Basic Form} when
86685  * {@link Ext.form.Basic#submit submit}ting.</p>
86686  * <p><u><b>Response Packet Criteria</b></u></p>
86687  * <p>A response packet may contain:
86688  * <div class="mdetail-params"><ul>
86689  * <li><b><code>success</code></b> property : Boolean
86690  * <div class="sub-desc">The <code>success</code> property is required.</div></li>
86691  * <li><b><code>errors</code></b> property : Object
86692  * <div class="sub-desc"><div class="sub-desc">The <code>errors</code> property,
86693  * which is optional, contains error messages for invalid fields.</div></li>
86694  * </ul></div>
86695  * <p><u><b>JSON Packets</b></u></p>
86696  * <p>By default, response packets are assumed to be JSON, so a typical response
86697  * packet may look like this:</p><pre><code>
86698 {
86699     success: false,
86700     errors: {
86701         clientCode: "Client not found",
86702         portOfLoading: "This field must not be null"
86703     }
86704 }</code></pre>
86705  * <p>Other data may be placed into the response for processing by the {@link Ext.form.Basic}'s callback
86706  * or event handler methods. The object decoded from this JSON is available in the
86707  * {@link Ext.form.action.Action#result result} property.</p>
86708  * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.reader.Xml XmlReader}:</p><pre><code>
86709     errorReader: new Ext.data.reader.Xml({
86710             record : 'field',
86711             success: '@success'
86712         }, [
86713             'id', 'msg'
86714         ]
86715     )
86716 </code></pre>
86717  * <p>then the results may be sent back in XML format:</p><pre><code>
86718 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
86719 &lt;message success="false"&gt;
86720 &lt;errors&gt;
86721     &lt;field&gt;
86722         &lt;id&gt;clientCode&lt;/id&gt;
86723         &lt;msg&gt;&lt;![CDATA[Code not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt;
86724     &lt;/field&gt;
86725     &lt;field&gt;
86726         &lt;id&gt;portOfLoading&lt;/id&gt;
86727         &lt;msg&gt;&lt;![CDATA[Port not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt;
86728     &lt;/field&gt;
86729 &lt;/errors&gt;
86730 &lt;/message&gt;
86731 </code></pre>
86732  * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.Basic}'s callback
86733  * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.reader.Xml#xmlData xmlData} property.</p>
86734  */
86735 Ext.define('Ext.form.action.Submit', {
86736     extend:'Ext.form.action.Action',
86737     alternateClassName: 'Ext.form.Action.Submit',
86738     alias: 'formaction.submit',
86739
86740     type: 'submit',
86741
86742     /**
86743      * @cfg {boolean} clientValidation Determines whether a Form's fields are validated
86744      * in a final call to {@link Ext.form.Basic#isValid isValid} prior to submission.
86745      * Pass <tt>false</tt> in the Form's submit options to prevent this. Defaults to true.
86746      */
86747
86748     // inherit docs
86749     run : function(){
86750         var form = this.form;
86751         if (this.clientValidation === false || form.isValid()) {
86752             this.doSubmit();
86753         } else {
86754             // client validation failed
86755             this.failureType = Ext.form.action.Action.CLIENT_INVALID;
86756             form.afterAction(this, false);
86757         }
86758     },
86759
86760     /**
86761      * @private
86762      * Perform the submit of the form data.
86763      */
86764     doSubmit: function() {
86765         var formEl,
86766             ajaxOptions = Ext.apply(this.createCallback(), {
86767                 url: this.getUrl(),
86768                 method: this.getMethod(),
86769                 headers: this.headers
86770             });
86771
86772         // For uploads we need to create an actual form that contains the file upload fields,
86773         // and pass that to the ajax call so it can do its iframe-based submit method.
86774         if (this.form.hasUpload()) {
86775             formEl = ajaxOptions.form = this.buildForm();
86776             ajaxOptions.isUpload = true;
86777         } else {
86778             ajaxOptions.params = this.getParams();
86779         }
86780
86781         Ext.Ajax.request(ajaxOptions);
86782
86783         if (formEl) {
86784             Ext.removeNode(formEl);
86785         }
86786     },
86787
86788     /**
86789      * @private
86790      * Build the full set of parameters from the field values plus any additional configured params.
86791      */
86792     getParams: function() {
86793         var nope = false,
86794             configParams = this.callParent(),
86795             fieldParams = this.form.getValues(nope, nope, this.submitEmptyText !== nope);
86796         return Ext.apply({}, fieldParams, configParams);
86797     },
86798
86799     /**
86800      * @private
86801      * Build a form element containing fields corresponding to all the parameters to be
86802      * submitted (everything returned by {@link #getParams}.
86803      * NOTE: the form element is automatically added to the DOM, so any code that uses
86804      * it must remove it from the DOM after finishing with it.
86805      * @return HTMLFormElement
86806      */
86807     buildForm: function() {
86808         var fieldsSpec = [],
86809             formSpec,
86810             formEl,
86811             basicForm = this.form,
86812             params = this.getParams(),
86813             uploadFields = [];
86814
86815         basicForm.getFields().each(function(field) {
86816             if (field.isFileUpload()) {
86817                 uploadFields.push(field);
86818             }
86819         });
86820
86821         function addField(name, val) {
86822             fieldsSpec.push({
86823                 tag: 'input',
86824                 type: 'hidden',
86825                 name: name,
86826                 value: val
86827             });
86828         }
86829
86830         // Add the form field values
86831         Ext.iterate(params, function(key, val) {
86832             if (Ext.isArray(val)) {
86833                 Ext.each(val, function(v) {
86834                     addField(key, v);
86835                 });
86836             } else {
86837                 addField(key, val);
86838             }
86839         });
86840
86841         formSpec = {
86842             tag: 'form',
86843             action: this.getUrl(),
86844             method: this.getMethod(),
86845             target: this.target || '_self',
86846             style: 'display:none',
86847             cn: fieldsSpec
86848         };
86849
86850         // Set the proper encoding for file uploads
86851         if (uploadFields.length) {
86852             formSpec.encoding = formSpec.enctype = 'multipart/form-data';
86853         }
86854
86855         // Create the form
86856         formEl = Ext.core.DomHelper.append(Ext.getBody(), formSpec);
86857
86858         // Special handling for file upload fields: since browser security measures prevent setting
86859         // their values programatically, and prevent carrying their selected values over when cloning,
86860         // we have to move the actual field instances out of their components and into the form.
86861         Ext.Array.each(uploadFields, function(field) {
86862             if (field.rendered) { // can only have a selected file value after being rendered
86863                 formEl.appendChild(field.extractFileInput());
86864             }
86865         });
86866
86867         return formEl;
86868     },
86869
86870
86871
86872     /**
86873      * @private
86874      */
86875     onSuccess: function(response) {
86876         var form = this.form,
86877             success = true,
86878             result = this.processResponse(response);
86879         if (result !== true && !result.success) {
86880             if (result.errors) {
86881                 form.markInvalid(result.errors);
86882             }
86883             this.failureType = Ext.form.action.Action.SERVER_INVALID;
86884             success = false;
86885         }
86886         form.afterAction(this, success);
86887     },
86888
86889     /**
86890      * @private
86891      */
86892     handleResponse: function(response) {
86893         var form = this.form,
86894             errorReader = form.errorReader,
86895             rs, errors, i, len, records;
86896         if (errorReader) {
86897             rs = errorReader.read(response);
86898             records = rs.records;
86899             errors = [];
86900             if (records) {
86901                 for(i = 0, len = records.length; i < len; i++) {
86902                     errors[i] = records[i].data;
86903                 }
86904             }
86905             if (errors.length < 1) {
86906                 errors = null;
86907             }
86908             return {
86909                 success : rs.success,
86910                 errors : errors
86911             };
86912         }
86913         return Ext.decode(response.responseText);
86914     }
86915 });
86916
86917 /**
86918  * @class Ext.util.ComponentDragger
86919  * @extends Ext.dd.DragTracker
86920  * <p>A subclass of Ext.dd.DragTracker which handles dragging any Component.</p>
86921  * <p>This is configured with a Component to be made draggable, and a config object for the
86922  * {@link Ext.dd.DragTracker} class.</p>
86923  * <p>A {@link #} delegate may be provided which may be either the element to use as the mousedown target
86924  * or a {@link Ext.DomQuery} selector to activate multiple mousedown targets.</p>
86925  * @constructor Create a new ComponentTracker
86926  * @param {object} comp The Component to provide dragging for.
86927  * @param {object} config The config object
86928  */
86929 Ext.define('Ext.util.ComponentDragger', {
86930
86931     /**
86932      * @cfg {Boolean} constrain
86933      * Specify as <code>true</code> to constrain the Component to within the bounds of the {@link #constrainTo} region.
86934      */
86935
86936     /**
86937      * @cfg {String/Element} delegate
86938      * Optional. <p>A {@link Ext.DomQuery DomQuery} selector which identifies child elements within the Component's encapsulating
86939      * Element which are the drag handles. This limits dragging to only begin when the matching elements are mousedowned.</p>
86940      * <p>This may also be a specific child element within the Component's encapsulating element to use as the drag handle.</p>
86941      */
86942
86943     /**
86944      * @cfg {Boolean} constrainDelegate
86945      * Specify as <code>true</code> to constrain the drag handles within the {@link constrainTo} region.
86946      */
86947
86948     extend: 'Ext.dd.DragTracker',
86949
86950     autoStart: 500,
86951
86952     constructor: function(comp, config) {
86953         this.comp = comp;
86954         this.initialConstrainTo = config.constrainTo;
86955         this.callParent([ config ]);
86956     },
86957
86958     onStart: function(e) {
86959         var me = this,
86960             comp = me.comp;
86961
86962         // Cache the start [X, Y] array
86963         this.startPosition = comp.getPosition();
86964
86965         // If client Component has a ghost method to show a lightweight version of itself
86966         // then use that as a drag proxy unless configured to liveDrag.
86967         if (comp.ghost && !comp.liveDrag) {
86968              me.proxy = comp.ghost();
86969              me.dragTarget = me.proxy.header.el;
86970         }
86971
86972         // Set the constrainTo Region before we start dragging.
86973         if (me.constrain || me.constrainDelegate) {
86974             me.constrainTo = me.calculateConstrainRegion();
86975         }
86976     },
86977
86978     calculateConstrainRegion: function() {
86979         var me = this,
86980             comp = me.comp,
86981             c = me.initialConstrainTo,
86982             delegateRegion,
86983             elRegion,
86984             shadowSize = comp.el.shadow ? comp.el.shadow.offset : 0;
86985
86986         // The configured constrainTo might be a Region or an element
86987         if (!(c instanceof Ext.util.Region)) {
86988             c =  Ext.fly(c).getViewRegion();
86989         }
86990
86991         // Reduce the constrain region to allow for shadow
86992         if (shadowSize) {
86993             c.adjust(0, -shadowSize, -shadowSize, shadowSize);
86994         }
86995
86996         // If they only want to constrain the *delegate* to within the constrain region,
86997         // adjust the region to be larger based on the insets of the delegate from the outer
86998         // edges of the Component.
86999         if (!me.constrainDelegate) {
87000             delegateRegion = Ext.fly(me.dragTarget).getRegion();
87001             elRegion = me.proxy ? me.proxy.el.getRegion() : comp.el.getRegion();
87002
87003             c.adjust(
87004                 delegateRegion.top - elRegion.top,
87005                 delegateRegion.right - elRegion.right,
87006                 delegateRegion.bottom - elRegion.bottom,
87007                 delegateRegion.left - elRegion.left
87008             );
87009         }
87010         return c;
87011     },
87012
87013     // Move either the ghost Component or the target Component to its new position on drag
87014     onDrag: function(e) {
87015         var me = this,
87016             comp = (me.proxy && !me.comp.liveDrag) ? me.proxy : me.comp,
87017             offset = me.getOffset(me.constrain || me.constrainDelegate ? 'dragTarget' : null);
87018
87019         comp.setPosition.apply(comp, [me.startPosition[0] + offset[0], me.startPosition[1] + offset[1]]);
87020     },
87021
87022     onEnd: function(e) {
87023         if (this.proxy && !this.comp.liveDrag) {
87024             this.comp.unghost();
87025         }
87026     }
87027 });
87028 /**
87029  * @class Ext.form.Labelable
87030
87031 A mixin which allows a component to be configured and decorated with a label and/or error message as is
87032 common for form fields. This is used by e.g. {@link Ext.form.field.Base} and {@link Ext.form.FieldContainer}
87033 to let them be managed by the Field layout.
87034
87035 **NOTE**: This mixin is mainly for internal library use and most users should not need to use it directly. It
87036 is more likely you will want to use one of the component classes that import this mixin, such as
87037 {@link Ext.form.field.Base} or {@link Ext.form.FieldContainer}.
87038
87039 Use of this mixin does not make a component a field in the logical sense, meaning it does not provide any
87040 logic or state related to values or validation; that is handled by the related {@link Ext.form.field.Field}
87041 mixin. These two mixins may be used separately (for example {@link Ext.form.FieldContainer} is Labelable but not a
87042 Field), or in combination (for example {@link Ext.form.field.Base} implements both and has logic for connecting the
87043 two.)
87044
87045 Component classes which use this mixin should use the Field layout
87046 or a derivation thereof to properly size and position the label and message according to the component config.
87047 They must also call the {@link #initLabelable} method during component initialization to ensure the mixin gets
87048 set up correctly.
87049
87050  * @markdown
87051  * @docauthor Jason Johnston <jason@sencha.com>
87052  */
87053 Ext.define("Ext.form.Labelable", {
87054     requires: ['Ext.XTemplate'],
87055
87056     /**
87057      * @cfg {Array/String/Ext.XTemplate} labelableRenderTpl
87058      * The rendering template for the field decorations. Component classes using this mixin should include
87059      * logic to use this as their {@link Ext.AbstractComponent#renderTpl renderTpl}, and implement the
87060      * {@link #getSubTplMarkup} method to generate the field body content.
87061      */
87062     labelableRenderTpl: [
87063         '<tpl if="!hideLabel && !(!fieldLabel && hideEmptyLabel)">',
87064             '<label<tpl if="inputId"> for="{inputId}"</tpl> class="{labelCls}"<tpl if="labelStyle"> style="{labelStyle}"</tpl>>',
87065                 '<tpl if="fieldLabel">{fieldLabel}{labelSeparator}</tpl>',
87066             '</label>',
87067         '</tpl>',
87068         '<div class="{baseBodyCls} {fieldBodyCls}"<tpl if="inputId"> id="{baseBodyCls}-{inputId}"</tpl> role="presentation">{subTplMarkup}</div>',
87069         '<div class="{errorMsgCls}" style="display:none"></div>',
87070         '<div class="{clearCls}" role="presentation"><!-- --></div>',
87071         {
87072             compiled: true,
87073             disableFormats: true
87074         }
87075     ],
87076
87077     /**
87078      * @cfg {Ext.XTemplate} activeErrorsTpl
87079      * The template used to format the Array of error messages passed to {@link #setActiveErrors}
87080      * into a single HTML string. By default this renders each message as an item in an unordered list.
87081      */
87082     activeErrorsTpl: [
87083         '<tpl if="errors && errors.length">',
87084             '<ul><tpl for="errors"><li<tpl if="xindex == xcount"> class="last"</tpl>>{.}</li></tpl></ul>',
87085         '</tpl>'
87086     ],
87087
87088     /**
87089      * @property isFieldLabelable
87090      * @type Boolean
87091      * Flag denoting that this object is labelable as a field. Always true.
87092      */
87093     isFieldLabelable: true,
87094
87095     /**
87096      * @cfg {String} formItemCls
87097      * A CSS class to be applied to the outermost element to denote that it is participating in the form
87098      * field layout. Defaults to 'x-form-item'.
87099      */
87100     formItemCls: Ext.baseCSSPrefix + 'form-item',
87101
87102     /**
87103      * @cfg {String} labelCls
87104      * The CSS class to be applied to the label element. Defaults to 'x-form-item-label'.
87105      */
87106     labelCls: Ext.baseCSSPrefix + 'form-item-label',
87107
87108     /**
87109      * @cfg {String} errorMsgCls
87110      * The CSS class to be applied to the error message element. Defaults to 'x-form-error-msg'.
87111      */
87112     errorMsgCls: Ext.baseCSSPrefix + 'form-error-msg',
87113
87114     /**
87115      * @cfg {String} baseBodyCls
87116      * The CSS class to be applied to the body content element. Defaults to 'x-form-item-body'.
87117      */
87118     baseBodyCls: Ext.baseCSSPrefix + 'form-item-body',
87119
87120     /**
87121      * @cfg {String} fieldBodyCls
87122      * An extra CSS class to be applied to the body content element in addition to {@link #fieldBodyCls}.
87123      * Defaults to empty.
87124      */
87125     fieldBodyCls: '',
87126
87127     /**
87128      * @cfg {String} clearCls
87129      * The CSS class to be applied to the special clearing div rendered directly after the field
87130      * contents wrapper to provide field clearing (defaults to <tt>'x-clear'</tt>).
87131      */
87132     clearCls: Ext.baseCSSPrefix + 'clear',
87133
87134     /**
87135      * @cfg {String} invalidCls
87136      * The CSS class to use when marking the component invalid (defaults to 'x-form-invalid')
87137      */
87138     invalidCls : Ext.baseCSSPrefix + 'form-invalid',
87139
87140     /**
87141      * @cfg {String} fieldLabel
87142      * The label for the field. It gets appended with the {@link #labelSeparator}, and its position
87143      * and sizing is determined by the {@link #labelAlign}, {@link #labelWidth}, and {@link #labelPad}
87144      * configs. Defaults to undefined.
87145      */
87146     fieldLabel: undefined,
87147
87148     /**
87149      * @cfg {String} labelAlign
87150      * <p>Controls the position and alignment of the {@link #fieldLabel}. Valid values are:</p>
87151      * <ul>
87152      * <li><tt>"left"</tt> (the default) - The label is positioned to the left of the field, with its text
87153      * aligned to the left. Its width is determined by the {@link #labelWidth} config.</li>
87154      * <li><tt>"top"</tt> - The label is positioned above the field.</li>
87155      * <li><tt>"right"</tt> - The label is positioned to the left of the field, with its text aligned
87156      * to the right. Its width is determined by the {@link #labelWidth} config.</li>
87157      * </ul>
87158      */
87159     labelAlign : 'left',
87160
87161     /**
87162      * @cfg {Number} labelWidth
87163      * The width of the {@link #fieldLabel} in pixels. Only applicable if the {@link #labelAlign} is set
87164      * to "left" or "right". Defaults to <tt>100</tt>.
87165      */
87166     labelWidth: 100,
87167
87168     /**
87169      * @cfg {Number} labelPad
87170      * The amount of space in pixels between the {@link #fieldLabel} and the input field. Defaults to <tt>5</tt>.
87171      */
87172     labelPad : 5,
87173
87174     /**
87175      * @cfg {String} labelSeparator
87176      * Character(s) to be inserted at the end of the {@link #fieldLabel label text}.
87177      */
87178     labelSeparator : ':',
87179
87180     /**
87181      * @cfg {String} labelStyle
87182      * <p>A CSS style specification string to apply directly to this field's label. Defaults to undefined.</p>
87183      */
87184
87185     /**
87186      * @cfg {Boolean} hideLabel
87187      * <p>Set to <tt>true</tt> to completely hide the label element ({@link #fieldLabel} and {@link #labelSeparator}).
87188      * Defaults to <tt>false</tt>.</p>
87189      * <p>Also see {@link #hideEmptyLabel}, which controls whether space will be reserved for an empty fieldLabel.</p>
87190      */
87191     hideLabel: false,
87192
87193     /**
87194      * @cfg {Boolean} hideEmptyLabel
87195      * <p>When set to <tt>true</tt>, the label element ({@link #fieldLabel} and {@link #labelSeparator}) will be
87196      * automatically hidden if the {@link #fieldLabel} is empty. Setting this to <tt>false</tt> will cause the empty
87197      * label element to be rendered and space to be reserved for it; this is useful if you want a field without a label
87198      * to line up with other labeled fields in the same form. Defaults to <tt>true</tt>.</p>
87199      * <p>If you wish to unconditionall hide the label even if a non-empty fieldLabel is configured, then set
87200      * the {@link #hideLabel} config to <tt>true</tt>.</p>
87201      */
87202     hideEmptyLabel: true,
87203
87204     /**
87205      * @cfg {Boolean} preventMark
87206      * <tt>true</tt> to disable displaying any {@link #setActiveError error message} set on this object.
87207      * Defaults to <tt>false</tt>.
87208      */
87209     preventMark: false,
87210
87211     /**
87212      * @cfg {Boolean} autoFitErrors
87213      * Whether to adjust the component's body area to make room for 'side' or 'under'
87214      * {@link #msgTarget error messages}. Defaults to <tt>true</tt>.
87215      */
87216     autoFitErrors: true,
87217
87218     /**
87219      * @cfg {String} msgTarget <p>The location where the error message text should display.
87220      * Must be one of the following values:</p>
87221      * <div class="mdetail-params"><ul>
87222      * <li><code>qtip</code> Display a quick tip containing the message when the user hovers over the field. This is the default.
87223      * <div class="subdesc"><b>{@link Ext.tip.QuickTipManager#init Ext.tip.QuickTipManager.init} must have been called for this setting to work.</b></div></li>
87224      * <li><code>title</code> Display the message in a default browser title attribute popup.</li>
87225      * <li><code>under</code> Add a block div beneath the field containing the error message.</li>
87226      * <li><code>side</code> Add an error icon to the right of the field, displaying the message in a popup on hover.</li>
87227      * <li><code>none</code> Don't display any error message. This might be useful if you are implementing custom error display.</li>
87228      * <li><code>[element id]</code> Add the error message directly to the innerHTML of the specified element.</li>
87229      * </ul></div>
87230      */
87231     msgTarget: 'qtip',
87232
87233     /**
87234      * @cfg {String} activeError
87235      * If specified, then the component will be displayed with this value as its active error when
87236      * first rendered. Defaults to undefined. Use {@link #setActiveError} or {@link #unsetActiveError} to
87237      * change it after component creation.
87238      */
87239
87240
87241     /**
87242      * Performs initialization of this mixin. Component classes using this mixin should call this method
87243      * during their own initialization.
87244      */
87245     initLabelable: function() {
87246         this.addCls(this.formItemCls);
87247
87248         this.addEvents(
87249             /**
87250              * @event errorchange
87251              * Fires when the active error message is changed via {@link #setActiveError}.
87252              * @param {Ext.form.Labelable} this
87253              * @param {String} error The active error message
87254              */
87255             'errorchange'
87256         );
87257     },
87258
87259     /**
87260      * Returns the label for the field. Defaults to simply returning the {@link #fieldLabel} config. Can be
87261      * overridden to provide
87262      * @return {String} The configured field label, or empty string if not defined
87263      */
87264     getFieldLabel: function() {
87265         return this.fieldLabel || '';
87266     },
87267
87268     /**
87269      * @protected
87270      * Generates the arguments for the field decorations {@link #labelableRenderTpl rendering template}.
87271      * @return {Object} The template arguments
87272      */
87273     getLabelableRenderData: function() {
87274         var me = this,
87275             labelAlign = me.labelAlign,
87276             labelPad = me.labelPad,
87277             labelStyle;
87278
87279         // Calculate label styles up front rather than in the Field layout for speed; this
87280         // is safe because label alignment/width/pad are not expected to change.
87281         if (labelAlign === 'top') {
87282             labelStyle = 'margin-bottom:' + labelPad + 'px;';
87283         } else {
87284             labelStyle = 'margin-right:' + labelPad + 'px;';
87285             // Add the width for border-box browsers; will be set by the Field layout for content-box
87286             if (Ext.isBorderBox) {
87287                 labelStyle += 'width:' + me.labelWidth + 'px;';
87288             }
87289         }
87290
87291         return Ext.copyTo(
87292             {
87293                 inputId: me.getInputId(),
87294                 fieldLabel: me.getFieldLabel(),
87295                 labelStyle: labelStyle + (me.labelStyle || ''),
87296                 subTplMarkup: me.getSubTplMarkup()
87297             },
87298             me,
87299             'hideLabel,hideEmptyLabel,labelCls,fieldBodyCls,baseBodyCls,errorMsgCls,clearCls,labelSeparator',
87300             true
87301         );
87302     },
87303
87304     /**
87305      * @protected
87306      * Returns the additional {@link Ext.AbstractComponent#renderSelectors} for selecting the field
87307      * decoration elements from the rendered {@link #labelableRenderTpl}. Component classes using this mixin should
87308      * be sure and merge this method's result into the component's {@link Ext.AbstractComponent#renderSelectors}
87309      * before rendering.
87310      */
87311     getLabelableSelectors: function() {
87312         return {
87313             /**
87314              * @property labelEl
87315              * @type Ext.core.Element
87316              * The label Element for this component. Only available after the component has been rendered.
87317              */
87318             labelEl: 'label.' + this.labelCls,
87319
87320             /**
87321              * @property bodyEl
87322              * @type Ext.core.Element
87323              * The div Element wrapping the component's contents. Only available after the component has been rendered.
87324              */
87325             bodyEl: '.' + this.baseBodyCls,
87326
87327             /**
87328              * @property errorEl
87329              * @type Ext.core.Element
87330              * The div Element that will contain the component's error message(s). Note that depending on the
87331              * configured {@link #msgTarget}, this element may be hidden in favor of some other form of
87332              * presentation, but will always be present in the DOM for use by assistive technologies.
87333              */
87334             errorEl: '.' + this.errorMsgCls
87335         };
87336     },
87337
87338     /**
87339      * @protected
87340      * Gets the markup to be inserted into the outer template's bodyEl. Defaults to empty string, should
87341      * be implemented by classes including this mixin as needed.
87342      * @return {String} The markup to be inserted
87343      */
87344     getSubTplMarkup: function() {
87345         return '';
87346     },
87347
87348     /**
87349      * Get the input id, if any, for this component. This is used as the "for" attribute on the label element.
87350      * Implementing subclasses may also use this as e.g. the id for their own <tt>input</tt> element.
87351      * @return {String} The input id
87352      */
87353     getInputId: function() {
87354         return '';
87355     },
87356
87357     /**
87358      * Gets the active error message for this component, if any. This does not trigger
87359      * validation on its own, it merely returns any message that the component may already hold.
87360      * @return {String} The active error message on the component; if there is no error, an empty string is returned.
87361      */
87362     getActiveError : function() {
87363         return this.activeError || '';
87364     },
87365
87366     /**
87367      * Tells whether the field currently has an active error message. This does not trigger
87368      * validation on its own, it merely looks for any message that the component may already hold.
87369      * @return {Boolean}
87370      */
87371     hasActiveError: function() {
87372         return !!this.getActiveError();
87373     },
87374
87375     /**
87376      * Sets the active error message to the given string. This replaces the entire error message
87377      * contents with the given string. Also see {@link #setActiveErrors} which accepts an Array of
87378      * messages and formats them according to the {@link #activeErrorsTpl}.
87379      * @param {String} msg The error message
87380      */
87381     setActiveError: function(msg) {
87382         this.activeError = msg;
87383         this.activeErrors = [msg];
87384         this.renderActiveError();
87385     },
87386
87387     /**
87388      * Gets an Array of any active error messages currently applied to the field. This does not trigger
87389      * validation on its own, it merely returns any messages that the component may already hold.
87390      * @return {Array} The active error messages on the component; if there are no errors, an empty Array is returned.
87391      */
87392     getActiveErrors: function() {
87393         return this.activeErrors || [];
87394     },
87395
87396     /**
87397      * Set the active error message to an Array of error messages. The messages are formatted into
87398      * a single message string using the {@link #activeErrorsTpl}. Also see {@link #setActiveError}
87399      * which allows setting the entire error contents with a single string.
87400      * @param {Array} errors The error messages
87401      */
87402     setActiveErrors: function(errors) {
87403         this.activeErrors = errors;
87404         this.activeError = this.getTpl('activeErrorsTpl').apply({errors: errors});
87405         this.renderActiveError();
87406     },
87407
87408     /**
87409      * Clears the active error.
87410      */
87411     unsetActiveError: function() {
87412         delete this.activeError;
87413         delete this.activeErrors;
87414         this.renderActiveError();
87415     },
87416
87417     /**
87418      * @private
87419      * Updates the rendered DOM to match the current activeError. This only updates the content and
87420      * attributes, you'll have to call doComponentLayout to actually update the display.
87421      */
87422     renderActiveError: function() {
87423         var me = this,
87424             activeError = me.getActiveError(),
87425             hasError = !!activeError;
87426
87427         if (activeError !== me.lastActiveError) {
87428             me.fireEvent('errorchange', me, activeError);
87429             me.lastActiveError = activeError;
87430         }
87431
87432         if (me.rendered && !me.isDestroyed && !me.preventMark) {
87433             // Add/remove invalid class
87434             me.el[hasError ? 'addCls' : 'removeCls'](me.invalidCls);
87435
87436             // Update the aria-invalid attribute
87437             me.getActionEl().dom.setAttribute('aria-invalid', hasError);
87438
87439             // Update the errorEl with the error message text
87440             me.errorEl.dom.innerHTML = activeError;
87441         }
87442     },
87443
87444     /**
87445      * Applies a set of default configuration values to this Labelable instance. For each of the
87446      * properties in the given object, check if this component hasOwnProperty that config; if not
87447      * then it's inheriting a default value from its prototype and we should apply the default value.
87448      * @param {Object} defaults The defaults to apply to the object.
87449      */
87450     setFieldDefaults: function(defaults) {
87451         var me = this;
87452         Ext.iterate(defaults, function(key, val) {
87453             if (!me.hasOwnProperty(key)) {
87454                 me[key] = val;
87455             }
87456         });
87457     },
87458
87459     /**
87460      * @protected Calculate and return the natural width of the bodyEl. Override to provide custom logic.
87461      * Note for implementors: if at all possible this method should be overridden with a custom implementation
87462      * that can avoid anything that would cause the browser to reflow, e.g. querying offsetWidth.
87463      */
87464     getBodyNaturalWidth: function() {
87465         return this.bodyEl.getWidth();
87466     }
87467
87468 });
87469
87470 /**
87471  * @class Ext.form.field.Field
87472
87473 This mixin provides a common interface for the logical behavior and state of form fields, including:
87474
87475 - Getter and setter methods for field values
87476 - Events and methods for tracking value and validity changes
87477 - Methods for triggering validation
87478
87479 **NOTE**: When implementing custom fields, it is most likely that you will want to extend the {@link Ext.form.field.Base}
87480 component class rather than using this mixin directly, as BaseField contains additional logic for generating an
87481 actual DOM complete with {@link Ext.form.Labelable label and error message} display and a form input field,
87482 plus methods that bind the Field value getters and setters to the input field's value.
87483
87484 If you do want to implement this mixin directly and don't want to extend {@link Ext.form.field.Base}, then
87485 you will most likely want to override the following methods with custom implementations: {@link #getValue},
87486 {@link #setValue}, and {@link #getErrors}. Other methods may be overridden as needed but their base
87487 implementations should be sufficient for common cases. You will also need to make sure that {@link #initField}
87488 is called during the component's initialization.
87489
87490  * @markdown
87491  * @docauthor Jason Johnston <jason@sencha.com>
87492  */
87493 Ext.define('Ext.form.field.Field', {
87494
87495     /**
87496      * @property isFormField
87497      * @type {Boolean}
87498      * Flag denoting that this component is a Field. Always true.
87499      */
87500     isFormField : true,
87501
87502     /**
87503      * @cfg {Mixed} value A value to initialize this field with (defaults to undefined).
87504      */
87505     
87506     /**
87507      * @cfg {String} name The name of the field (defaults to undefined). By default this is used as the parameter
87508      * name when including the {@link #getSubmitData field value} in a {@link Ext.form.Basic#submit form submit()}.
87509      * To prevent the field from being included in the form submit, set {@link #submitValue} to <tt>false</tt>.
87510      */
87511
87512     /**
87513      * @cfg {Boolean} disabled True to disable the field (defaults to false). Disabled Fields will not be
87514      * {@link Ext.form.Basic#submit submitted}.</p>
87515      */
87516     disabled : false,
87517
87518     /**
87519      * @cfg {Boolean} submitValue Setting this to <tt>false</tt> will prevent the field from being
87520      * {@link Ext.form.Basic#submit submitted} even when it is not disabled. Defaults to <tt>true</tt>.
87521      */
87522     submitValue: true,
87523
87524     /**
87525      * @cfg {Boolean} validateOnChange
87526      * <p>Specifies whether this field should be validated immediately whenever a change in its value is detected.
87527      * Defaults to <tt>true</tt>. If the validation results in a change in the field's validity, a
87528      * {@link #validitychange} event will be fired. This allows the field to show feedback about the
87529      * validity of its contents immediately as the user is typing.</p>
87530      * <p>When set to <tt>false</tt>, feedback will not be immediate. However the form will still be validated
87531      * before submitting if the <tt>clientValidation</tt> option to {@link Ext.form.Basic#doAction} is
87532      * enabled, or if the field or form are validated manually.</p>
87533      * <p>See also {@link Ext.form.field.Base#checkChangeEvents}for controlling how changes to the field's value are detected.</p>
87534      */
87535     validateOnChange: true,
87536
87537     /**
87538      * @private
87539      */
87540     suspendCheckChange: 0,
87541
87542     /**
87543      * Initializes this Field mixin on the current instance. Components using this mixin should call
87544      * this method during their own initialization process.
87545      */
87546     initField: function() {
87547         this.addEvents(
87548             /**
87549              * @event change
87550              * Fires when a user-initiated change is detected in the value of the field.
87551              * @param {Ext.form.field.Field} this
87552              * @param {Mixed} newValue The new value
87553              * @param {Mixed} oldValue The original value
87554              */
87555             'change',
87556             /**
87557              * @event validitychange
87558              * Fires when a change in the field's validity is detected.
87559              * @param {Ext.form.field.Field} this
87560              * @param {Boolean} isValid Whether or not the field is now valid
87561              */
87562             'validitychange',
87563             /**
87564              * @event dirtychange
87565              * Fires when a change in the field's {@link #isDirty} state is detected.
87566              * @param {Ext.form.field.Field} this
87567              * @param {Boolean} isDirty Whether or not the field is now dirty
87568              */
87569             'dirtychange'
87570         );
87571
87572         this.initValue();
87573     },
87574
87575     /**
87576      * @protected
87577      * Initializes the field's value based on the initial config.
87578      */
87579     initValue: function() {
87580         var me = this;
87581
87582         /**
87583          * @property originalValue
87584          * @type Mixed
87585          * The original value of the field as configured in the {@link #value} configuration, or as loaded by
87586          * the last form load operation if the form's {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
87587          * setting is <code>true</code>.
87588          */
87589         me.originalValue = me.lastValue = me.value;
87590
87591         // Set the initial value - prevent validation on initial set
87592         me.suspendCheckChange++;
87593         me.setValue(me.value);
87594         me.suspendCheckChange--;
87595     },
87596
87597     /**
87598      * Returns the {@link Ext.form.field.Field#name name} attribute of the field. This is used as the parameter
87599      * name when including the field value in a {@link Ext.form.Basic#submit form submit()}.
87600      * @return {String} name The field {@link Ext.form.field.Field#name name}
87601      */
87602     getName: function() {
87603         return this.name;
87604     },
87605
87606     /**
87607      * Returns the current data value of the field. The type of value returned is particular to the type of the
87608      * particular field (e.g. a Date object for {@link Ext.form.field.Date}).
87609      * @return {Mixed} value The field value
87610      */
87611     getValue: function() {
87612         return this.value;
87613     },
87614     
87615     /**
87616      * Sets a data value into the field and runs the change detection and validation.
87617      * @param {Mixed} value The value to set
87618      * @return {Ext.form.field.Field} this
87619      */
87620     setValue: function(value) {
87621         var me = this;
87622         me.value = value;
87623         me.checkChange();
87624         return me;
87625     },
87626
87627     /**
87628      * Returns whether two field {@link #getValue values} are logically equal. Field implementations may override
87629      * this to provide custom comparison logic appropriate for the particular field's data type.
87630      * @param {Mixed} value1 The first value to compare
87631      * @param {Mixed} value2 The second value to compare
87632      * @return {Boolean} True if the values are equal, false if inequal.
87633      */
87634     isEqual: function(value1, value2) {
87635         return String(value1) === String(value2);
87636     },
87637
87638     /**
87639      * <p>Returns the parameter(s) that would be included in a standard form submit for this field. Typically this
87640      * will be an object with a single name-value pair, the name being this field's {@link #getName name} and the
87641      * value being its current stringified value. More advanced field implementations may return more than one
87642      * name-value pair.</p>
87643      * <p>Note that the values returned from this method are not guaranteed to have been successfully
87644      * {@link #validate validated}.</p>
87645      * @return {Object} A mapping of submit parameter names to values; each value should be a string, or an array
87646      * of strings if that particular name has multiple values. It can also return <tt>null</tt> if there are no
87647      * parameters to be submitted.
87648      */
87649     getSubmitData: function() {
87650         var me = this,
87651             data = null;
87652         if (!me.disabled && me.submitValue && !me.isFileUpload()) {
87653             data = {};
87654             data[me.getName()] = '' + me.getValue();
87655         }
87656         return data;
87657     },
87658
87659     /**
87660      * <p>Returns the value(s) that should be saved to the {@link Ext.data.Model} instance for this field, when
87661      * {@link Ext.form.Basic#updateRecord} is called. Typically this will be an object with a single name-value
87662      * pair, the name being this field's {@link #getName name} and the value being its current data value. More
87663      * advanced field implementations may return more than one name-value pair. The returned values will be
87664      * saved to the corresponding field names in the Model.</p>
87665      * <p>Note that the values returned from this method are not guaranteed to have been successfully
87666      * {@link #validate validated}.</p>
87667      * @return {Object} A mapping of submit parameter names to values; each value should be a string, or an array
87668      * of strings if that particular name has multiple values. It can also return <tt>null</tt> if there are no
87669      * parameters to be submitted.
87670      */
87671     getModelData: function() {
87672         var me = this,
87673             data = null;
87674         if (!me.disabled && !me.isFileUpload()) {
87675             data = {};
87676             data[me.getName()] = me.getValue();
87677         }
87678         return data;
87679     },
87680
87681     /**
87682      * Resets the current field value to the originally loaded value and clears any validation messages.
87683      * See {@link Ext.form.Basic}.{@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
87684      */
87685     reset : function(){
87686         var me = this;
87687         
87688         me.setValue(me.originalValue);
87689         me.clearInvalid();
87690         // delete here so we reset back to the original state
87691         delete me.wasValid;
87692     },
87693
87694     /**
87695      * Resets the field's {@link #originalValue} property so it matches the current {@link #getValue value}.
87696      * This is called by {@link Ext.form.Basic}.{@link Ext.form.Basic#setValues setValues} if the form's
87697      * {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad} property is set to true.
87698      */
87699     resetOriginalValue: function() {
87700         this.originalValue = this.getValue();
87701         this.checkDirty();
87702     },
87703
87704     /**
87705      * <p>Checks whether the value of the field has changed since the last time it was checked. If the value
87706      * has changed, it:</p>
87707      * <ol>
87708      * <li>Fires the {@link #change change event},</li>
87709      * <li>Performs validation if the {@link #validateOnChange} config is enabled, firing the
87710      * {@link #validationchange validationchange event} if the validity has changed, and</li>
87711      * <li>Checks the {@link #isDirty dirty state} of the field and fires the {@link #dirtychange dirtychange event}
87712      * if it has changed.</li>
87713      * </ol>
87714      */
87715     checkChange: function() {
87716         if (!this.suspendCheckChange) {
87717             var me = this,
87718                 newVal = me.getValue(),
87719                 oldVal = me.lastValue;
87720             if (!me.isEqual(newVal, oldVal) && !me.isDestroyed) {
87721                 me.lastValue = newVal;
87722                 me.fireEvent('change', me, newVal, oldVal);
87723                 me.onChange(newVal, oldVal);
87724             }
87725         }
87726     },
87727
87728     /**
87729      * @private
87730      * Called when the field's value changes. Performs validation if the {@link #validateOnChange}
87731      * config is enabled, and invokes the dirty check.
87732      */
87733     onChange: function(newVal, oldVal) {
87734         if (this.validateOnChange) {
87735             this.validate();
87736         }
87737         this.checkDirty();
87738     },
87739
87740     /**
87741      * <p>Returns true if the value of this Field has been changed from its {@link #originalValue}.
87742      * Will always return false if the field is disabled.</p>
87743      * <p>Note that if the owning {@link Ext.form.Basic form} was configured with
87744      * {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
87745      * then the {@link #originalValue} is updated when the values are loaded by
87746      * {@link Ext.form.Basic}.{@link Ext.form.Basic#setValues setValues}.</p>
87747      * @return {Boolean} True if this field has been changed from its original value (and
87748      * is not disabled), false otherwise.
87749      */
87750     isDirty : function() {
87751         var me = this;
87752         return !me.disabled && !me.isEqual(me.getValue(), me.originalValue);
87753     },
87754
87755     /**
87756      * Checks the {@link #isDirty} state of the field and if it has changed since the last time
87757      * it was checked, fires the {@link #dirtychange} event.
87758      */
87759     checkDirty: function() {
87760         var me = this,
87761             isDirty = me.isDirty();
87762         if (isDirty !== me.wasDirty) {
87763             me.fireEvent('dirtychange', me, isDirty);
87764             me.onDirtyChange(isDirty);
87765             me.wasDirty = isDirty;
87766         }
87767     },
87768
87769     /**
87770      * @private Called when the field's dirty state changes.
87771      * @param {Boolean} isDirty
87772      */
87773     onDirtyChange: Ext.emptyFn,
87774
87775     /**
87776      * <p>Runs this field's validators and returns an array of error messages for any validation failures.
87777      * This is called internally during validation and would not usually need to be used manually.</p>
87778      * <p>Each subclass should override or augment the return value to provide their own errors.</p>
87779      * @param {Mixed} value The value to get errors for (defaults to the current field value)
87780      * @return {Array} All error messages for this field; an empty Array if none.
87781      */
87782     getErrors: function(value) {
87783         return [];
87784     },
87785
87786     /**
87787      * <p>Returns whether or not the field value is currently valid by {@link #getErrors validating} the
87788      * field's current value. The {@link #validitychange} event will not be fired; use {@link #validate}
87789      * instead if you want the event to fire. <b>Note</b>: {@link #disabled} fields are always treated as valid.</p>
87790      * <p>Implementations are encouraged to ensure that this method does not have side-effects such as
87791      * triggering error message display.</p>
87792      * @return {Boolean} True if the value is valid, else false
87793      */
87794     isValid : function() {
87795         var me = this;
87796         return me.disabled || Ext.isEmpty(me.getErrors());
87797     },
87798
87799     /**
87800      * <p>Returns whether or not the field value is currently valid by {@link #getErrors validating} the
87801      * field's current value, and fires the {@link #validitychange} event if the field's validity has
87802      * changed since the last validation. <b>Note</b>: {@link #disabled} fields are always treated as valid.</p>
87803      * <p>Custom implementations of this method are allowed to have side-effects such as triggering error
87804      * message display. To validate without side-effects, use {@link #isValid}.</p>
87805      * @return {Boolean} True if the value is valid, else false
87806      */
87807     validate : function() {
87808         var me = this,
87809             isValid = me.isValid();
87810         if (isValid !== me.wasValid) {
87811             me.wasValid = isValid;
87812             me.fireEvent('validitychange', me, isValid);
87813         }
87814         return isValid;
87815     },
87816
87817     /**
87818      * A utility for grouping a set of modifications which may trigger value changes into a single
87819      * transaction, to prevent excessive firing of {@link #change} events. This is useful for instance
87820      * if the field has sub-fields which are being updated as a group; you don't want the container
87821      * field to check its own changed state for each subfield change.
87822      * @param fn A function containing the transaction code
87823      */
87824     batchChanges: function(fn) {
87825         this.suspendCheckChange++;
87826         fn();
87827         this.suspendCheckChange--;
87828         this.checkChange();
87829     },
87830
87831     /**
87832      * Returns whether this Field is a file upload field; if it returns true, forms will use
87833      * special techniques for {@link Ext.form.Basic#submit submitting the form} via AJAX. See
87834      * {@link Ext.form.Basic#hasUpload} for details. If this returns true, the {@link #extractFileInput}
87835      * method must also be implemented to return the corresponding file input element.
87836      * @return {Boolean}
87837      */
87838     isFileUpload: function() {
87839         return false;
87840     },
87841
87842     /**
87843      * Only relevant if the instance's {@link #isFileUpload} method returns true. Returns a reference
87844      * to the file input DOM element holding the user's selected file. The input will be appended into
87845      * the submission form and will not be returned, so this method should also create a replacement.
87846      * @return {HTMLInputElement}
87847      */
87848     extractFileInput: function() {
87849         return null;
87850     },
87851
87852     /**
87853      * <p>Associate one or more error messages with this field. Components using this mixin should implement
87854      * this method to update the component's rendering to display the messages.</p>
87855      * <p><b>Note</b>: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to
87856      * return <code>false</code> if the value does <i>pass</i> validation. So simply marking a Field as invalid
87857      * will not prevent submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation}
87858      * option set.</p>
87859      * @param {String/Array} errors The error message(s) for the field.
87860      */
87861     markInvalid: Ext.emptyFn,
87862
87863     /**
87864      * <p>Clear any invalid styles/messages for this field. Components using this mixin should implement
87865      * this method to update the components rendering to clear any existing messages.</p>
87866      * <p><b>Note</b>: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to
87867      * return <code>true</code> if the value does not <i>pass</i> validation. So simply clearing a field's errors
87868      * will not necessarily allow submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation}
87869      * option set.</p>
87870      */
87871     clearInvalid: Ext.emptyFn
87872
87873 });
87874
87875 /**
87876  * @class Ext.layout.component.field.Field
87877  * @extends Ext.layout.component.Component
87878  * Layout class for components with {@link Ext.form.Labelable field labeling}, handling the sizing and alignment of
87879  * the form control, label, and error message treatment.
87880  * @private
87881  */
87882 Ext.define('Ext.layout.component.field.Field', {
87883
87884     /* Begin Definitions */
87885
87886     alias: ['layout.field'],
87887
87888     extend: 'Ext.layout.component.Component',
87889
87890     uses: ['Ext.tip.QuickTip', 'Ext.util.TextMetrics'],
87891
87892     /* End Definitions */
87893
87894     type: 'field',
87895
87896     beforeLayout: function(width, height) {
87897         var me = this;
87898         return me.callParent(arguments) || (!me.owner.preventMark && me.activeError !== me.owner.getActiveError());
87899     },
87900
87901     onLayout: function(width, height) {
87902         var me = this,
87903             owner = me.owner,
87904             labelStrategy = me.getLabelStrategy(),
87905             errorStrategy = me.getErrorStrategy(),
87906             isDefined = Ext.isDefined,
87907             isNumber = Ext.isNumber,
87908             lastSize, autoWidth, autoHeight, info, undef;
87909
87910         lastSize = me.lastComponentSize || {};
87911         if (!isDefined(width)) {
87912             width = lastSize.width;
87913             if (width < 0) { //first pass lastComponentSize.width is -Infinity
87914                 width = undef;
87915             }
87916         }
87917         if (!isDefined(height)) {
87918             height = lastSize.height;
87919             if (height < 0) { //first pass lastComponentSize.height is -Infinity
87920                 height = undef;
87921             }
87922         }
87923         autoWidth = !isNumber(width);
87924         autoHeight = !isNumber(height);
87925
87926         info = {
87927             autoWidth: autoWidth,
87928             autoHeight: autoHeight,
87929             width: autoWidth ? owner.getBodyNaturalWidth() : width, //always give a pixel width
87930             height: height,
87931
87932             // insets for the bodyEl from each side of the component layout area
87933             insets: {
87934                 top: 0,
87935                 right: 0,
87936                 bottom: 0,
87937                 left: 0
87938             }
87939         };
87940
87941         // NOTE the order of calculating insets and setting styles here is very important; we must first
87942         // calculate and set horizontal layout alone, as the horizontal sizing of elements can have an impact
87943         // on the vertical sizes due to wrapping, then calculate and set the vertical layout.
87944
87945         // perform preparation on the label and error (setting css classes, qtips, etc.)
87946         labelStrategy.prepare(owner, info);
87947         errorStrategy.prepare(owner, info);
87948
87949         // calculate the horizontal insets for the label and error
87950         labelStrategy.adjustHorizInsets(owner, info);
87951         errorStrategy.adjustHorizInsets(owner, info);
87952
87953         // set horizontal styles for label and error based on the current insets
87954         labelStrategy.layoutHoriz(owner, info);
87955         errorStrategy.layoutHoriz(owner, info);
87956
87957         // calculate the vertical insets for the label and error
87958         labelStrategy.adjustVertInsets(owner, info);
87959         errorStrategy.adjustVertInsets(owner, info);
87960
87961         // set vertical styles for label and error based on the current insets
87962         labelStrategy.layoutVert(owner, info);
87963         errorStrategy.layoutVert(owner, info);
87964
87965         // perform sizing of the elements based on the final dimensions and insets
87966         if (autoWidth && autoHeight) {
87967             // Don't use setTargetSize if auto-sized, so the calculated size is not reused next time
87968             me.setElementSize(owner.el, info.width, info.height);
87969         } else {
87970             me.setTargetSize(info.width, info.height);
87971         }
87972         me.sizeBody(info);
87973
87974         me.activeError = owner.getActiveError();
87975     },
87976
87977
87978     /**
87979      * Perform sizing and alignment of the bodyEl (and children) to match the calculated insets.
87980      */
87981     sizeBody: function(info) {
87982         var me = this,
87983             owner = me.owner,
87984             insets = info.insets,
87985             totalWidth = info.width,
87986             totalHeight = info.height,
87987             width = Ext.isNumber(totalWidth) ? totalWidth - insets.left - insets.right : totalWidth,
87988             height = Ext.isNumber(totalHeight) ? totalHeight - insets.top - insets.bottom : totalHeight;
87989
87990         // size the bodyEl
87991         me.setElementSize(owner.bodyEl, width, height);
87992
87993         // size the bodyEl's inner contents if necessary
87994         me.sizeBodyContents(width, height);
87995     },
87996
87997     /**
87998      * Size the contents of the field body, given the full dimensions of the bodyEl. Does nothing by
87999      * default, subclasses can override to handle their specific contents.
88000      * @param {Number} width The bodyEl width
88001      * @param {Number} height The bodyEl height
88002      */
88003     sizeBodyContents: Ext.emptyFn,
88004
88005
88006     /**
88007      * Return the set of strategy functions from the {@link #labelStrategies labelStrategies collection}
88008      * that is appropriate for the field's {@link Ext.form.field.Field#labelAlign labelAlign} config.
88009      */
88010     getLabelStrategy: function() {
88011         var me = this,
88012             strategies = me.labelStrategies,
88013             labelAlign = me.owner.labelAlign;
88014         return strategies[labelAlign] || strategies.base;
88015     },
88016
88017     /**
88018      * Return the set of strategy functions from the {@link #errorStrategies errorStrategies collection}
88019      * that is appropriate for the field's {@link Ext.form.field.Field#msgTarget msgTarget} config.
88020      */
88021     getErrorStrategy: function() {
88022         var me = this,
88023             owner = me.owner,
88024             strategies = me.errorStrategies,
88025             msgTarget = owner.msgTarget;
88026         return !owner.preventMark && Ext.isString(msgTarget) ?
88027                 (strategies[msgTarget] || strategies.elementId) :
88028                 strategies.none;
88029     },
88030
88031
88032
88033     /**
88034      * Collection of named strategies for laying out and adjusting labels to accommodate error messages.
88035      * An appropriate one will be chosen based on the owner field's {@link Ext.form.field.Field#labelAlign} config.
88036      */
88037     labelStrategies: (function() {
88038         var applyIf = Ext.applyIf,
88039             emptyFn = Ext.emptyFn,
88040             base = {
88041                 prepare: function(owner, info) {
88042                     var cls = owner.labelCls + '-' + owner.labelAlign,
88043                         labelEl = owner.labelEl;
88044                     if (labelEl && !labelEl.hasCls(cls)) {
88045                         labelEl.addCls(cls);
88046                     }
88047                 },
88048                 adjustHorizInsets: emptyFn,
88049                 adjustVertInsets: emptyFn,
88050                 layoutHoriz: emptyFn,
88051                 layoutVert: emptyFn
88052             },
88053             left = applyIf({
88054                 prepare: function(owner, info) {
88055                     base.prepare(owner, info);
88056                     // If auto width, add the label width to the body's natural width.
88057                     if (info.autoWidth) {
88058                         info.width += (!owner.labelEl ? 0 : owner.labelWidth + owner.labelPad);
88059                     }
88060                 },
88061                 adjustHorizInsets: function(owner, info) {
88062                     if (owner.labelEl) {
88063                         info.insets.left += owner.labelWidth + owner.labelPad;
88064                     }
88065                 },
88066                 layoutHoriz: function(owner, info) {
88067                     // For content-box browsers we can't rely on Labelable.js#getLabelableRenderData
88068                     // setting the width style because it needs to account for the final calculated
88069                     // padding/border styles for the label. So we set the width programmatically here to
88070                     // normalize content-box sizing, while letting border-box browsers use the original
88071                     // width style.
88072                     var labelEl = owner.labelEl;
88073                     if (labelEl && !owner.isLabelSized && !Ext.isBorderBox) {
88074                         labelEl.setWidth(owner.labelWidth);
88075                         owner.isLabelSized = true;
88076                     }
88077                 }
88078             }, base);
88079
88080
88081         return {
88082             base: base,
88083
88084             /**
88085              * Label displayed above the bodyEl
88086              */
88087             top: applyIf({
88088                 adjustVertInsets: function(owner, info) {
88089                     var labelEl = owner.labelEl;
88090                     if (labelEl) {
88091                         info.insets.top += Ext.util.TextMetrics.measure(labelEl, owner.fieldLabel, info.width).height +
88092                                            labelEl.getFrameWidth('tb') + owner.labelPad;
88093                     }
88094                 }
88095             }, base),
88096
88097             /**
88098              * Label displayed to the left of the bodyEl
88099              */
88100             left: left,
88101
88102             /**
88103              * Same as left, only difference is text-align in CSS
88104              */
88105             right: left
88106         };
88107     })(),
88108
88109
88110
88111     /**
88112      * Collection of named strategies for laying out and adjusting insets to accommodate error messages.
88113      * An appropriate one will be chosen based on the owner field's {@link Ext.form.field.Field#msgTarget} config.
88114      */
88115     errorStrategies: (function() {
88116         function setDisplayed(el, displayed) {
88117             var wasDisplayed = el.getStyle('display') !== 'none';
88118             if (displayed !== wasDisplayed) {
88119                 el.setDisplayed(displayed);
88120             }
88121         }
88122
88123         function setStyle(el, name, value) {
88124             if (el.getStyle(name) !== value) {
88125                 el.setStyle(name, value);
88126             }
88127         }
88128
88129         var applyIf = Ext.applyIf,
88130             emptyFn = Ext.emptyFn,
88131             base = {
88132                 prepare: function(owner) {
88133                     setDisplayed(owner.errorEl, false);
88134                 },
88135                 adjustHorizInsets: emptyFn,
88136                 adjustVertInsets: emptyFn,
88137                 layoutHoriz: emptyFn,
88138                 layoutVert: emptyFn
88139             };
88140
88141         return {
88142             none: base,
88143
88144             /**
88145              * Error displayed as icon (with QuickTip on hover) to right of the bodyEl
88146              */
88147             side: applyIf({
88148                 prepare: function(owner) {
88149                     var errorEl = owner.errorEl;
88150                     errorEl.addCls(Ext.baseCSSPrefix + 'form-invalid-icon');
88151                     Ext.layout.component.field.Field.initTip();
88152                     errorEl.dom.setAttribute('data-errorqtip', owner.getActiveError() || '');
88153                     setDisplayed(errorEl, owner.hasActiveError());
88154                 },
88155                 adjustHorizInsets: function(owner, info) {
88156                     if (owner.autoFitErrors && owner.hasActiveError()) {
88157                         info.insets.right += owner.errorEl.getWidth();
88158                     }
88159                 },
88160                 layoutHoriz: function(owner, info) {
88161                     if (owner.hasActiveError()) {
88162                         setStyle(owner.errorEl, 'left', info.width - info.insets.right + 'px');
88163                     }
88164                 },
88165                 layoutVert: function(owner, info) {
88166                     if (owner.hasActiveError()) {
88167                         setStyle(owner.errorEl, 'top', info.insets.top + 'px');
88168                     }
88169                 }
88170             }, base),
88171
88172             /**
88173              * Error message displayed underneath the bodyEl
88174              */
88175             under: applyIf({
88176                 prepare: function(owner) {
88177                     var errorEl = owner.errorEl,
88178                         cls = Ext.baseCSSPrefix + 'form-invalid-under';
88179                     if (!errorEl.hasCls(cls)) {
88180                         errorEl.addCls(cls);
88181                     }
88182                     setDisplayed(errorEl, owner.hasActiveError());
88183                 },
88184                 adjustVertInsets: function(owner, info) {
88185                     if (owner.autoFitErrors) {
88186                         info.insets.bottom += owner.errorEl.getHeight();
88187                     }
88188                 },
88189                 layoutHoriz: function(owner, info) {
88190                     var errorEl = owner.errorEl,
88191                         insets = info.insets;
88192
88193                     setStyle(errorEl, 'width', info.width - insets.right - insets.left + 'px');
88194                     setStyle(errorEl, 'marginLeft', insets.left + 'px');
88195                 }
88196             }, base),
88197
88198             /**
88199              * Error displayed as QuickTip on hover of the field container
88200              */
88201             qtip: applyIf({
88202                 prepare: function(owner) {
88203                     setDisplayed(owner.errorEl, false);
88204                     Ext.layout.component.field.Field.initTip();
88205                     owner.getActionEl().dom.setAttribute('data-errorqtip', owner.getActiveError() || '');
88206                 }
88207             }, base),
88208
88209             /**
88210              * Error displayed as title tip on hover of the field container
88211              */
88212             title: applyIf({
88213                 prepare: function(owner) {
88214                     setDisplayed(owner.errorEl, false);
88215                     owner.el.dom.title = owner.getActiveError() || '';
88216                 }
88217             }, base),
88218
88219             /**
88220              * Error message displayed as content of an element with a given id elsewhere in the app
88221              */
88222             elementId: applyIf({
88223                 prepare: function(owner) {
88224                     setDisplayed(owner.errorEl, false);
88225                     var targetEl = Ext.fly(owner.msgTarget);
88226                     if (targetEl) {
88227                         targetEl.dom.innerHTML = owner.getActiveError() || '';
88228                         targetEl.setDisplayed(owner.hasActiveError());
88229                     }
88230                 }
88231             }, base)
88232         };
88233     })(),
88234
88235     statics: {
88236         /**
88237          * Use a custom QuickTip instance separate from the main QuickTips singleton, so that we
88238          * can give it a custom frame style. Responds to errorqtip rather than the qtip property.
88239          */
88240         initTip: function() {
88241             var tip = this.tip;
88242             if (!tip) {
88243                 tip = this.tip = Ext.create('Ext.tip.QuickTip', {
88244                     baseCls: Ext.baseCSSPrefix + 'form-invalid-tip',
88245                     renderTo: Ext.getBody()
88246                 });
88247                 tip.tagConfig = Ext.apply({}, {attribute: 'errorqtip'}, tip.tagConfig);
88248             }
88249         },
88250
88251         /**
88252          * Destroy the error tip instance.
88253          */
88254         destroyTip: function() {
88255             var tip = this.tip;
88256             if (tip) {
88257                 tip.destroy();
88258                 delete this.tip;
88259             }
88260         }
88261     }
88262
88263 });
88264
88265 /**
88266  * @class Ext.form.field.VTypes
88267  * <p>This is a singleton object which contains a set of commonly used field validation functions.
88268  * The validations provided are basic and intended to be easily customizable and extended.</p>
88269  * <p>To add custom VTypes specify the <code>{@link Ext.form.field.Text#vtype vtype}</code> validation
88270  * test function, and optionally specify any corresponding error text to display and any keystroke
88271  * filtering mask to apply. For example:</p>
88272  * <pre><code>
88273 // custom Vtype for vtype:'time'
88274 var timeTest = /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i;
88275 Ext.apply(Ext.form.field.VTypes, {
88276     //  vtype validation function
88277     time: function(val, field) {
88278         return timeTest.test(val);
88279     },
88280     // vtype Text property: The error text to display when the validation function returns false
88281     timeText: 'Not a valid time.  Must be in the format "12:34 PM".',
88282     // vtype Mask property: The keystroke filter mask
88283     timeMask: /[\d\s:amp]/i
88284 });
88285  * </code></pre>
88286  * Another example:
88287  * <pre><code>
88288 // custom Vtype for vtype:'IPAddress'
88289 Ext.apply(Ext.form.field.VTypes, {
88290     IPAddress:  function(v) {
88291         return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
88292     },
88293     IPAddressText: 'Must be a numeric IP address',
88294     IPAddressMask: /[\d\.]/i
88295 });
88296  * </code></pre>
88297  * @singleton
88298  */
88299 Ext.define('Ext.form.field.VTypes', (function(){
88300     // closure these in so they are only created once.
88301     var alpha = /^[a-zA-Z_]+$/,
88302         alphanum = /^[a-zA-Z0-9_]+$/,
88303         email = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/,
88304         url = /(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
88305
88306     // All these messages and functions are configurable
88307     return {
88308         singleton: true,
88309         alternateClassName: 'Ext.form.VTypes',
88310
88311         /**
88312          * The function used to validate email addresses.  Note that this is a very basic validation -- complete
88313          * validation per the email RFC specifications is very complex and beyond the scope of this class, although
88314          * this function can be overridden if a more comprehensive validation scheme is desired.  See the validation
88315          * section of the <a href="http://en.wikipedia.org/wiki/E-mail_address">Wikipedia article on email addresses</a>
88316          * for additional information.  This implementation is intended to validate the following emails:<tt>
88317          * 'barney@example.de', 'barney.rubble@example.com', 'barney-rubble@example.coop', 'barney+rubble@example.com'
88318          * </tt>.
88319          * @param {String} value The email address
88320          * @return {Boolean} true if the RegExp test passed, and false if not.
88321          */
88322         'email' : function(v){
88323             return email.test(v);
88324         },
88325         /**
88326          * The error text to display when the email validation function returns false.  Defaults to:
88327          * <tt>'This field should be an e-mail address in the format "user@example.com"'</tt>
88328          * @type String
88329          */
88330         'emailText' : 'This field should be an e-mail address in the format "user@example.com"',
88331         /**
88332          * The keystroke filter mask to be applied on email input.  See the {@link #email} method for
88333          * information about more complex email validation. Defaults to:
88334          * <tt>/[a-z0-9_\.\-@]/i</tt>
88335          * @type RegExp
88336          */
88337         'emailMask' : /[a-z0-9_\.\-@\+]/i,
88338
88339         /**
88340          * The function used to validate URLs
88341          * @param {String} value The URL
88342          * @return {Boolean} true if the RegExp test passed, and false if not.
88343          */
88344         'url' : function(v){
88345             return url.test(v);
88346         },
88347         /**
88348          * The error text to display when the url validation function returns false.  Defaults to:
88349          * <tt>'This field should be a URL in the format "http:/'+'/www.example.com"'</tt>
88350          * @type String
88351          */
88352         'urlText' : 'This field should be a URL in the format "http:/'+'/www.example.com"',
88353
88354         /**
88355          * The function used to validate alpha values
88356          * @param {String} value The value
88357          * @return {Boolean} true if the RegExp test passed, and false if not.
88358          */
88359         'alpha' : function(v){
88360             return alpha.test(v);
88361         },
88362         /**
88363          * The error text to display when the alpha validation function returns false.  Defaults to:
88364          * <tt>'This field should only contain letters and _'</tt>
88365          * @type String
88366          */
88367         'alphaText' : 'This field should only contain letters and _',
88368         /**
88369          * The keystroke filter mask to be applied on alpha input.  Defaults to:
88370          * <tt>/[a-z_]/i</tt>
88371          * @type RegExp
88372          */
88373         'alphaMask' : /[a-z_]/i,
88374
88375         /**
88376          * The function used to validate alphanumeric values
88377          * @param {String} value The value
88378          * @return {Boolean} true if the RegExp test passed, and false if not.
88379          */
88380         'alphanum' : function(v){
88381             return alphanum.test(v);
88382         },
88383         /**
88384          * The error text to display when the alphanumeric validation function returns false.  Defaults to:
88385          * <tt>'This field should only contain letters, numbers and _'</tt>
88386          * @type String
88387          */
88388         'alphanumText' : 'This field should only contain letters, numbers and _',
88389         /**
88390          * The keystroke filter mask to be applied on alphanumeric input.  Defaults to:
88391          * <tt>/[a-z0-9_]/i</tt>
88392          * @type RegExp
88393          */
88394         'alphanumMask' : /[a-z0-9_]/i
88395     };
88396 })());
88397
88398 /**
88399  * @private
88400  * @class Ext.layout.component.field.Text
88401  * @extends Ext.layout.component.field.Field
88402  * Layout class for {@link Ext.form.field.Text} fields. Handles sizing the input field.
88403  */
88404 Ext.define('Ext.layout.component.field.Text', {
88405     extend: 'Ext.layout.component.field.Field',
88406     alias: 'layout.textfield',
88407     requires: ['Ext.util.TextMetrics'],
88408
88409     type: 'textfield',
88410
88411
88412     /**
88413      * Allow layout to proceed if the {@link Ext.form.field.Text#grow} config is enabled and the value has
88414      * changed since the last layout.
88415      */
88416     beforeLayout: function(width, height) {
88417         var me = this,
88418             owner = me.owner,
88419             lastValue = this.lastValue,
88420             value = owner.getRawValue();
88421         this.lastValue = value;
88422         return me.callParent(arguments) || (owner.grow && value !== lastValue);
88423     },
88424
88425
88426     /**
88427      * Size the field body contents given the total dimensions of the bodyEl, taking into account the optional
88428      * {@link Ext.form.field.Text#grow} configurations.
88429      * @param {Number} width The bodyEl width
88430      * @param {Number} height The bodyEl height
88431      */
88432     sizeBodyContents: function(width, height) {
88433         var size = this.adjustForGrow(width, height);
88434         this.setElementSize(this.owner.inputEl, size[0], size[1]);
88435     },
88436
88437
88438     /**
88439      * Given the target bodyEl dimensions, adjust them if necessary to return the correct final
88440      * size based on the text field's {@link Ext.form.field.Text#grow grow config}.
88441      * @param {Number} width The bodyEl width
88442      * @param {Number} height The bodyEl height
88443      * @return {Array} [inputElWidth, inputElHeight]
88444      */
88445     adjustForGrow: function(width, height) {
88446         var me = this,
88447             owner = me.owner,
88448             inputEl, value, calcWidth,
88449             result = [width, height];
88450
88451         if (owner.grow) {
88452             inputEl = owner.inputEl;
88453
88454             // Find the width that contains the whole text value
88455             value = (inputEl.dom.value || (owner.hasFocus ? '' : owner.emptyText) || '') + owner.growAppend;
88456             calcWidth = inputEl.getTextWidth(value) + inputEl.getBorderWidth("lr") + inputEl.getPadding("lr");
88457
88458             // Constrain
88459             result[0] = Ext.Number.constrain(calcWidth, owner.growMin,
88460                     Math.max(owner.growMin, Math.min(owner.growMax, Ext.isNumber(width) ? width : Infinity)));
88461         }
88462
88463         return result;
88464     }
88465
88466 });
88467
88468 /**
88469  * @private
88470  * @class Ext.layout.component.field.TextArea
88471  * @extends Ext.layout.component.field.Field
88472  * Layout class for {@link Ext.form.field.TextArea} fields. Handles sizing the textarea field.
88473  */
88474 Ext.define('Ext.layout.component.field.TextArea', {
88475     extend: 'Ext.layout.component.field.Text',
88476     alias: 'layout.textareafield',
88477
88478     type: 'textareafield',
88479
88480
88481     /**
88482      * Given the target bodyEl dimensions, adjust them if necessary to return the correct final
88483      * size based on the text field's {@link Ext.form.field.Text#grow grow config}. Overrides the
88484      * textfield layout's implementation to handle height rather than width.
88485      * @param {Number} width The bodyEl width
88486      * @param {Number} height The bodyEl height
88487      * @return {Array} [inputElWidth, inputElHeight]
88488      */
88489     adjustForGrow: function(width, height) {
88490         var me = this,
88491             owner = me.owner,
88492             inputEl, value, max,
88493             curWidth, curHeight, calcHeight,
88494             result = [width, height];
88495
88496         if (owner.grow) {
88497             inputEl = owner.inputEl;
88498             curWidth = inputEl.getWidth(true); //subtract border/padding to get the available width for the text
88499             curHeight = inputEl.getHeight();
88500
88501             // Get and normalize the field value for measurement
88502             value = inputEl.dom.value || '&#160;';
88503             value += owner.growAppend;
88504
88505             // Translate newlines to <br> tags
88506             value = value.replace(/\n/g, '<br>');
88507
88508             // Find the height that contains the whole text value
88509             calcHeight = Ext.util.TextMetrics.measure(inputEl, value, curWidth).height +
88510                          inputEl.getBorderWidth("tb") + inputEl.getPadding("tb");
88511
88512             // Constrain
88513             max = owner.growMax;
88514             if (Ext.isNumber(height)) {
88515                 max = Math.min(max, height);
88516             }
88517             result[1] = Ext.Number.constrain(calcHeight, owner.growMin, max);
88518         }
88519
88520         return result;
88521     }
88522
88523 });
88524 /**
88525  * @class Ext.layout.container.Anchor
88526  * @extends Ext.layout.container.Container
88527  * <p>This is a layout that enables anchoring of contained elements relative to the container's dimensions.
88528  * If the container is resized, all anchored items are automatically rerendered according to their
88529  * <b><tt>{@link #anchor}</tt></b> rules.</p>
88530  * <p>This class is intended to be extended or created via the layout: 'anchor' {@link Ext.layout.container.AbstractContainer#layout}
88531  * config, and should generally not need to be created directly via the new keyword.</p>
88532  * <p>AnchorLayout does not have any direct config options (other than inherited ones). By default,
88533  * AnchorLayout will calculate anchor measurements based on the size of the container itself. However, the
88534  * container using the AnchorLayout can supply an anchoring-specific config property of <b>anchorSize</b>.
88535  * If anchorSize is specifed, the layout will use it as a virtual container for the purposes of calculating
88536  * anchor measurements based on it instead, allowing the container to be sized independently of the anchoring
88537  * logic if necessary.  
88538  * {@img Ext.layout.container.Anchor/Ext.layout.container.Anchor.png Ext.layout.container.Anchor container layout}
88539  * For example:
88540         Ext.create('Ext.Panel', {
88541                 width: 500,
88542                 height: 400,
88543                 title: "AnchorLayout Panel",
88544                 layout: 'anchor',
88545                 renderTo: Ext.getBody(),
88546                 items: [{
88547                         xtype: 'panel',
88548                         title: '75% Width and 20% Height',
88549                         anchor: '75% 20%'
88550                 },{
88551                         xtype: 'panel',
88552                         title: 'Offset -300 Width & -200 Height',
88553                         anchor: '-300 -200'             
88554                 },{
88555                         xtype: 'panel',
88556                         title: 'Mixed Offset and Percent',
88557                         anchor: '-250 20%'
88558                 }]
88559         });
88560  */
88561
88562 Ext.define('Ext.layout.container.Anchor', {
88563
88564     /* Begin Definitions */
88565
88566     alias: 'layout.anchor',
88567     extend: 'Ext.layout.container.Container',
88568     alternateClassName: 'Ext.layout.AnchorLayout',
88569
88570     /* End Definitions */
88571
88572     /**
88573      * @cfg {String} anchor
88574      * <p>This configuation option is to be applied to <b>child <tt>items</tt></b> of a container managed by
88575      * this layout (ie. configured with <tt>layout:'anchor'</tt>).</p><br/>
88576      *
88577      * <p>This value is what tells the layout how an item should be anchored to the container. <tt>items</tt>
88578      * added to an AnchorLayout accept an anchoring-specific config property of <b>anchor</b> which is a string
88579      * containing two values: the horizontal anchor value and the vertical anchor value (for example, '100% 50%').
88580      * The following types of anchor values are supported:<div class="mdetail-params"><ul>
88581      *
88582      * <li><b>Percentage</b> : Any value between 1 and 100, expressed as a percentage.<div class="sub-desc">
88583      * The first anchor is the percentage width that the item should take up within the container, and the
88584      * second is the percentage height.  For example:<pre><code>
88585 // two values specified
88586 anchor: '100% 50%' // render item complete width of the container and
88587                    // 1/2 height of the container
88588 // one value specified
88589 anchor: '100%'     // the width value; the height will default to auto
88590      * </code></pre></div></li>
88591      *
88592      * <li><b>Offsets</b> : Any positive or negative integer value.<div class="sub-desc">
88593      * This is a raw adjustment where the first anchor is the offset from the right edge of the container,
88594      * and the second is the offset from the bottom edge. For example:<pre><code>
88595 // two values specified
88596 anchor: '-50 -100' // render item the complete width of the container
88597                    // minus 50 pixels and
88598                    // the complete height minus 100 pixels.
88599 // one value specified
88600 anchor: '-50'      // anchor value is assumed to be the right offset value
88601                    // bottom offset will default to 0
88602      * </code></pre></div></li>
88603      *
88604      * <li><b>Sides</b> : Valid values are <tt>'right'</tt> (or <tt>'r'</tt>) and <tt>'bottom'</tt>
88605      * (or <tt>'b'</tt>).<div class="sub-desc">
88606      * Either the container must have a fixed size or an anchorSize config value defined at render time in
88607      * order for these to have any effect.</div></li>
88608      *
88609      * <li><b>Mixed</b> : <div class="sub-desc">
88610      * Anchor values can also be mixed as needed.  For example, to render the width offset from the container
88611      * right edge by 50 pixels and 75% of the container's height use:
88612      * <pre><code>
88613 anchor: '-50 75%'
88614      * </code></pre></div></li>
88615      *
88616      *
88617      * </ul></div>
88618      */
88619
88620     type: 'anchor',
88621
88622     /**
88623      * @cfg {String} defaultAnchor
88624      *
88625      * default anchor for all child container items applied if no anchor or specific width is set on the child item.  Defaults to '100%'.
88626      *
88627      */
88628     defaultAnchor: '100%',
88629
88630     parseAnchorRE: /^(r|right|b|bottom)$/i,
88631
88632     // private
88633     onLayout: function() {
88634         this.callParent(arguments);
88635
88636         var me = this,
88637             size = me.getLayoutTargetSize(),
88638             owner = me.owner,
88639             target = me.getTarget(),
88640             ownerWidth = size.width,
88641             ownerHeight = size.height,
88642             overflow = target.getStyle('overflow'),
88643             components = me.getVisibleItems(owner),
88644             len = components.length,
88645             boxes = [],
88646             box, newTargetSize, anchorWidth, anchorHeight, component, anchorSpec, calcWidth, calcHeight,
88647             anchorsArray, anchor, i, el;
88648
88649         if (ownerWidth < 20 && ownerHeight < 20) {
88650             return;
88651         }
88652
88653         // Anchor layout uses natural HTML flow to arrange the child items.
88654         // To ensure that all browsers (I'm looking at you IE!) add the bottom margin of the last child to the
88655         // containing element height, we create a zero-sized element with style clear:both to force a "new line"
88656         if (!me.clearEl) {
88657             me.clearEl = target.createChild({
88658                 cls: Ext.baseCSSPrefix + 'clear',
88659                 role: 'presentation'
88660             });
88661         }
88662
88663         // find the container anchoring size
88664         if (owner.anchorSize) {
88665             if (typeof owner.anchorSize == 'number') {
88666                 anchorWidth = owner.anchorSize;
88667             }
88668             else {
88669                 anchorWidth = owner.anchorSize.width;
88670                 anchorHeight = owner.anchorSize.height;
88671             }
88672         }
88673         else {
88674             anchorWidth = owner.initialConfig.width;
88675             anchorHeight = owner.initialConfig.height;
88676         }
88677
88678         // Work around WebKit RightMargin bug. We're going to inline-block all the children only ONCE and remove it when we're done
88679         if (!Ext.supports.RightMargin) {
88680             target.addCls(Ext.baseCSSPrefix + 'inline-children');
88681         }
88682
88683         for (i = 0; i < len; i++) {
88684             component = components[i];
88685             el = component.el;
88686             anchor = component.anchor;
88687
88688             if (!component.anchor && component.items && !Ext.isNumber(component.width) && !(Ext.isIE6 && Ext.isStrict)) {
88689                 component.anchor = anchor = me.defaultAnchor;
88690             }
88691
88692             if (anchor) {
88693                 anchorSpec = component.anchorSpec;
88694                 // cache all anchor values
88695                 if (!anchorSpec) {
88696                     anchorsArray = anchor.split(' ');
88697                     component.anchorSpec = anchorSpec = {
88698                         right: me.parseAnchor(anchorsArray[0], component.initialConfig.width, anchorWidth),
88699                         bottom: me.parseAnchor(anchorsArray[1], component.initialConfig.height, anchorHeight)
88700                     };
88701                 }
88702                 calcWidth = anchorSpec.right ? me.adjustWidthAnchor(anchorSpec.right(ownerWidth) - el.getMargin('lr'), component) : undefined;
88703                 calcHeight = anchorSpec.bottom ? me.adjustHeightAnchor(anchorSpec.bottom(ownerHeight) - el.getMargin('tb'), component) : undefined;
88704
88705                 boxes.push({
88706                     component: component,
88707                     anchor: true,
88708                     width: calcWidth || undefined,
88709                     height: calcHeight || undefined
88710                 });
88711             } else {
88712                 boxes.push({
88713                     component: component,
88714                     anchor: false
88715                 });
88716             }
88717         }
88718
88719         // Work around WebKit RightMargin bug. We're going to inline-block all the children only ONCE and remove it when we're done
88720         if (!Ext.supports.RightMargin) {
88721             target.removeCls(Ext.baseCSSPrefix + 'inline-children');
88722         }
88723
88724         for (i = 0; i < len; i++) {
88725             box = boxes[i];
88726             me.setItemSize(box.component, box.width, box.height);
88727         }
88728
88729         if (overflow && overflow != 'hidden' && !me.adjustmentPass) {
88730             newTargetSize = me.getLayoutTargetSize();
88731             if (newTargetSize.width != size.width || newTargetSize.height != size.height) {
88732                 me.adjustmentPass = true;
88733                 me.onLayout();
88734             }
88735         }
88736
88737         delete me.adjustmentPass;
88738     },
88739
88740     // private
88741     parseAnchor: function(a, start, cstart) {
88742         if (a && a != 'none') {
88743             var ratio;
88744             // standard anchor
88745             if (this.parseAnchorRE.test(a)) {
88746                 var diff = cstart - start;
88747                 return function(v) {
88748                     return v - diff;
88749                 };
88750             }    
88751             // percentage
88752             else if (a.indexOf('%') != -1) {
88753                 ratio = parseFloat(a.replace('%', '')) * 0.01;
88754                 return function(v) {
88755                     return Math.floor(v * ratio);
88756                 };
88757             }    
88758             // simple offset adjustment
88759             else {
88760                 a = parseInt(a, 10);
88761                 if (!isNaN(a)) {
88762                     return function(v) {
88763                         return v + a;
88764                     };
88765                 }
88766             }
88767         }
88768         return null;
88769     },
88770
88771     // private
88772     adjustWidthAnchor: function(value, comp) {
88773         return value;
88774     },
88775
88776     // private
88777     adjustHeightAnchor: function(value, comp) {
88778         return value;
88779     }
88780
88781 });
88782 /**
88783  * @class Ext.form.action.Load
88784  * @extends Ext.form.action.Action
88785  * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.Basic}.</p>
88786  * <p>Instances of this class are only created by a {@link Ext.form.Basic Form} when
88787  * {@link Ext.form.Basic#load load}ing.</p>
88788  * <p><u><b>Response Packet Criteria</b></u></p>
88789  * <p>A response packet <b>must</b> contain:
88790  * <div class="mdetail-params"><ul>
88791  * <li><b><code>success</code></b> property : Boolean</li>
88792  * <li><b><code>data</code></b> property : Object</li>
88793  * <div class="sub-desc">The <code>data</code> property contains the values of Fields to load.
88794  * The individual value object for each Field is passed to the Field's
88795  * {@link Ext.form.field.Field#setValue setValue} method.</div></li>
88796  * </ul></div>
88797  * <p><u><b>JSON Packets</b></u></p>
88798  * <p>By default, response packets are assumed to be JSON, so for the following form load call:<pre><code>
88799 var myFormPanel = new Ext.form.Panel({
88800     title: 'Client and routing info',
88801     items: [{
88802         fieldLabel: 'Client',
88803         name: 'clientName'
88804     }, {
88805         fieldLabel: 'Port of loading',
88806         name: 'portOfLoading'
88807     }, {
88808         fieldLabel: 'Port of discharge',
88809         name: 'portOfDischarge'
88810     }]
88811 });
88812 myFormPanel.{@link Ext.form.Panel#getForm getForm}().{@link Ext.form.Basic#load load}({
88813     url: '/getRoutingInfo.php',
88814     params: {
88815         consignmentRef: myConsignmentRef
88816     },
88817     failure: function(form, action) {
88818         Ext.Msg.alert("Load failed", action.result.errorMessage);
88819     }
88820 });
88821 </code></pre>
88822  * a <b>success response</b> packet may look like this:</p><pre><code>
88823 {
88824     success: true,
88825     data: {
88826         clientName: "Fred. Olsen Lines",
88827         portOfLoading: "FXT",
88828         portOfDischarge: "OSL"
88829     }
88830 }</code></pre>
88831  * while a <b>failure response</b> packet may look like this:</p><pre><code>
88832 {
88833     success: false,
88834     errorMessage: "Consignment reference not found"
88835 }</code></pre>
88836  * <p>Other data may be placed into the response for processing the {@link Ext.form.Basic Form}'s
88837  * callback or event handler methods. The object decoded from this JSON is available in the
88838  * {@link Ext.form.action.Action#result result} property.</p>
88839  */
88840 Ext.define('Ext.form.action.Load', {
88841     extend:'Ext.form.action.Action',
88842     requires: ['Ext.data.Connection'],
88843     alternateClassName: 'Ext.form.Action.Load',
88844     alias: 'formaction.load',
88845
88846     type: 'load',
88847
88848     /**
88849      * @private
88850      */
88851     run: function() {
88852         Ext.Ajax.request(Ext.apply(
88853             this.createCallback(),
88854             {
88855                 method: this.getMethod(),
88856                 url: this.getUrl(),
88857                 headers: this.headers,
88858                 params: this.getParams()
88859             }
88860         ));
88861     },
88862
88863     /**
88864      * @private
88865      */
88866     onSuccess: function(response){
88867         var result = this.processResponse(response),
88868             form = this.form;
88869         if (result === true || !result.success || !result.data) {
88870             this.failureType = Ext.form.action.Action.LOAD_FAILURE;
88871             form.afterAction(this, false);
88872             return;
88873         }
88874         form.clearInvalid();
88875         form.setValues(result.data);
88876         form.afterAction(this, true);
88877     },
88878
88879     /**
88880      * @private
88881      */
88882     handleResponse: function(response) {
88883         var reader = this.form.reader,
88884             rs, data;
88885         if (reader) {
88886             rs = reader.read(response);
88887             data = rs.records && rs.records[0] ? rs.records[0].data : null;
88888             return {
88889                 success : rs.success,
88890                 data : data
88891             };
88892         }
88893         return Ext.decode(response.responseText);
88894     }
88895 });
88896
88897
88898 /**
88899  * @class Ext.window.Window
88900  * @extends Ext.panel.Panel
88901  * <p>A specialized panel intended for use as an application window.  Windows are floated, {@link #resizable}, and
88902  * {@link #draggable} by default.  Windows can be {@link #maximizable maximized} to fill the viewport,
88903  * restored to their prior size, and can be {@link #minimize}d.</p>
88904  * <p>Windows can also be linked to a {@link Ext.ZIndexManager} or managed by the {@link Ext.WindowManager} to provide
88905  * grouping, activation, to front, to back and other application-specific behavior.</p>
88906  * <p>By default, Windows will be rendered to document.body. To {@link #constrain} a Window to another element
88907  * specify {@link Ext.Component#renderTo renderTo}.</p>
88908  * <p><b>As with all {@link Ext.container.Container Container}s, it is important to consider how you want the Window
88909  * to size and arrange any child Components. Choose an appropriate {@link #layout} configuration which lays out
88910  * child Components in the required manner.</b></p>
88911  * {@img Ext.window.Window/Ext.window.Window.png Window component}
88912  * Example:<code><pre>
88913 Ext.create('Ext.window.Window', {
88914     title: 'Hello',
88915     height: 200,
88916     width: 400,
88917     layout: 'fit',
88918     items: {  // Let's put an empty grid in just to illustrate fit layout
88919         xtype: 'grid',
88920         border: false,
88921         columns: [{header: 'World'}],                 // One header just for show. There's no data,
88922         store: Ext.create('Ext.data.ArrayStore', {}) // A dummy empty data store
88923     }
88924 }).show();
88925 </pre></code>
88926  * @constructor
88927  * @param {Object} config The config object
88928  * @xtype window
88929  */
88930 Ext.define('Ext.window.Window', {
88931     extend: 'Ext.panel.Panel',
88932
88933     alternateClassName: 'Ext.Window',
88934
88935     requires: ['Ext.util.ComponentDragger', 'Ext.util.Region', 'Ext.EventManager'],
88936
88937     alias: 'widget.window',
88938
88939     /**
88940      * @cfg {Number} x
88941      * The X position of the left edge of the window on initial showing. Defaults to centering the Window within
88942      * the width of the Window's container {@link Ext.core.Element Element) (The Element that the Window is rendered to).
88943      */
88944     /**
88945      * @cfg {Number} y
88946      * The Y position of the top edge of the window on initial showing. Defaults to centering the Window within
88947      * the height of the Window's container {@link Ext.core.Element Element) (The Element that the Window is rendered to).
88948      */
88949     /**
88950      * @cfg {Boolean} modal
88951      * True to make the window modal and mask everything behind it when displayed, false to display it without
88952      * restricting access to other UI elements (defaults to false).
88953      */
88954     /**
88955      * @cfg {String/Element} animateTarget
88956      * Id or element from which the window should animate while opening (defaults to null with no animation).
88957      */
88958     /**
88959      * @cfg {String/Number/Component} defaultFocus
88960      * <p>Specifies a Component to receive focus when this Window is focused.</p>
88961      * <p>This may be one of:</p><div class="mdetail-params"><ul>
88962      * <li>The index of a footer Button.</li>
88963      * <li>The id or {@link Ext.AbstractComponent#itemId} of a descendant Component.</li>
88964      * <li>A Component.</li>
88965      * </ul></div>
88966      */
88967     /**
88968      * @cfg {Function} onEsc
88969      * Allows override of the built-in processing for the escape key. Default action
88970      * is to close the Window (performing whatever action is specified in {@link #closeAction}.
88971      * To prevent the Window closing when the escape key is pressed, specify this as
88972      * Ext.emptyFn (See {@link Ext#emptyFn Ext.emptyFn}).
88973      */
88974     /**
88975      * @cfg {Boolean} collapsed
88976      * True to render the window collapsed, false to render it expanded (defaults to false). Note that if
88977      * {@link #expandOnShow} is true (the default) it will override the <code>collapsed</code> config and the window
88978      * will always be expanded when shown.
88979      */
88980     /**
88981      * @cfg {Boolean} maximized
88982      * True to initially display the window in a maximized state. (Defaults to false).
88983      */
88984
88985     /**
88986     * @cfg {String} baseCls
88987     * The base CSS class to apply to this panel's element (defaults to 'x-window').
88988     */
88989     baseCls: Ext.baseCSSPrefix + 'window',
88990
88991     /**
88992      * @cfg {Mixed} resizable
88993      * <p>Specify as <code>true</code> to allow user resizing at each edge and corner of the window, false to disable
88994      * resizing (defaults to true).</p>
88995      * <p>This may also be specified as a config object to </p>
88996      */
88997     resizable: true,
88998
88999     /**
89000      * @cfg {Boolean} draggable
89001      * <p>True to allow the window to be dragged by the header bar, false to disable dragging (defaults to true).  Note
89002      * that by default the window will be centered in the viewport, so if dragging is disabled the window may need
89003      * to be positioned programmatically after render (e.g., myWindow.setPosition(100, 100);).<p>
89004      */
89005     draggable: true,
89006
89007     /**
89008      * @cfg {Boolean} constrain
89009      * True to constrain the window within its containing element, false to allow it to fall outside of its
89010      * containing element. By default the window will be rendered to document.body.  To render and constrain the
89011      * window within another element specify {@link #renderTo}.
89012      * (defaults to false).  Optionally the header only can be constrained using {@link #constrainHeader}.
89013      */
89014     constrain: false,
89015
89016     /**
89017      * @cfg {Boolean} constrainHeader
89018      * True to constrain the window header within its containing element (allowing the window body to fall outside
89019      * of its containing element) or false to allow the header to fall outside its containing element (defaults to
89020      * false). Optionally the entire window can be constrained using {@link #constrain}.
89021      */
89022     constrainHeader: false,
89023
89024     /**
89025      * @cfg {Boolean} plain
89026      * True to render the window body with a transparent background so that it will blend into the framing
89027      * elements, false to add a lighter background color to visually highlight the body element and separate it
89028      * more distinctly from the surrounding frame (defaults to false).
89029      */
89030     plain: false,
89031
89032     /**
89033      * @cfg {Boolean} minimizable
89034      * True to display the 'minimize' tool button and allow the user to minimize the window, false to hide the button
89035      * and disallow minimizing the window (defaults to false).  Note that this button provides no implementation --
89036      * the behavior of minimizing a window is implementation-specific, so the minimize event must be handled and a
89037      * custom minimize behavior implemented for this option to be useful.
89038      */
89039     minimizable: false,
89040
89041     /**
89042      * @cfg {Boolean} maximizable
89043      * True to display the 'maximize' tool button and allow the user to maximize the window, false to hide the button
89044      * and disallow maximizing the window (defaults to false).  Note that when a window is maximized, the tool button
89045      * will automatically change to a 'restore' button with the appropriate behavior already built-in that will
89046      * restore the window to its previous size.
89047      */
89048     maximizable: false,
89049
89050     // inherit docs
89051     minHeight: 100,
89052
89053     // inherit docs
89054     minWidth: 200,
89055
89056     /**
89057      * @cfg {Boolean} expandOnShow
89058      * True to always expand the window when it is displayed, false to keep it in its current state (which may be
89059      * {@link #collapsed}) when displayed (defaults to true).
89060      */
89061     expandOnShow: true,
89062
89063     // inherited docs, same default
89064     collapsible: false,
89065
89066     /**
89067      * @cfg {Boolean} closable
89068      * <p>True to display the 'close' tool button and allow the user to close the window, false to
89069      * hide the button and disallow closing the window (defaults to <code>true</code>).</p>
89070      * <p>By default, when close is requested by either clicking the close button in the header
89071      * or pressing ESC when the Window has focus, the {@link #close} method will be called. This
89072      * will <i>{@link Ext.Component#destroy destroy}</i> the Window and its content meaning that
89073      * it may not be reused.</p>
89074      * <p>To make closing a Window <i>hide</i> the Window so that it may be reused, set
89075      * {@link #closeAction} to 'hide'.</p>
89076      */
89077     closable: true,
89078
89079     /**
89080      * @cfg {Boolean} hidden
89081      * Render this Window hidden (default is <code>true</code>). If <code>true</code>, the
89082      * {@link #hide} method will be called internally.
89083      */
89084     hidden: true,
89085
89086     // Inherit docs from Component. Windows render to the body on first show.
89087     autoRender: true,
89088
89089     // Inherit docs from Component. Windows hide using visibility.
89090     hideMode: 'visibility',
89091
89092     /** @cfg {Boolean} floating @hide Windows are always floating*/
89093     floating: true,
89094
89095     ariaRole: 'alertdialog',
89096     
89097     itemCls: 'x-window-item',
89098
89099     overlapHeader: true,
89100     
89101     ignoreHeaderBorderManagement: true,
89102
89103     // private
89104     initComponent: function() {
89105         var me = this;
89106         me.callParent();
89107         me.addEvents(
89108             /**
89109              * @event activate
89110              * Fires after the window has been visually activated via {@link #setActive}.
89111              * @param {Ext.window.Window} this
89112              */
89113             /**
89114              * @event deactivate
89115              * Fires after the window has been visually deactivated via {@link #setActive}.
89116              * @param {Ext.window.Window} this
89117              */
89118             /**
89119              * @event resize
89120              * Fires after the window has been resized.
89121              * @param {Ext.window.Window} this
89122              * @param {Number} width The window's new width
89123              * @param {Number} height The window's new height
89124              */
89125             'resize',
89126             /**
89127              * @event maximize
89128              * Fires after the window has been maximized.
89129              * @param {Ext.window.Window} this
89130              */
89131             'maximize',
89132             /**
89133              * @event minimize
89134              * Fires after the window has been minimized.
89135              * @param {Ext.window.Window} this
89136              */
89137             'minimize',
89138             /**
89139              * @event restore
89140              * Fires after the window has been restored to its original size after being maximized.
89141              * @param {Ext.window.Window} this
89142              */
89143             'restore'
89144         );
89145
89146         if (me.plain) {
89147             me.addClsWithUI('plain');
89148         }
89149
89150         if (me.modal) {
89151             me.ariaRole = 'dialog';
89152         }
89153     },
89154
89155     // State Management
89156     // private
89157
89158     initStateEvents: function(){
89159         var events = this.stateEvents;
89160         // push on stateEvents if they don't exist
89161         Ext.each(['maximize', 'restore', 'resize', 'dragend'], function(event){
89162             if (Ext.Array.indexOf(events, event)) {
89163                 events.push(event);
89164             }
89165         });
89166         this.callParent();
89167     },
89168
89169     getState: function() {
89170         var me = this,
89171             state = me.callParent() || {},
89172             maximized = !!me.maximized;
89173
89174         state.maximized = maximized;
89175         Ext.apply(state, {
89176             size: maximized ? me.restoreSize : me.getSize(),
89177             pos: maximized ? me.restorePos : me.getPosition()
89178         });
89179         return state;
89180     },
89181
89182     applyState: function(state){
89183         var me = this;
89184
89185         if (state) {
89186             me.maximized = state.maximized;
89187             if (me.maximized) {
89188                 me.hasSavedRestore = true;
89189                 me.restoreSize = state.size;
89190                 me.restorePos = state.pos;
89191             } else {
89192                 Ext.apply(me, {
89193                     width: state.size.width,
89194                     height: state.size.height,
89195                     x: state.pos[0],
89196                     y: state.pos[1]
89197                 });
89198             }
89199         }
89200     },
89201
89202     // private
89203     onMouseDown: function () {
89204         if (this.floating) {
89205             this.toFront();
89206         }
89207     },
89208
89209     // private
89210     onRender: function(ct, position) {
89211         var me = this;
89212         me.callParent(arguments);
89213         me.focusEl = me.el;
89214
89215         // Double clicking a header will toggleMaximize
89216         if (me.maximizable) {
89217             me.header.on({
89218                 dblclick: {
89219                     fn: me.toggleMaximize,
89220                     element: 'el',
89221                     scope: me
89222                 }
89223             });
89224         }
89225     },
89226
89227     // private
89228     afterRender: function() {
89229         var me = this,
89230             hidden = me.hidden,
89231             keyMap;
89232
89233         me.hidden = false;
89234         // Component's afterRender sizes and positions the Component
89235         me.callParent();
89236         me.hidden = hidden;
89237
89238         // Create the proxy after the size has been applied in Component.afterRender
89239         me.proxy = me.getProxy();
89240
89241         // clickToRaise
89242         me.mon(me.el, 'mousedown', me.onMouseDown, me);
89243
89244         // Initialize
89245         if (me.maximized) {
89246             me.maximized = false;
89247             me.maximize();
89248         }
89249
89250         if (me.closable) {
89251             keyMap = me.getKeyMap();
89252             keyMap.on(27, me.onEsc, me);
89253             keyMap.disable();
89254         }
89255     },
89256
89257     /**
89258      * @private
89259      * @override
89260      * Override Component.initDraggable.
89261      * Window uses the header element as the delegate.
89262      */
89263     initDraggable: function() {
89264         var me = this,
89265             ddConfig;
89266
89267         if (!me.header) {
89268             me.updateHeader(true);
89269         }
89270
89271         ddConfig = Ext.applyIf({
89272             el: me.el,
89273             delegate: '#' + me.header.id
89274         }, me.draggable);
89275
89276         // Add extra configs if Window is specified to be constrained
89277         if (me.constrain || me.constrainHeader) {
89278             ddConfig.constrain = me.constrain;
89279             ddConfig.constrainDelegate = me.constrainHeader;
89280             ddConfig.constrainTo = me.constrainTo || me.container;
89281         }
89282
89283         /**
89284          * <p>If this Window is configured {@link #draggable}, this property will contain
89285          * an instance of {@link Ext.util.ComponentDragger} (A subclass of {@link Ext.dd.DragTracker DragTracker})
89286          * which handles dragging the Window's DOM Element, and constraining according to the {@link #constrain}
89287          * and {@link #constrainHeader} .</p>
89288          * <p>This has implementations of <code>onBeforeStart</code>, <code>onDrag</code> and <code>onEnd</code>
89289          * which perform the dragging action. If extra logic is needed at these points, use
89290          * {@link Ext.Function#createInterceptor createInterceptor} or {@link Ext.Function#createSequence createSequence} to
89291          * augment the existing implementations.</p>
89292          * @type Ext.util.ComponentDragger
89293          * @property dd
89294          */
89295         me.dd = Ext.create('Ext.util.ComponentDragger', this, ddConfig);
89296         me.relayEvents(me.dd, ['dragstart', 'drag', 'dragend']);
89297     },
89298
89299     // private
89300     onEsc: function(k, e) {
89301         e.stopEvent();
89302         this[this.closeAction]();
89303     },
89304
89305     // private
89306     beforeDestroy: function() {
89307         var me = this;
89308         if (me.rendered) {
89309             delete this.animateTarget;
89310             me.hide();
89311             Ext.destroy(
89312                 me.keyMap
89313             );
89314         }
89315         me.callParent();
89316     },
89317
89318     /**
89319      * @private
89320      * @override
89321      * Contribute class-specific tools to the header.
89322      * Called by Panel's initTools.
89323      */
89324     addTools: function() {
89325         var me = this;
89326
89327         // Call Panel's initTools
89328         me.callParent();
89329
89330         if (me.minimizable) {
89331             me.addTool({
89332                 type: 'minimize',
89333                 handler: Ext.Function.bind(me.minimize, me, [])
89334             });
89335         }
89336         if (me.maximizable) {
89337             me.addTool({
89338                 type: 'maximize',
89339                 handler: Ext.Function.bind(me.maximize, me, [])
89340             });
89341             me.addTool({
89342                 type: 'restore',
89343                 handler: Ext.Function.bind(me.restore, me, []),
89344                 hidden: true
89345             });
89346         }
89347     },
89348
89349     /**
89350      * Gets the configured default focus item.  If a {@link #defaultFocus} is set, it will receive focus, otherwise the
89351      * Container itself will receive focus.
89352      */
89353     getFocusEl: function() {
89354         var me = this,
89355             f = me.focusEl,
89356             defaultComp = me.defaultButton || me.defaultFocus,
89357             t = typeof db,
89358             el,
89359             ct;
89360
89361         if (Ext.isDefined(defaultComp)) {
89362             if (Ext.isNumber(defaultComp)) {
89363                 f = me.query('button')[defaultComp];
89364             } else if (Ext.isString(defaultComp)) {
89365                 f = me.down('#' + defaultComp);
89366             } else {
89367                 f = defaultComp;
89368             }
89369         }
89370         return f || me.focusEl;
89371     },
89372
89373     // private
89374     beforeShow: function() {
89375         this.callParent();
89376
89377         if (this.expandOnShow) {
89378             this.expand(false);
89379         }
89380     },
89381
89382     // private
89383     afterShow: function(animateTarget) {
89384         var me = this,
89385             size;
89386
89387         // Perform superclass's afterShow tasks
89388         // Which might include animating a proxy from an animTarget
89389         me.callParent(arguments);
89390
89391         if (me.maximized) {
89392             me.fitContainer();
89393         }
89394
89395         if (me.monitorResize || me.constrain || me.constrainHeader) {
89396             Ext.EventManager.onWindowResize(me.onWindowResize, me);
89397         }
89398         me.doConstrain();
89399         if (me.keyMap) {
89400             me.keyMap.enable();
89401         }
89402     },
89403
89404     // private
89405     doClose: function() {
89406         var me = this;
89407
89408         // immediate close
89409         if (me.hidden) {
89410             me.fireEvent('close', me);
89411             me[me.closeAction]();
89412         } else {
89413             // close after hiding
89414             me.hide(me.animTarget, me.doClose, me);
89415         }
89416     },
89417
89418     // private
89419     afterHide: function() {
89420         var me = this;
89421
89422         // No longer subscribe to resizing now that we're hidden
89423         if (me.monitorResize || me.constrain || me.constrainHeader) {
89424             Ext.EventManager.removeResizeListener(me.onWindowResize, me);
89425         }
89426
89427         // Turn off keyboard handling once window is hidden
89428         if (me.keyMap) {
89429             me.keyMap.disable();
89430         }
89431
89432         // Perform superclass's afterHide tasks.
89433         me.callParent(arguments);
89434     },
89435
89436     // private
89437     onWindowResize: function() {
89438         if (this.maximized) {
89439             this.fitContainer();
89440         }
89441         this.doConstrain();
89442     },
89443
89444     /**
89445      * Placeholder method for minimizing the window.  By default, this method simply fires the {@link #minimize} event
89446      * since the behavior of minimizing a window is application-specific.  To implement custom minimize behavior,
89447      * either the minimize event can be handled or this method can be overridden.
89448      * @return {Ext.window.Window} this
89449      */
89450     minimize: function() {
89451         this.fireEvent('minimize', this);
89452         return this;
89453     },
89454
89455     afterCollapse: function() {
89456         var me = this;
89457
89458         if (me.maximizable) {
89459             me.tools.maximize.hide();
89460             me.tools.restore.hide();
89461         }
89462         if (me.resizer) {
89463             me.resizer.disable();
89464         }
89465         me.callParent(arguments);
89466     },
89467
89468     afterExpand: function() {
89469         var me = this;
89470
89471         if (me.maximized) {
89472             me.tools.restore.show();
89473         } else if (me.maximizable) {
89474             me.tools.maximize.show();
89475         }
89476         if (me.resizer) {
89477             me.resizer.enable();
89478         }
89479         me.callParent(arguments);
89480     },
89481
89482     /**
89483      * Fits the window within its current container and automatically replaces
89484      * the {@link #maximizable 'maximize' tool button} with the 'restore' tool button.
89485      * Also see {@link #toggleMaximize}.
89486      * @return {Ext.window.Window} this
89487      */
89488     maximize: function() {
89489         var me = this;
89490
89491         if (!me.maximized) {
89492             me.expand(false);
89493             if (!me.hasSavedRestore) {
89494                 me.restoreSize = me.getSize();
89495                 me.restorePos = me.getPosition(true);
89496             }
89497             if (me.maximizable) {
89498                 me.tools.maximize.hide();
89499                 me.tools.restore.show();
89500             }
89501             me.maximized = true;
89502             me.el.disableShadow();
89503
89504             if (me.dd) {
89505                 me.dd.disable();
89506             }
89507             if (me.collapseTool) {
89508                 me.collapseTool.hide();
89509             }
89510             me.el.addCls(Ext.baseCSSPrefix + 'window-maximized');
89511             me.container.addCls(Ext.baseCSSPrefix + 'window-maximized-ct');
89512
89513             me.setPosition(0, 0);
89514             me.fitContainer();
89515             me.fireEvent('maximize', me);
89516         }
89517         return me;
89518     },
89519
89520     /**
89521      * Restores a {@link #maximizable maximized}  window back to its original
89522      * size and position prior to being maximized and also replaces
89523      * the 'restore' tool button with the 'maximize' tool button.
89524      * Also see {@link #toggleMaximize}.
89525      * @return {Ext.window.Window} this
89526      */
89527     restore: function() {
89528         var me = this,
89529             tools = me.tools;
89530
89531         if (me.maximized) {
89532             delete me.hasSavedRestore;
89533             me.removeCls(Ext.baseCSSPrefix + 'window-maximized');
89534
89535             // Toggle tool visibility
89536             if (tools.restore) {
89537                 tools.restore.hide();
89538             }
89539             if (tools.maximize) {
89540                 tools.maximize.show();
89541             }
89542             if (me.collapseTool) {
89543                 me.collapseTool.show();
89544             }
89545
89546             // Restore the position/sizing
89547             me.setPosition(me.restorePos);
89548             me.setSize(me.restoreSize);
89549
89550             // Unset old position/sizing
89551             delete me.restorePos;
89552             delete me.restoreSize;
89553
89554             me.maximized = false;
89555
89556             me.el.enableShadow(true);
89557
89558             // Allow users to drag and drop again
89559             if (me.dd) {
89560                 me.dd.enable();
89561             }
89562
89563             me.container.removeCls(Ext.baseCSSPrefix + 'window-maximized-ct');
89564
89565             me.doConstrain();
89566             me.fireEvent('restore', me);
89567         }
89568         return me;
89569     },
89570
89571     /**
89572      * A shortcut method for toggling between {@link #maximize} and {@link #restore} based on the current maximized
89573      * state of the window.
89574      * @return {Ext.window.Window} this
89575      */
89576     toggleMaximize: function() {
89577         return this[this.maximized ? 'restore': 'maximize']();
89578     }
89579
89580     /**
89581      * @cfg {Boolean} autoWidth @hide
89582      * Absolute positioned element and therefore cannot support autoWidth.
89583      * A width is a required configuration.
89584      **/
89585 });
89586 /**
89587  * @class Ext.form.field.Base
89588  * @extends Ext.Component
89589
89590 Base class for form fields that provides default event handling, rendering, and other common functionality
89591 needed by all form field types. Utilizes the {@link Ext.form.field.Field} mixin for value handling and validation,
89592 and the {@link Ext.form.Labelable} mixin to provide label and error message display.
89593
89594 In most cases you will want to use a subclass, such as {@link Ext.form.field.Text} or {@link Ext.form.field.Checkbox},
89595 rather than creating instances of this class directly. However if you are implementing a custom form field,
89596 using this as the parent class is recommended.
89597
89598 __Values and Conversions__
89599
89600 Because BaseField implements the Field mixin, it has a main value that can be initialized with the
89601 {@link #value} config and manipulated via the {@link #getValue} and {@link #setValue} methods. This main
89602 value can be one of many data types appropriate to the current field, for instance a {@link Ext.form.field.Date Date}
89603 field would use a JavaScript Date object as its value type. However, because the field is rendered as a HTML
89604 input, this value data type can not always be directly used in the rendered field.
89605
89606 Therefore BaseField introduces the concept of a "raw value". This is the value of the rendered HTML input field,
89607 and is normally a String. The {@link #getRawValue} and {@link #setRawValue} methods can be used to directly
89608 work with the raw value, though it is recommended to use getValue and setValue in most cases.
89609
89610 Conversion back and forth between the main value and the raw value is handled by the {@link #valueToRaw} and
89611 {@link #rawToValue} methods. If you are implementing a subclass that uses a non-String value data type, you
89612 should override these methods to handle the conversion.
89613
89614 __Rendering__
89615
89616 The content of the field body is defined by the {@link #fieldSubTpl} XTemplate, with its argument data
89617 created by the {@link #getSubTplData} method. Override this template and/or method to create custom
89618 field renderings.
89619 {@img Ext.form.BaseField/Ext.form.BaseField.png Ext.form.BaseField BaseField component}
89620 __Example usage:__
89621
89622     // A simple subclass of BaseField that creates a HTML5 search field. Redirects to the
89623     // searchUrl when the Enter key is pressed.
89624     Ext.define('Ext.form.SearchField', {
89625         extend: 'Ext.form.field.Base',
89626         alias: 'widget.searchfield',
89627     
89628         inputType: 'search',
89629     
89630         // Config defining the search URL
89631         searchUrl: 'http://www.google.com/search?q={0}',
89632     
89633         // Add specialkey listener
89634         initComponent: function() {
89635             this.callParent();
89636             this.on('specialkey', this.checkEnterKey, this);
89637         },
89638     
89639         // Handle enter key presses, execute the search if the field has a value
89640         checkEnterKey: function(field, e) {
89641             var value = this.getValue();
89642             if (e.getKey() === e.ENTER && !Ext.isEmpty(value)) {
89643                 location.href = Ext.String.format(this.searchUrl, value);
89644             }
89645         }
89646     });
89647
89648     Ext.create('Ext.form.Panel', {
89649         title: 'BaseField Example',
89650         bodyPadding: 5,
89651         width: 250,
89652                 
89653         // Fields will be arranged vertically, stretched to full width
89654         layout: 'anchor',
89655         defaults: {
89656             anchor: '100%'
89657         },
89658         items: [{
89659             xtype: 'searchfield',
89660             fieldLabel: 'Search',
89661             name: 'query'
89662         }]
89663         renderTo: Ext.getBody()
89664     });
89665
89666  * @constructor
89667  * Creates a new Field
89668  * @param {Object} config Configuration options
89669  *
89670  * @xtype field
89671  * @markdown
89672  * @docauthor Jason Johnston <jason@sencha.com>
89673  */
89674 Ext.define('Ext.form.field.Base', {
89675     extend: 'Ext.Component',
89676     mixins: {
89677         labelable: 'Ext.form.Labelable',
89678         field: 'Ext.form.field.Field'
89679     },
89680     alias: 'widget.field',
89681     alternateClassName: ['Ext.form.Field', 'Ext.form.BaseField'],
89682     requires: ['Ext.util.DelayedTask', 'Ext.XTemplate', 'Ext.layout.component.field.Field'],
89683
89684     fieldSubTpl: [
89685         '<input id="{id}" type="{type}" ',
89686         '<tpl if="name">name="{name}" </tpl>',
89687         '<tpl if="size">size="{size}" </tpl>',
89688         '<tpl if="tabIdx">tabIndex="{tabIdx}" </tpl>',
89689         'class="{fieldCls} {typeCls}" autocomplete="off" />',
89690         {
89691             compiled: true,
89692             disableFormats: true
89693         }
89694     ],
89695
89696     /**
89697      * @cfg {String} name The name of the field (defaults to undefined). This is used as the parameter
89698      * name when including the field value in a {@link Ext.form.Basic#submit form submit()}. If no name is
89699      * configured, it falls back to the {@link #inputId}. To prevent the field from being included in the
89700      * form submit, set {@link #submitValue} to <tt>false</tt>.
89701      */
89702
89703     /**
89704      * @cfg {String} inputType
89705      * <p>The type attribute for input fields -- e.g. radio, text, password, file (defaults to <tt>'text'</tt>).
89706      * The extended types supported by HTML5 inputs (url, email, etc.) may also be used, though using them
89707      * will cause older browsers to fall back to 'text'.</p>
89708      * <p>The type 'password' must be used to render that field type currently -- there is no separate Ext
89709      * component for that. You can use {@link Ext.form.field.File} which creates a custom-rendered file upload
89710      * field, but if you want a plain unstyled file input you can use a BaseField with inputType:'file'.</p>
89711      */
89712     inputType: 'text',
89713
89714     /**
89715      * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered,
89716      * not those which are built via applyTo (defaults to undefined).
89717      */
89718
89719     /**
89720      * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided
89721      * (defaults to 'The value in this field is invalid')
89722      */
89723     invalidText : 'The value in this field is invalid',
89724
89725     /**
89726      * @cfg {String} fieldCls The default CSS class for the field input (defaults to 'x-form-field')
89727      */
89728     fieldCls : Ext.baseCSSPrefix + 'form-field',
89729
89730     /**
89731      * @cfg {String} fieldStyle Optional CSS style(s) to be applied to the {@link #inputEl field input element}.
89732      * Should be a valid argument to {@link Ext.core.Element#applyStyles}. Defaults to undefined. See also the
89733      * {@link #setFieldStyle} method for changing the style after initialization.
89734      */
89735
89736     /**
89737      * @cfg {String} focusCls The CSS class to use when the field receives focus (defaults to 'x-form-focus')
89738      */
89739     focusCls : Ext.baseCSSPrefix + 'form-focus',
89740
89741     /**
89742      * @cfg {String} dirtyCls The CSS class to use when the field value {@link #isDirty is dirty}.
89743      */
89744     dirtyCls : Ext.baseCSSPrefix + 'form-dirty',
89745
89746     /**
89747      * @cfg {Array} checkChangeEvents
89748      * <p>A list of event names that will be listened for on the field's {@link #inputEl input element}, which
89749      * will cause the field's value to be checked for changes. If a change is detected, the
89750      * {@link #change change event} will be fired, followed by validation if the {@link #validateOnChange}
89751      * option is enabled.</p>
89752      * <p>Defaults to <tt>['change', 'propertychange']</tt> in Internet Explorer, and <tt>['change', 'input',
89753      * 'textInput', 'keyup', 'dragdrop']</tt> in other browsers. This catches all the ways that field values
89754      * can be changed in most supported browsers; the only known exceptions at the time of writing are:</p>
89755      * <ul>
89756      * <li>Safari 3.2 and older: cut/paste in textareas via the context menu, and dragging text into textareas</li>
89757      * <li>Opera 10 and 11: dragging text into text fields and textareas, and cut via the context menu in text
89758      * fields and textareas</li>
89759      * <li>Opera 9: Same as Opera 10 and 11, plus paste from context menu in text fields and textareas</li>
89760      * </ul>
89761      * <p>If you need to guarantee on-the-fly change notifications including these edge cases, you can call the
89762      * {@link #checkChange} method on a repeating interval, e.g. using {@link Ext.TaskManager}, or if the field is
89763      * within a {@link Ext.form.Panel}, you can use the FormPanel's {@link Ext.form.Panel#pollForChanges}
89764      * configuration to set up such a task automatically.</p>
89765      */
89766     checkChangeEvents: Ext.isIE && (!document.documentMode || document.documentMode < 9) ?
89767                         ['change', 'propertychange'] :
89768                         ['change', 'input', 'textInput', 'keyup', 'dragdrop'],
89769
89770     /**
89771      * @cfg {Number} checkChangeBuffer
89772      * Defines a timeout in milliseconds for buffering {@link #checkChangeEvents} that fire in rapid succession.
89773      * Defaults to 50 milliseconds.
89774      */
89775     checkChangeBuffer: 50,
89776
89777     componentLayout: 'field',
89778
89779     /**
89780      * @cfg {Boolean} readOnly <tt>true</tt> to mark the field as readOnly in HTML
89781      * (defaults to <tt>false</tt>).
89782      * <br><p><b>Note</b>: this only sets the element's readOnly DOM attribute.
89783      * Setting <code>readOnly=true</code>, for example, will not disable triggering a
89784      * ComboBox or Date; it gives you the option of forcing the user to choose
89785      * via the trigger without typing in the text box. To hide the trigger use
89786      * <code>{@link Ext.form.field.Trigger#hideTrigger hideTrigger}</code>.</p>
89787      */
89788     readOnly : false,
89789
89790     /**
89791      * @cfg {String} readOnlyCls The CSS class applied to the component's main element when it is {@link #readOnly}.
89792      */
89793     readOnlyCls: Ext.baseCSSPrefix + 'form-readonly',
89794
89795     /**
89796      * @cfg {String} inputId
89797      * The id that will be given to the generated input DOM element. Defaults to an automatically generated id.
89798      * If you configure this manually, you must make sure it is unique in the document.
89799      */
89800
89801     /**
89802      * @cfg {Boolean} validateOnBlur
89803      * Whether the field should validate when it loses focus (defaults to <tt>true</tt>). This will cause fields
89804      * to be validated as the user steps through the fields in the form regardless of whether they are making
89805      * changes to those fields along the way. See also {@link #validateOnChange}.
89806      */
89807     validateOnBlur: true,
89808
89809     // private
89810     hasFocus : false,
89811     
89812     baseCls: Ext.baseCSSPrefix + 'field',
89813     
89814     maskOnDisable: false,
89815
89816     // private
89817     initComponent : function() {
89818         var me = this;
89819
89820         me.callParent();
89821
89822         me.subTplData = me.subTplData || {};
89823
89824         me.addEvents(
89825             /**
89826              * @event focus
89827              * Fires when this field receives input focus.
89828              * @param {Ext.form.field.Base} this
89829              */
89830             'focus',
89831             /**
89832              * @event blur
89833              * Fires when this field loses input focus.
89834              * @param {Ext.form.field.Base} this
89835              */
89836             'blur',
89837             /**
89838              * @event specialkey
89839              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.
89840              * To handle other keys see {@link Ext.panel.Panel#keys} or {@link Ext.util.KeyMap}.
89841              * You can check {@link Ext.EventObject#getKey} to determine which key was pressed.
89842              * For example: <pre><code>
89843 var form = new Ext.form.Panel({
89844     ...
89845     items: [{
89846             fieldLabel: 'Field 1',
89847             name: 'field1',
89848             allowBlank: false
89849         },{
89850             fieldLabel: 'Field 2',
89851             name: 'field2',
89852             listeners: {
89853                 specialkey: function(field, e){
89854                     // e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
89855                     // e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
89856                     if (e.{@link Ext.EventObject#getKey getKey()} == e.ENTER) {
89857                         var form = field.up('form').getForm();
89858                         form.submit();
89859                     }
89860                 }
89861             }
89862         }
89863     ],
89864     ...
89865 });
89866              * </code></pre>
89867              * @param {Ext.form.field.Base} this
89868              * @param {Ext.EventObject} e The event object
89869              */
89870             'specialkey'
89871         );
89872
89873         // Init mixins
89874         me.initLabelable();
89875         me.initField();
89876
89877         // Default name to inputId
89878         if (!me.name) {
89879             me.name = me.getInputId();
89880         }
89881     },
89882
89883     /**
89884      * Returns the input id for this field. If none was specified via the {@link #inputId} config,
89885      * then an id will be automatically generated.
89886      */
89887     getInputId: function() {
89888         return this.inputId || (this.inputId = Ext.id());
89889     },
89890
89891     /**
89892      * @protected Creates and returns the data object to be used when rendering the {@link #fieldSubTpl}.
89893      * @return {Object} The template data
89894      */
89895     getSubTplData: function() {
89896         var me = this,
89897             type = me.inputType,
89898             inputId = me.getInputId();
89899
89900         return Ext.applyIf(me.subTplData, {
89901             id: inputId,
89902             name: me.name || inputId,
89903             type: type,
89904             size: me.size || 20,
89905             cls: me.cls,
89906             fieldCls: me.fieldCls,
89907             tabIdx: me.tabIndex,
89908             typeCls: Ext.baseCSSPrefix + 'form-' + (type === 'password' ? 'text' : type)
89909         });
89910     },
89911
89912     /**
89913      * @protected
89914      * Gets the markup to be inserted into the outer template's bodyEl. For fields this is the
89915      * actual input element.
89916      */
89917     getSubTplMarkup: function() {
89918         return this.getTpl('fieldSubTpl').apply(this.getSubTplData());
89919     },
89920
89921     initRenderTpl: function() {
89922         var me = this;
89923         if (!me.hasOwnProperty('renderTpl')) {
89924             me.renderTpl = me.getTpl('labelableRenderTpl');
89925         }
89926         return me.callParent();
89927     },
89928
89929     initRenderData: function() {
89930         return Ext.applyIf(this.callParent(), this.getLabelableRenderData());
89931     },
89932
89933     /**
89934      * Set the {@link #fieldStyle CSS style} of the {@link #inputEl field input element}.
89935      * @param {String/Object/Function} style The style(s) to apply. Should be a valid argument to
89936      * {@link Ext.core.Element#applyStyles}.
89937      */
89938     setFieldStyle: function(style) {
89939         var me = this,
89940             inputEl = me.inputEl;
89941         if (inputEl) {
89942             inputEl.applyStyles(style);
89943         }
89944         me.fieldStyle = style;
89945     },
89946
89947     // private
89948     onRender : function() {
89949         var me = this,
89950             fieldStyle = me.fieldStyle,
89951             renderSelectors = me.renderSelectors;
89952
89953         Ext.applyIf(renderSelectors, me.getLabelableSelectors());
89954
89955         Ext.applyIf(renderSelectors, {
89956             /**
89957              * @property inputEl
89958              * @type Ext.core.Element
89959              * The input Element for this Field. Only available after the field has been rendered.
89960              */
89961             inputEl: '.' + me.fieldCls
89962         });
89963
89964         me.callParent(arguments);
89965
89966         // Make the stored rawValue get set as the input element's value
89967         me.setRawValue(me.rawValue);
89968
89969         if (me.readOnly) {
89970             me.setReadOnly(true);
89971         }
89972         if (me.disabled) {
89973             me.disable();
89974         }
89975         if (fieldStyle) {
89976             me.setFieldStyle(fieldStyle);
89977         }
89978
89979         me.renderActiveError();
89980     },
89981
89982     initAria: function() {
89983         var me = this;
89984         me.callParent();
89985
89986         // Associate the field to the error message element
89987         me.getActionEl().dom.setAttribute('aria-describedby', Ext.id(me.errorEl));
89988     },
89989
89990     getFocusEl: function() {
89991         return this.inputEl;
89992     },
89993
89994     isFileUpload: function() {
89995         return this.inputType === 'file';
89996     },
89997
89998     extractFileInput: function() {
89999         var me = this,
90000             fileInput = me.isFileUpload() ? me.inputEl.dom : null,
90001             clone;
90002         if (fileInput) {
90003             clone = fileInput.cloneNode(true);
90004             fileInput.parentNode.replaceChild(clone, fileInput);
90005             me.inputEl = Ext.get(clone);
90006         }
90007         return fileInput;
90008     },
90009
90010     // private override to use getSubmitValue() as a convenience
90011     getSubmitData: function() {
90012         var me = this,
90013             data = null,
90014             val;
90015         if (!me.disabled && me.submitValue && !me.isFileUpload()) {
90016             val = me.getSubmitValue();
90017             if (val !== null) {
90018                 data = {};
90019                 data[me.getName()] = val;
90020             }
90021         }
90022         return data;
90023     },
90024
90025     /**
90026      * <p>Returns the value that would be included in a standard form submit for this field. This will be combined
90027      * with the field's name to form a <tt>name=value</tt> pair in the {@link #getSubmitData submitted parameters}.
90028      * If an empty string is returned then just the <tt>name=</tt> will be submitted; if <tt>null</tt> is returned
90029      * then nothing will be submitted.</p>
90030      * <p>Note that the value returned will have been {@link #processRawValue processed} but may or may not have
90031      * been successfully {@link #validate validated}.</p>
90032      * @return {String} The value to be submitted, or <tt>null</tt>.
90033      */
90034     getSubmitValue: function() {
90035         return this.processRawValue(this.getRawValue());
90036     },
90037
90038     /**
90039      * Returns the raw value of the field, without performing any normalization, conversion, or validation.
90040      * To get a normalized and converted value see {@link #getValue}.
90041      * @return {String} value The raw String value of the field
90042      */
90043     getRawValue: function() {
90044         var me = this,
90045             v = (me.inputEl ? me.inputEl.getValue() : Ext.value(me.rawValue, ''));
90046         me.rawValue = v;
90047         return v;
90048     },
90049
90050     /**
90051      * Sets the field's raw value directly, bypassing {@link #valueToRaw value conversion}, change detection, and
90052      * validation. To set the value with these additional inspections see {@link #setValue}.
90053      * @param {Mixed} value The value to set
90054      * @return {Mixed} value The field value that is set
90055      */
90056     setRawValue: function(value) {
90057         var me = this;
90058         value = Ext.value(value, '');
90059         me.rawValue = value;
90060
90061         // Some Field subclasses may not render an inputEl
90062         if (me.inputEl) {
90063             me.inputEl.dom.value = value;
90064         }
90065         return value;
90066     },
90067
90068     /**
90069      * <p>Converts a mixed-type value to a raw representation suitable for displaying in the field. This allows
90070      * controlling how value objects passed to {@link #setValue} are shown to the user, including localization.
90071      * For instance, for a {@link Ext.form.field.Date}, this would control how a Date object passed to {@link #setValue}
90072      * would be converted to a String for display in the field.</p>
90073      * <p>See {@link #rawToValue} for the opposite conversion.</p>
90074      * <p>The base implementation simply does a standard toString conversion, and converts
90075      * {@link Ext#isEmpty empty values} to an empty string.</p>
90076      * @param {Mixed} value The mixed-type value to convert to the raw representation.
90077      * @return {Mixed} The converted raw value.
90078      */
90079     valueToRaw: function(value) {
90080         return '' + Ext.value(value, '');
90081     },
90082
90083     /**
90084      * <p>Converts a raw input field value into a mixed-type value that is suitable for this particular field type.
90085      * This allows controlling the normalization and conversion of user-entered values into field-type-appropriate
90086      * values, e.g. a Date object for {@link Ext.form.field.Date}, and is invoked by {@link #getValue}.</p>
90087      * <p>It is up to individual implementations to decide how to handle raw values that cannot be successfully
90088      * converted to the desired object type.</p>
90089      * <p>See {@link #valueToRaw} for the opposite conversion.</p>
90090      * <p>The base implementation does no conversion, returning the raw value untouched.</p>
90091      * @param {Mixed} rawValue
90092      * @return {Mixed} The converted value.
90093      */
90094     rawToValue: function(rawValue) {
90095         return rawValue;
90096     },
90097
90098     /**
90099      * Performs any necessary manipulation of a raw field value to prepare it for {@link #rawToValue conversion}
90100      * and/or {@link #validate validation}, for instance stripping out ignored characters. In the base implementation
90101      * it does nothing; individual subclasses may override this as needed.
90102      * @param {Mixed} value The unprocessed string value
90103      * @return {Mixed} The processed string value
90104      */
90105     processRawValue: function(value) {
90106         return value;
90107     },
90108
90109     /**
90110      * Returns the current data value of the field. The type of value returned is particular to the type of the
90111      * particular field (e.g. a Date object for {@link Ext.form.field.Date}), as the result of calling {@link #rawToValue} on
90112      * the field's {@link #processRawValue processed} String value. To return the raw String value, see {@link #getRawValue}.
90113      * @return {Mixed} value The field value
90114      */
90115     getValue: function() {
90116         var me = this,
90117             val = me.rawToValue(me.processRawValue(me.getRawValue()));
90118         me.value = val;
90119         return val;
90120     },
90121
90122     /**
90123      * Sets a data value into the field and runs the change detection and validation. To set the value directly
90124      * without these inspections see {@link #setRawValue}.
90125      * @param {Mixed} value The value to set
90126      * @return {Ext.form.field.Field} this
90127      */
90128     setValue: function(value) {
90129         var me = this;
90130         me.setRawValue(me.valueToRaw(value));
90131         return me.mixins.field.setValue.call(me, value);
90132     },
90133
90134
90135     //private
90136     onDisable: function() {
90137         var me = this,
90138             inputEl = me.inputEl;
90139         me.callParent();
90140         if (inputEl) {
90141             inputEl.dom.disabled = true;
90142         }
90143     },
90144
90145     //private
90146     onEnable: function() {
90147         var me = this,
90148             inputEl = me.inputEl;
90149         me.callParent();
90150         if (inputEl) {
90151             inputEl.dom.disabled = false;
90152         }
90153     },
90154
90155     /**
90156      * Sets the read only state of this field.
90157      * @param {Boolean} readOnly Whether the field should be read only.
90158      */
90159     setReadOnly: function(readOnly) {
90160         var me = this,
90161             inputEl = me.inputEl;
90162         if (inputEl) {
90163             inputEl.dom.readOnly = readOnly;
90164             inputEl.dom.setAttribute('aria-readonly', readOnly);
90165         }
90166         me[readOnly ? 'addCls' : 'removeCls'](me.readOnlyCls);
90167         me.readOnly = readOnly;
90168     },
90169
90170     // private
90171     fireKey: function(e){
90172         if(e.isSpecialKey()){
90173             this.fireEvent('specialkey', this, Ext.create('Ext.EventObjectImpl', e));
90174         }
90175     },
90176
90177     // private
90178     initEvents : function(){
90179         var me = this,
90180             inputEl = me.inputEl,
90181             onChangeTask,
90182             onChangeEvent;
90183         if (inputEl) {
90184             me.mon(inputEl, Ext.EventManager.getKeyEvent(), me.fireKey,  me);
90185             me.mon(inputEl, 'focus', me.onFocus, me);
90186
90187             // standardise buffer across all browsers + OS-es for consistent event order.
90188             // (the 10ms buffer for Editors fixes a weird FF/Win editor issue when changing OS window focus)
90189             me.mon(inputEl, 'blur', me.onBlur, me, me.inEditor ? {buffer:10} : null);
90190
90191             // listen for immediate value changes
90192             onChangeTask = Ext.create('Ext.util.DelayedTask', me.checkChange, me);
90193             me.onChangeEvent = onChangeEvent = function() {
90194                 onChangeTask.delay(me.checkChangeBuffer);
90195             };
90196             Ext.each(me.checkChangeEvents, function(eventName) {
90197                 if (eventName === 'propertychange') {
90198                     me.usesPropertychange = true;
90199                 }
90200                 me.mon(inputEl, eventName, onChangeEvent);
90201             }, me);
90202         }
90203         me.callParent();
90204     },
90205
90206     doComponentLayout: function() {
90207         var me = this,
90208             inputEl = me.inputEl,
90209             usesPropertychange = me.usesPropertychange,
90210             ename = 'propertychange',
90211             onChangeEvent = me.onChangeEvent;
90212
90213         // In IE if propertychange is one of the checkChangeEvents, we need to remove
90214         // the listener prior to layout and re-add it after, to prevent it from firing
90215         // needlessly for attribute and style changes applied to the inputEl.
90216         if (usesPropertychange) {
90217             me.mun(inputEl, ename, onChangeEvent);
90218         }
90219         me.callParent(arguments);
90220         if (usesPropertychange) {
90221             me.mon(inputEl, ename, onChangeEvent);
90222         }
90223     },
90224
90225     // private
90226     preFocus: Ext.emptyFn,
90227
90228     // private
90229     onFocus: function() {
90230         var me = this,
90231             focusCls = me.focusCls,
90232             inputEl = me.inputEl;
90233         me.preFocus();
90234         if (focusCls && inputEl) {
90235             inputEl.addCls(focusCls);
90236         }
90237         if (!me.hasFocus) {
90238             me.hasFocus = true;
90239             me.fireEvent('focus', me);
90240         }
90241     },
90242
90243     // private
90244     beforeBlur : Ext.emptyFn,
90245
90246     // private
90247     onBlur : function(){
90248         var me = this,
90249             focusCls = me.focusCls,
90250             inputEl = me.inputEl;
90251         me.beforeBlur();
90252         if (focusCls && inputEl) {
90253             inputEl.removeCls(focusCls);
90254         }
90255         if (me.validateOnBlur) {
90256             me.validate();
90257         }
90258         me.hasFocus = false;
90259         me.fireEvent('blur', me);
90260         me.postBlur();
90261     },
90262
90263     // private
90264     postBlur : Ext.emptyFn,
90265
90266
90267     /**
90268      * @private Called when the field's dirty state changes. Adds/removes the {@link #dirtyCls} on the main element.
90269      * @param {Boolean} isDirty
90270      */
90271     onDirtyChange: function(isDirty) {
90272         this[isDirty ? 'addCls' : 'removeCls'](this.dirtyCls);
90273     },
90274
90275
90276     /**
90277      * Returns whether or not the field value is currently valid by
90278      * {@link #getErrors validating} the {@link #processRawValue processed raw value}
90279      * of the field. <b>Note</b>: {@link #disabled} fields are always treated as valid.
90280      * @return {Boolean} True if the value is valid, else false
90281      */
90282     isValid : function() {
90283         var me = this;
90284         return me.disabled || me.validateValue(me.processRawValue(me.getRawValue()));
90285     },
90286
90287
90288     /**
90289      * <p>Uses {@link #getErrors} to build an array of validation errors. If any errors are found, they are passed
90290      * to {@link #markInvalid} and false is returned, otherwise true is returned.</p>
90291      * <p>Previously, subclasses were invited to provide an implementation of this to process validations - from 3.2
90292      * onwards {@link #getErrors} should be overridden instead.</p>
90293      * @param {Mixed} value The value to validate
90294      * @return {Boolean} True if all validations passed, false if one or more failed
90295      */
90296     validateValue: function(value) {
90297         var me = this,
90298             errors = me.getErrors(value),
90299             isValid = Ext.isEmpty(errors);
90300         if (!me.preventMark) {
90301             if (isValid) {
90302                 me.clearInvalid();
90303             } else {
90304                 me.markInvalid(errors);
90305             }
90306         }
90307
90308         return isValid;
90309     },
90310
90311     /**
90312      * <p>Display one or more error messages associated with this field, using {@link #msgTarget} to determine how to
90313      * display the messages and applying {@link #invalidCls} to the field's UI element.</p>
90314      * <p><b>Note</b>: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to
90315      * return <code>false</code> if the value does <i>pass</i> validation. So simply marking a Field as invalid
90316      * will not prevent submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation}
90317      * option set.</p>
90318      * @param {String/Array} errors The validation message(s) to display.
90319      */
90320     markInvalid : function(errors) {
90321         // Save the message and fire the 'invalid' event
90322         var me = this,
90323             oldMsg = me.getActiveError();
90324         me.setActiveErrors(Ext.Array.from(errors));
90325         if (oldMsg !== me.getActiveError()) {
90326             me.doComponentLayout();
90327         }
90328     },
90329
90330     /**
90331      * <p>Clear any invalid styles/messages for this field.</p>
90332      * <p><b>Note</b>: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to
90333      * return <code>true</code> if the value does not <i>pass</i> validation. So simply clearing a field's errors
90334      * will not necessarily allow submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation}
90335      * option set.</p>
90336      */
90337     clearInvalid : function() {
90338         // Clear the message and fire the 'valid' event
90339         var me = this,
90340             hadError = me.hasActiveError();
90341         me.unsetActiveError();
90342         if (hadError) {
90343             me.doComponentLayout();
90344         }
90345     },
90346
90347     /**
90348      * @private Overrides the method from the Ext.form.Labelable mixin to also add the invalidCls to the inputEl,
90349      * as that is required for proper styling in IE with nested fields (due to lack of child selector)
90350      */
90351     renderActiveError: function() {
90352         var me = this,
90353             hasError = me.hasActiveError();
90354         if (me.inputEl) {
90355             // Add/remove invalid class
90356             me.inputEl[hasError ? 'addCls' : 'removeCls'](me.invalidCls + '-field');
90357         }
90358         me.mixins.labelable.renderActiveError.call(me);
90359     },
90360
90361
90362     getActionEl: function() {
90363         return this.inputEl || this.el;
90364     }
90365
90366 });
90367
90368 /**
90369  * @class Ext.form.field.Text
90370  * @extends Ext.form.field.Base
90371  
90372 A basic text field.  Can be used as a direct replacement for traditional text inputs,
90373 or as the base class for more sophisticated input controls (like {@link Ext.form.field.TextArea}
90374 and {@link Ext.form.field.ComboBox}). Has support for empty-field placeholder values (see {@link #emptyText}).
90375
90376 #Validation#
90377
90378 The Text field has a useful set of validations built in:
90379
90380 - {@link #allowBlank} for making the field required
90381 - {@link #minLength} for requiring a minimum value length
90382 - {@link #maxLength} for setting a maximum value length (with {@link #enforceMaxLength} to add it
90383   as the `maxlength` attribute on the input element)
90384 - {@link regex} to specify a custom regular expression for validation
90385
90386 In addition, custom validations may be added:
90387  
90388 - {@link #vtype} specifies a virtual type implementation from {@link Ext.form.field.VTypes} which can contain
90389   custom validation logic
90390 - {@link #validator} allows a custom arbitrary function to be called during validation
90391
90392 The details around how and when each of these validation options get used are described in the
90393 documentation for {@link #getErrors}.
90394
90395 By default, the field value is checked for validity immediately while the user is typing in the
90396 field. This can be controlled with the {@link #validateOnChange}, {@link #checkChangeEvents}, and
90397 {@link #checkChangeBugger} configurations. Also see the details on Form Validation in the
90398 {@link Ext.form.Panel} class documentation.
90399
90400 #Masking and Character Stripping#
90401
90402 Text fields can be configured with custom regular expressions to be applied to entered values before
90403 validation: see {@link #maskRe} and {@link #stripCharsRe} for details.
90404 {@img Ext.form.Text/Ext.form.Text.png Ext.form.Text component}
90405 #Example usage:#
90406
90407     Ext.create('Ext.form.Panel', {
90408         title: 'Contact Info',
90409         width: 300,
90410         bodyPadding: 10,
90411         renderTo: Ext.getBody(),        
90412         items: [{
90413             xtype: 'textfield',
90414             name: 'name',
90415             fieldLabel: 'Name',
90416             allowBlank: false  // requires a non-empty value
90417         }, {
90418             xtype: 'textfield',
90419             name: 'email',
90420             fieldLabel: 'Email Address',
90421             vtype: 'email'  // requires value to be a valid email address format
90422         }]
90423     }); 
90424
90425  * @constructor Creates a new TextField
90426  * @param {Object} config Configuration options
90427  *
90428  * @xtype textfield
90429  * @markdown
90430  * @docauthor Jason Johnston <jason@sencha.com>
90431  */
90432 Ext.define('Ext.form.field.Text', {
90433     extend:'Ext.form.field.Base',
90434     alias: 'widget.textfield',
90435     requires: ['Ext.form.field.VTypes', 'Ext.layout.component.field.Text'],
90436     alternateClassName: ['Ext.form.TextField', 'Ext.form.Text'],
90437
90438     /**
90439      * @cfg {String} vtypeText A custom error message to display in place of the default message provided
90440      * for the <b><code>{@link #vtype}</code></b> currently set for this field (defaults to <tt>undefined</tt>).
90441      * <b>Note</b>: only applies if <b><code>{@link #vtype}</code></b> is set, else ignored.
90442      */
90443     
90444     /**
90445      * @cfg {RegExp} stripCharsRe A JavaScript RegExp object used to strip unwanted content from the value
90446      * before validation (defaults to <tt>undefined</tt>).
90447      */
90448
90449     /**
90450      * @cfg {Number} size An initial value for the 'size' attribute on the text input element. This is only
90451      * used if the field has no configured {@link #width} and is not given a width by its container's layout.
90452      * Defaults to <tt>20</tt>.
90453      */
90454     size: 20,
90455
90456     /**
90457      * @cfg {Boolean} grow <tt>true</tt> if this field should automatically grow and shrink to its content
90458      * (defaults to <tt>false</tt>)
90459      */
90460
90461     /**
90462      * @cfg {Number} growMin The minimum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
90463      * to <tt>30</tt>)
90464      */
90465     growMin : 30,
90466     
90467     /**
90468      * @cfg {Number} growMax The maximum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
90469      * to <tt>800</tt>)
90470      */
90471     growMax : 800,
90472
90473     /**
90474      * @cfg {String} growAppend
90475      * A string that will be appended to the field's current value for the purposes of calculating the target
90476      * field size. Only used when the {@link #grow} config is <tt>true</tt>. Defaults to a single capital "W"
90477      * (the widest character in common fonts) to leave enough space for the next typed character and avoid the
90478      * field value shifting before the width is adjusted.
90479      */
90480     growAppend: 'W',
90481     
90482     /**
90483      * @cfg {String} vtype A validation type name as defined in {@link Ext.form.field.VTypes} (defaults to <tt>undefined</tt>)
90484      */
90485
90486     /**
90487      * @cfg {RegExp} maskRe An input mask regular expression that will be used to filter keystrokes that do
90488      * not match (defaults to <tt>undefined</tt>)
90489      */
90490
90491     /**
90492      * @cfg {Boolean} disableKeyFilter Specify <tt>true</tt> to disable input keystroke filtering (defaults
90493      * to <tt>false</tt>)
90494      */
90495
90496     /**
90497      * @cfg {Boolean} allowBlank Specify <tt>false</tt> to validate that the value's length is > 0 (defaults to
90498      * <tt>true</tt>)
90499      */
90500     allowBlank : true,
90501     
90502     /**
90503      * @cfg {Number} minLength Minimum input field length required (defaults to <tt>0</tt>)
90504      */
90505     minLength : 0,
90506     
90507     /**
90508      * @cfg {Number} maxLength Maximum input field length allowed by validation (defaults to Number.MAX_VALUE).
90509      * This behavior is intended to provide instant feedback to the user by improving usability to allow pasting
90510      * and editing or overtyping and back tracking. To restrict the maximum number of characters that can be
90511      * entered into the field use the <tt><b>{@link Ext.form.field.Text#enforceMaxLength enforceMaxLength}</b></tt> option.
90512      */
90513     maxLength : Number.MAX_VALUE,
90514     
90515     /**
90516      * @cfg {Boolean} enforceMaxLength True to set the maxLength property on the underlying input field. Defaults to <tt>false</tt>
90517      */
90518
90519     /**
90520      * @cfg {String} minLengthText Error text to display if the <b><tt>{@link #minLength minimum length}</tt></b>
90521      * validation fails (defaults to <tt>'The minimum length for this field is {minLength}'</tt>)
90522      */
90523     minLengthText : 'The minimum length for this field is {0}',
90524     
90525     /**
90526      * @cfg {String} maxLengthText Error text to display if the <b><tt>{@link #maxLength maximum length}</tt></b>
90527      * validation fails (defaults to <tt>'The maximum length for this field is {maxLength}'</tt>)
90528      */
90529     maxLengthText : 'The maximum length for this field is {0}',
90530     
90531     /**
90532      * @cfg {Boolean} selectOnFocus <tt>true</tt> to automatically select any existing field text when the field
90533      * receives input focus (defaults to <tt>false</tt>)
90534      */
90535     
90536     /**
90537      * @cfg {String} blankText The error text to display if the <b><tt>{@link #allowBlank}</tt></b> validation
90538      * fails (defaults to <tt>'This field is required'</tt>)
90539      */
90540     blankText : 'This field is required',
90541     
90542     /**
90543      * @cfg {Function} validator
90544      * <p>A custom validation function to be called during field validation ({@link #getErrors})
90545      * (defaults to <tt>undefined</tt>). If specified, this function will be called first, allowing the
90546      * developer to override the default validation process.</p>
90547      * <br><p>This function will be passed the following Parameters:</p>
90548      * <div class="mdetail-params"><ul>
90549      * <li><code>value</code>: <i>Mixed</i>
90550      * <div class="sub-desc">The current field value</div></li>
90551      * </ul></div>
90552      * <br><p>This function is to Return:</p>
90553      * <div class="mdetail-params"><ul>
90554      * <li><code>true</code>: <i>Boolean</i>
90555      * <div class="sub-desc"><code>true</code> if the value is valid</div></li>
90556      * <li><code>msg</code>: <i>String</i>
90557      * <div class="sub-desc">An error message if the value is invalid</div></li>
90558      * </ul></div>
90559      */
90560
90561     /**
90562      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation
90563      * (defaults to <tt>undefined</tt>). If the test fails, the field will be marked invalid using
90564      * <b><tt>{@link #regexText}</tt></b>.
90565      */
90566
90567     /**
90568      * @cfg {String} regexText The error text to display if <b><tt>{@link #regex}</tt></b> is used and the
90569      * test fails during validation (defaults to <tt>''</tt>)
90570      */
90571     regexText : '',
90572     
90573     /**
90574      * @cfg {String} emptyText
90575      * <p>The default text to place into an empty field (defaults to <tt>undefined</tt>).</p>
90576      * <p>Note that normally this value will be submitted to the server if this field is enabled; to prevent this
90577      * you can set the {@link Ext.form.action.Action#submitEmptyText submitEmptyText} option of
90578      * {@link Ext.form.Basic#submit} to <tt>false</tt>.</p>
90579      * <p>Also note that if you use <tt>{@link #inputType inputType}:'file'</tt>, {@link #emptyText} is not
90580      * supported and should be avoided.</p>
90581      */
90582
90583     /**
90584      * @cfg {String} emptyCls The CSS class to apply to an empty field to style the <b><tt>{@link #emptyText}</tt></b>
90585      * (defaults to <tt>'x-form-empty-field'</tt>).  This class is automatically added and removed as needed
90586      * depending on the current field value.
90587      */
90588     emptyCls : Ext.baseCSSPrefix + 'form-empty-field',
90589
90590     ariaRole: 'textbox',
90591
90592     /**
90593      * @cfg {Boolean} enableKeyEvents <tt>true</tt> to enable the proxying of key events for the HTML input field (defaults to <tt>false</tt>)
90594      */
90595
90596     componentLayout: 'textfield',
90597
90598     initComponent : function(){
90599         this.callParent();
90600         this.addEvents(
90601             /**
90602              * @event autosize
90603              * Fires when the <tt><b>{@link #autoSize}</b></tt> function is triggered and the field is
90604              * resized according to the {@link #grow}/{@link #growMin}/{@link #growMax} configs as a result.
90605              * This event provides a hook for the developer to apply additional logic at runtime to resize the
90606              * field if needed.
90607              * @param {Ext.form.field.Text} this This text field
90608              * @param {Number} width The new field width
90609              */
90610             'autosize',
90611
90612             /**
90613              * @event keydown
90614              * Keydown input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
90615              * is set to true.
90616              * @param {Ext.form.field.Text} this This text field
90617              * @param {Ext.EventObject} e
90618              */
90619             'keydown',
90620             /**
90621              * @event keyup
90622              * Keyup input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
90623              * is set to true.
90624              * @param {Ext.form.field.Text} this This text field
90625              * @param {Ext.EventObject} e
90626              */
90627             'keyup',
90628             /**
90629              * @event keypress
90630              * Keypress input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
90631              * is set to true.
90632              * @param {Ext.form.field.Text} this This text field
90633              * @param {Ext.EventObject} e
90634              */
90635             'keypress'
90636         );
90637     },
90638
90639     // private
90640     initEvents : function(){
90641         var me = this,
90642             el = me.inputEl;
90643         
90644         me.callParent();
90645         if(me.selectOnFocus || me.emptyText){
90646             me.mon(el, 'mousedown', me.onMouseDown, me);
90647         }
90648         if(me.maskRe || (me.vtype && me.disableKeyFilter !== true && (me.maskRe = Ext.form.field.VTypes[me.vtype+'Mask']))){
90649             me.mon(el, 'keypress', me.filterKeys, me);
90650         }
90651
90652         if (me.enableKeyEvents) {
90653             me.mon(el, {
90654                 scope: me,
90655                 keyup: me.onKeyUp,
90656                 keydown: me.onKeyDown,
90657                 keypress: me.onKeyPress
90658             });
90659         }
90660     },
90661
90662     /**
90663      * @private override - treat undefined and null values as equal to an empty string value
90664      */
90665     isEqual: function(value1, value2) {
90666         return String(Ext.value(value1, '')) === String(Ext.value(value2, ''));
90667     },
90668
90669     /**
90670      * @private
90671      * If grow=true, invoke the autoSize method when the field's value is changed.
90672      */
90673     onChange: function() {
90674         this.callParent();
90675         this.autoSize();
90676     },
90677     
90678     afterRender: function(){
90679         var me = this;
90680         if (me.enforceMaxLength) {
90681             me.inputEl.dom.maxLength = me.maxLength;
90682         }
90683         me.applyEmptyText();
90684         me.autoSize();
90685         me.callParent();
90686     },
90687
90688     onMouseDown: function(e){
90689         var me = this;
90690         if(!me.hasFocus){
90691             me.mon(me.inputEl, 'mouseup', Ext.emptyFn, me, { single: true, preventDefault: true });
90692         }
90693     },
90694
90695     /**
90696      * Performs any necessary manipulation of a raw String value to prepare it for {@link #stringToValue conversion}
90697      * and/or {@link #validate validation}. For text fields this applies the configured {@link #stripCharsRe} to the
90698      * raw value.
90699      * @param {String} value The unprocessed string value
90700      * @return {String} The processed string value
90701      */
90702     processRawValue: function(value) {
90703         var me = this,
90704             stripRe = me.stripCharsRe,
90705             newValue;
90706             
90707         if (stripRe) {
90708             newValue = value.replace(stripRe, '');
90709             if (newValue !== value) {
90710                 me.setRawValue(newValue);
90711                 value = newValue;
90712             }
90713         }
90714         return value;
90715     },
90716
90717     //private
90718     onDisable: function(){
90719         this.callParent();
90720         if (Ext.isIE) {
90721             this.inputEl.dom.unselectable = 'on';
90722         }
90723     },
90724
90725     //private
90726     onEnable: function(){
90727         this.callParent();
90728         if (Ext.isIE) {
90729             this.inputEl.dom.unselectable = '';
90730         }
90731     },
90732
90733     onKeyDown: function(e) {
90734         this.fireEvent('keydown', this, e);
90735     },
90736
90737     onKeyUp: function(e) {
90738         this.fireEvent('keyup', this, e);
90739     },
90740
90741     onKeyPress: function(e) {
90742         this.fireEvent('keypress', this, e);
90743     },
90744
90745     /**
90746      * Resets the current field value to the originally-loaded value and clears any validation messages.
90747      * Also adds <tt><b>{@link #emptyText}</b></tt> and <tt><b>{@link #emptyCls}</b></tt> if the
90748      * original value was blank.
90749      */
90750     reset : function(){
90751         this.callParent();
90752         this.applyEmptyText();
90753     },
90754
90755     applyEmptyText : function(){
90756         var me = this,
90757             emptyText = me.emptyText,
90758             isEmpty;
90759
90760         if (me.rendered && emptyText) {
90761             isEmpty = me.getRawValue().length < 1 && !me.hasFocus;
90762             
90763             if (Ext.supports.Placeholder) {
90764                 me.inputEl.dom.placeholder = emptyText;
90765             } else if (isEmpty) {
90766                 me.setRawValue(emptyText);
90767             }
90768             
90769             //all browsers need this because of a styling issue with chrome + placeholders.
90770             //the text isnt vertically aligned when empty (and using the placeholder)
90771             if (isEmpty) {
90772                 me.inputEl.addCls(me.emptyCls);
90773             }
90774
90775             me.autoSize();
90776         }
90777     },
90778
90779     // private
90780     preFocus : function(){
90781         var me = this,
90782             inputEl = me.inputEl,
90783             emptyText = me.emptyText,
90784             isEmpty;
90785
90786         if (emptyText && !Ext.supports.Placeholder && inputEl.dom.value === emptyText) {
90787             me.setRawValue('');
90788             isEmpty = true;
90789             inputEl.removeCls(me.emptyCls);
90790         } else if (Ext.supports.Placeholder) {
90791             me.inputEl.removeCls(me.emptyCls);
90792         }
90793         if (me.selectOnFocus || isEmpty) {
90794             inputEl.dom.select();
90795         }
90796     },
90797
90798     onFocus: function() {
90799         var me = this;
90800         me.callParent(arguments);
90801         if (me.emptyText) {
90802             me.autoSize();
90803         }
90804     },
90805
90806     // private
90807     postBlur : function(){
90808         this.applyEmptyText();
90809     },
90810
90811     // private
90812     filterKeys : function(e){
90813         if(e.ctrlKey){
90814             return;
90815         }
90816         var key = e.getKey(),
90817             charCode = String.fromCharCode(e.getCharCode());
90818             
90819         if(Ext.isGecko && (e.isNavKeyPress() || key === e.BACKSPACE || (key === e.DELETE && e.button === -1))){
90820             return;
90821         }
90822         
90823         if(!Ext.isGecko && e.isSpecialKey() && !charCode){
90824             return;
90825         }
90826         if(!this.maskRe.test(charCode)){
90827             e.stopEvent();
90828         }
90829     },
90830
90831     /**
90832      * Returns the raw String value of the field, without performing any normalization, conversion, or validation.
90833      * Gets the current value of the input element if the field has been rendered, ignoring the value if it is the
90834      * {@link #emptyText}. To get a normalized and converted value see {@link #getValue}.
90835      * @return {String} value The raw String value of the field
90836      */
90837     getRawValue: function() {
90838         var me = this,
90839             v = me.callParent();
90840         if (v === me.emptyText) {
90841             v = '';
90842         }
90843         return v;
90844     },
90845
90846     /**
90847      * Sets a data value into the field and runs the change detection and validation. Also applies any configured
90848      * {@link #emptyText} for text fields. To set the value directly without these inspections see {@link #setRawValue}.
90849      * @param {Mixed} value The value to set
90850      * @return {Ext.form.field.Text} this
90851      */
90852     setValue: function(value) {
90853         var me = this,
90854             inputEl = me.inputEl;
90855         
90856         if (inputEl && me.emptyText && !Ext.isEmpty(value)) {
90857             inputEl.removeCls(me.emptyCls);
90858         }
90859         
90860         me.callParent(arguments);
90861
90862         me.applyEmptyText();
90863         return me;
90864     },
90865
90866     /**
90867 Validates a value according to the field's validation rules and returns an array of errors
90868 for any failing validations. Validation rules are processed in the following order:
90869
90870 1. **Field specific validator**
90871     
90872     A validator offers a way to customize and reuse a validation specification.
90873     If a field is configured with a `{@link #validator}`
90874     function, it will be passed the current field value.  The `{@link #validator}`
90875     function is expected to return either:
90876     
90877     - Boolean `true`  if the value is valid (validation continues).
90878     - a String to represent the invalid message if invalid (validation halts).
90879
90880 2. **Basic Validation**
90881
90882     If the `{@link #validator}` has not halted validation,
90883     basic validation proceeds as follows:
90884     
90885     - `{@link #allowBlank}` : (Invalid message = `{@link #emptyText}`)
90886     
90887         Depending on the configuration of <code>{@link #allowBlank}</code>, a
90888         blank field will cause validation to halt at this step and return
90889         Boolean true or false accordingly.
90890     
90891     - `{@link #minLength}` : (Invalid message = `{@link #minLengthText}`)
90892
90893         If the passed value does not satisfy the `{@link #minLength}`
90894         specified, validation halts.
90895
90896     -  `{@link #maxLength}` : (Invalid message = `{@link #maxLengthText}`)
90897
90898         If the passed value does not satisfy the `{@link #maxLength}`
90899         specified, validation halts.
90900
90901 3. **Preconfigured Validation Types (VTypes)**
90902
90903     If none of the prior validation steps halts validation, a field
90904     configured with a `{@link #vtype}` will utilize the
90905     corresponding {@link Ext.form.field.VTypes VTypes} validation function.
90906     If invalid, either the field's `{@link #vtypeText}` or
90907     the VTypes vtype Text property will be used for the invalid message.
90908     Keystrokes on the field will be filtered according to the VTypes
90909     vtype Mask property.
90910
90911 4. **Field specific regex test**
90912
90913     If none of the prior validation steps halts validation, a field's
90914     configured <code>{@link #regex}</code> test will be processed.
90915     The invalid message for this test is configured with `{@link #regexText}`
90916
90917      * @param {Mixed} value The value to validate. The processed raw value will be used if nothing is passed
90918      * @return {Array} Array of any validation errors
90919      * @markdown
90920      */
90921     getErrors: function(value) {
90922         var me = this,
90923             errors = me.callParent(arguments),
90924             validator = me.validator,
90925             emptyText = me.emptyText,
90926             allowBlank = me.allowBlank,
90927             vtype = me.vtype,
90928             vtypes = Ext.form.field.VTypes,
90929             regex = me.regex,
90930             format = Ext.String.format,
90931             msg;
90932
90933         value = value || me.processRawValue(me.getRawValue());
90934
90935         if (Ext.isFunction(validator)) {
90936             msg = validator.call(me, value);
90937             if (msg !== true) {
90938                 errors.push(msg);
90939             }
90940         }
90941
90942         if (value.length < 1 || value === emptyText) {
90943             if (!allowBlank) {
90944                 errors.push(me.blankText);
90945             }
90946             //if value is blank, there cannot be any additional errors
90947             return errors;
90948         }
90949
90950         if (value.length < me.minLength) {
90951             errors.push(format(me.minLengthText, me.minLength));
90952         }
90953
90954         if (value.length > me.maxLength) {
90955             errors.push(format(me.maxLengthText, me.maxLength));
90956         }
90957
90958         if (vtype) {
90959             if(!vtypes[vtype](value, me)){
90960                 errors.push(me.vtypeText || vtypes[vtype +'Text']);
90961             }
90962         }
90963
90964         if (regex && !regex.test(value)) {
90965             errors.push(me.regexText || me.invalidText);
90966         }
90967
90968         return errors;
90969     },
90970
90971     /**
90972      * Selects text in this field
90973      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
90974      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
90975      */
90976     selectText : function(start, end){
90977         var me = this,
90978             v = me.getRawValue(),
90979             doFocus = true,
90980             el = me.inputEl.dom,
90981             undef,
90982             range;
90983             
90984         if (v.length > 0) {
90985             start = start === undef ? 0 : start;
90986             end = end === undef ? v.length : end;
90987             if (el.setSelectionRange) {
90988                 el.setSelectionRange(start, end);
90989             }
90990             else if(el.createTextRange) {
90991                 range = el.createTextRange();
90992                 range.moveStart('character', start);
90993                 range.moveEnd('character', end - v.length);
90994                 range.select();
90995             }
90996             doFocus = Ext.isGecko || Ext.isOpera;
90997         }
90998         if (doFocus) {
90999             me.focus();
91000         }
91001     },
91002
91003     /**
91004      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
91005      * This only takes effect if <tt>{@link #grow} = true</tt>, and fires the {@link #autosize} event if the
91006      * width changes.
91007      */
91008     autoSize: function() {
91009         var me = this,
91010             width;
91011         if (me.grow && me.rendered) {
91012             me.doComponentLayout();
91013             width = me.inputEl.getWidth();
91014             if (width !== me.lastInputWidth) {
91015                 me.fireEvent('autosize', width);
91016                 me.lastInputWidth = width;
91017             }
91018         }
91019     },
91020
91021     initAria: function() {
91022         this.callParent();
91023         this.getActionEl().dom.setAttribute('aria-required', this.allowBlank === false);
91024     },
91025
91026     /**
91027      * @protected override
91028      * To get the natural width of the inputEl, we do a simple calculation based on the
91029      * 'size' config. We use hard-coded numbers to approximate what browsers do natively,
91030      * to avoid having to read any styles which would hurt performance.
91031      */
91032     getBodyNaturalWidth: function() {
91033         return Math.round(this.size * 6.5) + 20;
91034     }
91035
91036 });
91037
91038 /**
91039  * @class Ext.form.field.TextArea
91040  * @extends Ext.form.field.Text
91041
91042 This class creates a multiline text field, which can be used as a direct replacement for traditional 
91043 textarea fields. In addition, it supports automatically {@link #grow growing} the height of the textarea to 
91044 fit its content.
91045
91046 All of the configuration options from {@link Ext.form.field.Text} can be used on TextArea.
91047 {@img Ext.form.TextArea/Ext.form.TextArea.png Ext.form.TextArea component}
91048 Example usage:
91049
91050     Ext.create('Ext.form.FormPanel', {
91051         title      : 'Sample TextArea',
91052         width      : 400,
91053         bodyPadding: 10,
91054         renderTo   : Ext.getBody(),
91055         items: [{
91056             xtype     : 'textareafield',
91057             grow      : true,
91058             name      : 'message',
91059             fieldLabel: 'Message',
91060             anchor    : '100%'
91061         }]
91062     }); 
91063
91064 Some other useful configuration options when using {@link #grow} are {@link #growMin} and {@link #growMax}. These 
91065 allow you to set the minimum and maximum grow heights for the textarea.
91066
91067  * @constructor
91068  * Creates a new TextArea
91069  * @param {Object} config Configuration options
91070  * @xtype textareafield
91071  * @docauthor Robert Dougan <rob@sencha.com>
91072  */
91073 Ext.define('Ext.form.field.TextArea', {
91074     extend:'Ext.form.field.Text',
91075     alias: ['widget.textareafield', 'widget.textarea'],
91076     alternateClassName: 'Ext.form.TextArea',
91077     requires: ['Ext.XTemplate', 'Ext.layout.component.field.TextArea'],
91078
91079     fieldSubTpl: [
91080         '<textarea id="{id}" ',
91081             '<tpl if="name">name="{name}" </tpl>',
91082             '<tpl if="rows">rows="{rows}" </tpl>',
91083             '<tpl if="cols">cols="{cols}" </tpl>',
91084             '<tpl if="tabIdx">tabIndex="{tabIdx}" </tpl>',
91085             'class="{fieldCls} {typeCls}" ',
91086             'autocomplete="off">',
91087         '</textarea>',
91088         {
91089             compiled: true,
91090             disableFormats: true
91091         }
91092     ],
91093
91094     /**
91095      * @cfg {Number} growMin The minimum height to allow when <tt>{@link Ext.form.field.Text#grow grow}=true</tt>
91096      * (defaults to <tt>60</tt>)
91097      */
91098     growMin: 60,
91099
91100     /**
91101      * @cfg {Number} growMax The maximum height to allow when <tt>{@link Ext.form.field.Text#grow grow}=true</tt>
91102      * (defaults to <tt>1000</tt>)
91103      */
91104     growMax: 1000,
91105
91106     /**
91107      * @cfg {String} growAppend
91108      * A string that will be appended to the field's current value for the purposes of calculating the target
91109      * field size. Only used when the {@link #grow} config is <tt>true</tt>. Defaults to a newline for TextArea
91110      * to ensure there is always a space below the current line.
91111      */
91112     growAppend: '\n-',
91113
91114     /**
91115      * @cfg {Number} cols An initial value for the 'cols' attribute on the textarea element. This is only
91116      * used if the component has no configured {@link #width} and is not given a width by its container's
91117      * layout. Defaults to <tt>20</tt>.
91118      */
91119     cols: 20,
91120
91121     /**
91122      * @cfg {Number} cols An initial value for the 'cols' attribute on the textarea element. This is only
91123      * used if the component has no configured {@link #width} and is not given a width by its container's
91124      * layout. Defaults to <tt>4</tt>.
91125      */
91126     rows: 4,
91127
91128     /**
91129      * @cfg {Boolean} enterIsSpecial
91130      * True if you want the enter key to be classed as a <tt>special</tt> key. Special keys are generally navigation
91131      * keys (arrows, space, enter). Setting the config property to <tt>true</tt> would mean that you could not insert
91132      * returns into the textarea.
91133      * (defaults to <tt>false</tt>)
91134      */
91135     enterIsSpecial: false,
91136
91137     /**
91138      * @cfg {Boolean} preventScrollbars <tt>true</tt> to prevent scrollbars from appearing regardless of how much text is
91139      * in the field. This option is only relevant when {@link #grow} is <tt>true</tt>. Equivalent to setting overflow: hidden, defaults to
91140      * <tt>false</tt>.
91141      */
91142     preventScrollbars: false,
91143
91144     // private
91145     componentLayout: 'textareafield',
91146
91147     // private
91148     onRender: function(ct, position) {
91149         var me = this;
91150         Ext.applyIf(me.subTplData, {
91151             cols: me.cols,
91152             rows: me.rows
91153         });
91154
91155         me.callParent(arguments);
91156     },
91157
91158     // private
91159     afterRender: function(){
91160         var me = this;
91161
91162         me.callParent(arguments);
91163
91164         if (me.grow) {
91165             if (me.preventScrollbars) {
91166                 me.inputEl.setStyle('overflow', 'hidden');
91167             }
91168             me.inputEl.setHeight(me.growMin);
91169         }
91170     },
91171
91172     // private
91173     fireKey: function(e) {
91174         if (e.isSpecialKey() && (this.enterIsSpecial || (e.getKey() !== e.ENTER || e.hasModifier()))) {
91175             this.fireEvent('specialkey', this, e);
91176         }
91177     },
91178
91179     /**
91180      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
91181      * This only takes effect if <tt>{@link #grow} = true</tt>, and fires the {@link #autosize} event if
91182      * the height changes.
91183      */
91184     autoSize: function() {
91185         var me = this,
91186             height;
91187
91188         if (me.grow && me.rendered) {
91189             me.doComponentLayout();
91190             height = me.inputEl.getHeight();
91191             if (height !== me.lastInputHeight) {
91192                 me.fireEvent('autosize', height);
91193                 me.lastInputHeight = height;
91194             }
91195         }
91196     },
91197
91198     // private
91199     initAria: function() {
91200         this.callParent(arguments);
91201         this.getActionEl().dom.setAttribute('aria-multiline', true);
91202     },
91203
91204     /**
91205      * @protected override
91206      * To get the natural width of the textarea element, we do a simple calculation based on the
91207      * 'cols' config. We use hard-coded numbers to approximate what browsers do natively,
91208      * to avoid having to read any styles which would hurt performance.
91209      */
91210     getBodyNaturalWidth: function() {
91211         return Math.round(this.cols * 6.5) + 20;
91212     }
91213
91214 });
91215
91216
91217 /**
91218  * @class Ext.window.MessageBox
91219  * @extends Ext.window.Window
91220
91221 Utility class for generating different styles of message boxes.  The singleton instance, `Ext.Msg` can also be used.
91222 Note that a MessageBox is asynchronous.  Unlike a regular JavaScript `alert` (which will halt
91223 browser execution), showing a MessageBox will not cause the code to stop.  For this reason, if you have code
91224 that should only run *after* some user feedback from the MessageBox, you must use a callback function
91225 (see the `function` parameter for {@link #show} for more details).
91226
91227 {@img Ext.window.MessageBox/messagebox1.png alert MessageBox}
91228 {@img Ext.window.MessageBox/messagebox2.png prompt MessageBox}
91229 {@img Ext.window.MessageBox/messagebox3.png show MessageBox}
91230 #Example usage:#
91231
91232     // Basic alert:
91233     Ext.Msg.alert('Status', 'Changes saved successfully.');
91234
91235     // Prompt for user data and process the result using a callback:
91236     Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
91237         if (btn == 'ok'){
91238             // process text value and close...
91239         }
91240     });
91241
91242     // Show a dialog using config options:
91243     Ext.Msg.show({
91244          title:'Save Changes?',
91245          msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?',
91246          buttons: Ext.Msg.YESNOCANCEL,
91247          fn: processResult,
91248          animateTarget: 'elId',
91249          icon: Ext.window.MessageBox.QUESTION
91250     });
91251
91252  * @markdown
91253  * @singleton
91254  * @xtype messagebox
91255  */
91256 Ext.define('Ext.window.MessageBox', {
91257     extend: 'Ext.window.Window',
91258
91259     requires: [
91260         'Ext.toolbar.Toolbar',
91261         'Ext.form.field.Text',
91262         'Ext.form.field.TextArea',
91263         'Ext.button.Button',
91264         'Ext.layout.container.Anchor',
91265         'Ext.layout.container.HBox',
91266         'Ext.ProgressBar'
91267     ],
91268     
91269     alternateClassName: 'Ext.MessageBox',
91270
91271     alias: 'widget.messagebox',
91272
91273     /**
91274      * Button config that displays a single OK button
91275      * @type Number
91276      */
91277     OK : 1,
91278     /**
91279      * Button config that displays a single Yes button
91280      * @type Number
91281      */
91282     YES : 2,
91283     /**
91284      * Button config that displays a single No button
91285      * @type Number
91286      */
91287     NO : 4,
91288     /**
91289      * Button config that displays a single Cancel button
91290      * @type Number
91291      */
91292     CANCEL : 8,
91293     /**
91294      * Button config that displays OK and Cancel buttons
91295      * @type Number
91296      */
91297     OKCANCEL : 9,
91298     /**
91299      * Button config that displays Yes and No buttons
91300      * @type Number
91301      */
91302     YESNO : 6,
91303     /**
91304      * Button config that displays Yes, No and Cancel buttons
91305      * @type Number
91306      */
91307     YESNOCANCEL : 14,
91308     /**
91309      * The CSS class that provides the INFO icon image
91310      * @type String
91311      */
91312     INFO : 'ext-mb-info',
91313     /**
91314      * The CSS class that provides the WARNING icon image
91315      * @type String
91316      */
91317     WARNING : 'ext-mb-warning',
91318     /**
91319      * The CSS class that provides the QUESTION icon image
91320      * @type String
91321      */
91322     QUESTION : 'ext-mb-question',
91323     /**
91324      * The CSS class that provides the ERROR icon image
91325      * @type String
91326      */
91327     ERROR : 'ext-mb-error',
91328
91329     // hide it by offsets. Windows are hidden on render by default.
91330     hideMode: 'offsets',
91331     closeAction: 'hide',
91332     resizable: false,
91333     title: '&#160;',
91334
91335     width: 600,
91336     height: 500,
91337     minWidth: 250,
91338     maxWidth: 600,
91339     minHeight: 110,
91340     maxHeight: 500,
91341     constrain: true,
91342
91343     cls: Ext.baseCSSPrefix + 'message-box',
91344
91345     layout: {
91346         type: 'anchor'
91347     },
91348
91349     /**
91350      * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
91351      * @type Number
91352      */
91353     defaultTextHeight : 75,
91354     /**
91355      * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
91356      * for setting a different minimum width than text-only dialogs may need (defaults to 250).
91357      * @type Number
91358      */
91359     minProgressWidth : 250,
91360     /**
91361      * The minimum width in pixels of the message box if it is a prompt dialog.  This is useful
91362      * for setting a different minimum width than text-only dialogs may need (defaults to 250).
91363      * @type Number
91364      */
91365     minPromptWidth: 250,
91366     /**
91367      * An object containing the default button text strings that can be overriden for localized language support.
91368      * Supported properties are: ok, cancel, yes and no.  Generally you should include a locale-specific
91369      * resource file for handling language support across the framework.
91370      * Customize the default text like so: Ext.window.MessageBox.buttonText.yes = "oui"; //french
91371      * @type Object
91372      */
91373     buttonText: {
91374         ok: 'OK',
91375         yes: 'Yes',
91376         no: 'No',
91377         cancel: 'Cancel'
91378     },
91379
91380     buttonIds: [
91381         'ok', 'yes', 'no', 'cancel'
91382     ],
91383
91384     titleText: {
91385         confirm: 'Confirm',
91386         prompt: 'Prompt',
91387         wait: 'Loading...',
91388         alert: 'Attention'
91389     },
91390     
91391     iconHeight: 35,
91392
91393     makeButton: function(btnIdx) {
91394         var btnId = this.buttonIds[btnIdx];
91395         return Ext.create('Ext.button.Button', {
91396             handler: this.btnCallback,
91397             itemId: btnId,
91398             scope: this,
91399             text: this.buttonText[btnId],
91400             minWidth: 75
91401         });
91402     },
91403
91404     btnCallback: function(btn) {
91405         var me = this,
91406             value,
91407             field;
91408
91409         if (me.cfg.prompt || me.cfg.multiline) {
91410             if (me.cfg.multiline) {
91411                 field = me.textArea;
91412             } else {
91413                 field = me.textField;
91414             }
91415             value = field.getValue();
91416             field.reset();
91417         }
91418
91419         // Important not to have focus remain in the hidden Window; Interferes with DnD.
91420         btn.blur();
91421         me.hide();
91422         me.userCallback(btn.itemId, value, me.cfg);
91423     },
91424
91425     hide: function() {
91426         var me = this;
91427         me.dd.endDrag();
91428         me.progressBar.reset();
91429         me.removeCls(me.cfg.cls);
91430         me.callParent();
91431     },
91432
91433     initComponent: function() {
91434         var me = this,
91435             i, button;
91436
91437         me.title = '&#160;';
91438
91439         me.topContainer = Ext.create('Ext.container.Container', {
91440             anchor: '100%',
91441             style: {
91442                 padding: '10px',
91443                 overflow: 'hidden'
91444             },
91445             items: [
91446                 me.iconComponent = Ext.create('Ext.Component', {
91447                     cls: 'ext-mb-icon',
91448                     width: 50,
91449                     height: me.iconHeight,
91450                     style: {
91451                         'float': 'left'
91452                     }
91453                 }),
91454                 me.promptContainer = Ext.create('Ext.container.Container', {
91455                     layout: {
91456                         type: 'anchor'
91457                     },
91458                     items: [
91459                         me.msg = Ext.create('Ext.Component', {
91460                             autoEl: { tag: 'span' },
91461                             cls: 'ext-mb-text'
91462                         }),
91463                         me.textField = Ext.create('Ext.form.field.Text', {
91464                             anchor: '100%',
91465                             enableKeyEvents: true,
91466                             listeners: {
91467                                 keydown: me.onPromptKey,
91468                                 scope: me
91469                             }
91470                         }),
91471                         me.textArea = Ext.create('Ext.form.field.TextArea', {
91472                             anchor: '100%',
91473                             height: 75
91474                         })
91475                     ]
91476                 })
91477             ]
91478         });
91479         me.progressBar = Ext.create('Ext.ProgressBar', {
91480             anchor: '-10',
91481             style: 'margin-left:10px'
91482         });
91483
91484         me.items = [me.topContainer, me.progressBar];
91485
91486         // Create the buttons based upon passed bitwise config
91487         me.msgButtons = [];
91488         for (i = 0; i < 4; i++) {
91489             button = me.makeButton(i);
91490             me.msgButtons[button.itemId] = button;
91491             me.msgButtons.push(button);
91492         }
91493         me.bottomTb = Ext.create('Ext.toolbar.Toolbar', {
91494             ui: 'footer',
91495             dock: 'bottom',
91496             layout: {
91497                 pack: 'center'
91498             },
91499             items: [
91500                 me.msgButtons[0],
91501                 me.msgButtons[1],
91502                 me.msgButtons[2],
91503                 me.msgButtons[3]
91504             ]
91505         });
91506         me.dockedItems = [me.bottomTb];
91507
91508         me.callParent();
91509     },
91510
91511     onPromptKey: function(textField, e) {
91512         var me = this,
91513             blur;
91514             
91515         if (e.keyCode === Ext.EventObject.RETURN || e.keyCode === 10) {
91516             if (me.msgButtons.ok.isVisible()) {
91517                 blur = true;
91518                 me.msgButtons.ok.handler.call(me, me.msgButtons.ok);
91519             } else if (me.msgButtons.yes.isVisible()) {
91520                 me.msgButtons.yes.handler.call(me, me.msgButtons.yes);
91521                 blur = true;
91522             }
91523             
91524             if (blur) {
91525                 me.textField.blur();
91526             }
91527         }
91528     },
91529
91530     reconfigure: function(cfg) {
91531         var me = this,
91532             buttons = cfg.buttons || 0,
91533             hideToolbar = true,
91534             initialWidth = me.maxWidth,
91535             i;
91536
91537         cfg = cfg || {};
91538         me.cfg = cfg;
91539         if (cfg.width) {
91540             initialWidth = cfg.width;
91541         }
91542
91543         // Default to allowing the Window to take focus.
91544         delete me.defaultFocus;
91545         
91546         // clear any old animateTarget
91547         me.animateTarget = cfg.animateTarget || undefined;
91548
91549         // Defaults to modal
91550         me.modal = cfg.modal !== false;
91551
91552         // Show the title
91553         if (cfg.title) {
91554             me.setTitle(cfg.title||'&#160;');
91555         }
91556
91557         if (!me.rendered) {
91558             me.width = initialWidth;
91559             me.render(Ext.getBody());
91560         } else {
91561             me.setSize(initialWidth, me.maxHeight);
91562         }
91563         me.setPosition(-10000, -10000);
91564
91565         // Hide or show the close tool
91566         me.closable = cfg.closable && !cfg.wait;
91567         if (cfg.closable === false) {
91568             me.tools.close.hide();
91569         } else {
91570             me.tools.close.show();
91571         }
91572
91573         // Hide or show the header
91574         if (!cfg.title && !me.closable) {
91575             me.header.hide();
91576         } else {
91577             me.header.show();
91578         }
91579
91580         // Default to dynamic drag: drag the window, not a ghost
91581         me.liveDrag = !cfg.proxyDrag;
91582
91583         // wrap the user callback
91584         me.userCallback = Ext.Function.bind(cfg.callback ||cfg.fn || Ext.emptyFn, cfg.scope || Ext.global);
91585
91586         // Hide or show the icon Component
91587         me.setIcon(cfg.icon);
91588
91589         // Hide or show the message area
91590         if (cfg.msg) {
91591             me.msg.update(cfg.msg);
91592             me.msg.show();
91593         } else {
91594             me.msg.hide();
91595         }
91596
91597         // Hide or show the input field
91598         if (cfg.prompt || cfg.multiline) {
91599             me.multiline = cfg.multiline;
91600             if (cfg.multiline) {
91601                 me.textArea.setValue(cfg.value);
91602                 me.textArea.setHeight(cfg.defaultTextHeight || me.defaultTextHeight);
91603                 me.textArea.show();
91604                 me.textField.hide();
91605                 me.defaultFocus = me.textArea;
91606             } else {
91607                 me.textField.setValue(cfg.value);
91608                 me.textArea.hide();
91609                 me.textField.show();
91610                 me.defaultFocus = me.textField;
91611             }
91612         } else {
91613             me.textArea.hide();
91614             me.textField.hide();
91615         }
91616
91617         // Hide or show the progress bar
91618         if (cfg.progress || cfg.wait) {
91619             me.progressBar.show();
91620             me.updateProgress(0, cfg.progressText);
91621             if(cfg.wait === true){
91622                 me.progressBar.wait(cfg.waitConfig);
91623             }
91624         } else {
91625             me.progressBar.hide();
91626         }
91627
91628         // Hide or show buttons depending on flag value sent.
91629         for (i = 0; i < 4; i++) {
91630             if (buttons & Math.pow(2, i)) {
91631
91632                 // Default to focus on the first visible button if focus not already set
91633                 if (!me.defaultFocus) {
91634                     me.defaultFocus = me.msgButtons[i];
91635                 }
91636                 me.msgButtons[i].show();
91637                 hideToolbar = false;
91638             } else {
91639                 me.msgButtons[i].hide();
91640             }
91641         }
91642
91643         // Hide toolbar if no buttons to show
91644         if (hideToolbar) {
91645             me.bottomTb.hide();
91646         } else {
91647             me.bottomTb.show();
91648         }
91649         me.hidden = true;
91650     },
91651
91652     /**
91653      * Displays a new message box, or reinitializes an existing message box, based on the config options
91654      * passed in. All display functions (e.g. prompt, alert, etc.) on MessageBox call this function internally,
91655      * although those calls are basic shortcuts and do not support all of the config options allowed here.
91656      * @param {Object} config The following config options are supported: <ul>
91657      * <li><b>animateTarget</b> : String/Element<div class="sub-desc">An id or Element from which the message box should animate as it
91658      * opens and closes (defaults to undefined)</div></li>
91659      * <li><b>buttons</b> : Number<div class="sub-desc">A bitwise button specifier consisting of the sum of any of the following constants:<ul>
91660      * <li>Ext.window.MessageBox.OK</li>
91661      * <li>Ext.window.MessageBox.YES</li>
91662      * <li>Ext.window.MessageBox.NO</li>
91663      * <li>Ext.window.MessageBox.CANCEL</li>
91664      * </ul>Or false to not show any buttons (defaults to false)</div></li>
91665      * <li><b>closable</b> : Boolean<div class="sub-desc">False to hide the top-right close button (defaults to true). Note that
91666      * progress and wait dialogs will ignore this property and always hide the close button as they can only
91667      * be closed programmatically.</div></li>
91668      * <li><b>cls</b> : String<div class="sub-desc">A custom CSS class to apply to the message box's container element</div></li>
91669      * <li><b>defaultTextHeight</b> : Number<div class="sub-desc">The default height in pixels of the message box's multiline textarea
91670      * if displayed (defaults to 75)</div></li>
91671      * <li><b>fn</b> : Function<div class="sub-desc">A callback function which is called when the dialog is dismissed either
91672      * by clicking on the configured buttons, or on the dialog close button, or by pressing
91673      * the return button to enter input.
91674      * <p>Progress and wait dialogs will ignore this option since they do not respond to user
91675      * actions and can only be closed programmatically, so any required function should be called
91676      * by the same code after it closes the dialog. Parameters passed:<ul>
91677      * <li><b>buttonId</b> : String<div class="sub-desc">The ID of the button pressed, one of:<div class="sub-desc"><ul>
91678      * <li><tt>ok</tt></li>
91679      * <li><tt>yes</tt></li>
91680      * <li><tt>no</tt></li>
91681      * <li><tt>cancel</tt></li>
91682      * </ul></div></div></li>
91683      * <li><b>text</b> : String<div class="sub-desc">Value of the input field if either <tt><a href="#show-option-prompt" ext:member="show-option-prompt" ext:cls="Ext.window.MessageBox">prompt</a></tt>
91684      * or <tt><a href="#show-option-multiline" ext:member="show-option-multiline" ext:cls="Ext.window.MessageBox">multiline</a></tt> is true</div></li>
91685      * <li><b>opt</b> : Object<div class="sub-desc">The config object passed to show.</div></li>
91686      * </ul></p></div></li>
91687      * <li><b>scope</b> : Object<div class="sub-desc">The scope (<code>this</code> reference) in which the function will be executed.</div></li>
91688      * <li><b>icon</b> : String<div class="sub-desc">A CSS class that provides a background image to be used as the body icon for the
91689      * dialog (e.g. Ext.window.MessageBox.WARNING or 'custom-class') (defaults to '')</div></li>
91690      * <li><b>iconCls</b> : String<div class="sub-desc">The standard {@link Ext.window.Window#iconCls} to
91691      * add an optional header icon (defaults to '')</div></li>
91692      * <li><b>maxWidth</b> : Number<div class="sub-desc">The maximum width in pixels of the message box (defaults to 600)</div></li>
91693      * <li><b>minWidth</b> : Number<div class="sub-desc">The minimum width in pixels of the message box (defaults to 100)</div></li>
91694      * <li><b>modal</b> : Boolean<div class="sub-desc">False to allow user interaction with the page while the message box is
91695      * displayed (defaults to true)</div></li>
91696      * <li><b>msg</b> : String<div class="sub-desc">A string that will replace the existing message box body text (defaults to the
91697      * XHTML-compliant non-breaking space character '&amp;#160;')</div></li>
91698      * <li><a id="show-option-multiline"></a><b>multiline</b> : Boolean<div class="sub-desc">
91699      * True to prompt the user to enter multi-line text (defaults to false)</div></li>
91700      * <li><b>progress</b> : Boolean<div class="sub-desc">True to display a progress bar (defaults to false)</div></li>
91701      * <li><b>progressText</b> : String<div class="sub-desc">The text to display inside the progress bar if progress = true (defaults to '')</div></li>
91702      * <li><a id="show-option-prompt"></a><b>prompt</b> : Boolean<div class="sub-desc">True to prompt the user to enter single-line text (defaults to false)</div></li>
91703      * <li><b>proxyDrag</b> : Boolean<div class="sub-desc">True to display a lightweight proxy while dragging (defaults to false)</div></li>
91704      * <li><b>title</b> : String<div class="sub-desc">The title text</div></li>
91705      * <li><b>value</b> : String<div class="sub-desc">The string value to set into the active textbox element if displayed</div></li>
91706      * <li><b>wait</b> : Boolean<div class="sub-desc">True to display a progress bar (defaults to false)</div></li>
91707      * <li><b>waitConfig</b> : Object<div class="sub-desc">A {@link Ext.ProgressBar#waitConfig} object (applies only if wait = true)</div></li>
91708      * <li><b>width</b> : Number<div class="sub-desc">The width of the dialog in pixels</div></li>
91709      * </ul>
91710      * Example usage:
91711      * <pre><code>
91712 Ext.Msg.show({
91713 title: 'Address',
91714 msg: 'Please enter your address:',
91715 width: 300,
91716 buttons: Ext.window.MessageBox.OKCANCEL,
91717 multiline: true,
91718 fn: saveAddress,
91719 animateTarget: 'addAddressBtn',
91720 icon: Ext.window.MessageBox.INFO
91721 });
91722 </code></pre>
91723      * @return {Ext.window.MessageBox} this
91724      */
91725     show: function(cfg) {
91726         var me = this;
91727             
91728         me.reconfigure(cfg);
91729         me.addCls(cfg.cls);
91730         if (cfg.animateTarget) {
91731             me.doAutoSize(false);
91732             me.callParent();
91733         } else {
91734             me.callParent();
91735             me.doAutoSize(true);
91736         }
91737         return me;
91738     },
91739     
91740     afterShow: function(){
91741         if (this.animateTarget) {
91742             this.center();
91743         }    
91744         this.callParent(arguments);
91745     },
91746
91747     doAutoSize: function(center) {
91748         var me = this,
91749             icon = me.iconComponent,
91750             iconHeight = me.iconHeight;
91751
91752         if (!Ext.isDefined(me.frameWidth)) {
91753             me.frameWidth = me.el.getWidth() - me.body.getWidth();
91754         }
91755         
91756         // reset to the original dimensions
91757         icon.setHeight(iconHeight);
91758
91759         // Allow per-invocation override of minWidth
91760         me.minWidth = me.cfg.minWidth || Ext.getClass(this).prototype.minWidth;
91761
91762         // Set best possible size based upon allowing the text to wrap in the maximized Window, and
91763         // then constraining it to within the max with. Then adding up constituent element heights.
91764         me.topContainer.doLayout();
91765         if (Ext.isIE6 || Ext.isIEQuirks) {
91766             // In IE quirks, the initial full width of the prompt fields will prevent the container element
91767             // from collapsing once sized down, so temporarily force them to a small width. They'll get
91768             // layed out to their final width later when setting the final window size.
91769             me.textField.setCalculatedSize(9);
91770             me.textArea.setCalculatedSize(9);
91771         }
91772         var width = me.cfg.width || me.msg.getWidth() + icon.getWidth() + 25, /* topContainer's layout padding */
91773             height = (me.header.rendered ? me.header.getHeight() : 0) +
91774             Math.max(me.promptContainer.getHeight(), icon.getHeight()) +
91775             me.progressBar.getHeight() +
91776             (me.bottomTb.rendered ? me.bottomTb.getHeight() : 0) + 20 ;/* topContainer's layout padding */
91777
91778         // Update to the size of the content, this way the text won't wrap under the icon.
91779         icon.setHeight(Math.max(iconHeight, me.msg.getHeight()));
91780         me.setSize(width + me.frameWidth, height + me.frameWidth);
91781         if (center) {
91782             me.center();
91783         }
91784         return me;
91785     },
91786
91787     updateText: function(text) {
91788         this.msg.update(text);
91789         return this.doAutoSize(true);
91790     },
91791
91792     /**
91793      * Adds the specified icon to the dialog.  By default, the class 'ext-mb-icon' is applied for default
91794      * styling, and the class passed in is expected to supply the background image url. Pass in empty string ('')
91795      * to clear any existing icon. This method must be called before the MessageBox is shown.
91796      * The following built-in icon classes are supported, but you can also pass in a custom class name:
91797      * <pre>
91798 Ext.window.MessageBox.INFO
91799 Ext.window.MessageBox.WARNING
91800 Ext.window.MessageBox.QUESTION
91801 Ext.window.MessageBox.ERROR
91802      *</pre>
91803      * @param {String} icon A CSS classname specifying the icon's background image url, or empty string to clear the icon
91804      * @return {Ext.window.MessageBox} this
91805      */
91806     setIcon : function(icon) {
91807         var me = this;
91808         me.iconComponent.removeCls(me.iconCls);
91809         if (icon) {
91810             me.iconComponent.show();
91811             me.iconComponent.addCls(Ext.baseCSSPrefix + 'dlg-icon');
91812             me.iconComponent.addCls(me.iconCls = icon);
91813         } else {
91814             me.iconComponent.removeCls(Ext.baseCSSPrefix + 'dlg-icon');
91815             me.iconComponent.hide();
91816         }
91817         return me;
91818     },
91819
91820     /**
91821      * Updates a progress-style message box's text and progress bar. Only relevant on message boxes
91822      * initiated via {@link Ext.window.MessageBox#progress} or {@link Ext.window.MessageBox#wait},
91823      * or by calling {@link Ext.window.MessageBox#show} with progress: true.
91824      * @param {Number} value Any number between 0 and 1 (e.g., .5, defaults to 0)
91825      * @param {String} progressText The progress text to display inside the progress bar (defaults to '')
91826      * @param {String} msg The message box's body text is replaced with the specified string (defaults to undefined
91827      * so that any existing body text will not get overwritten by default unless a new value is passed in)
91828      * @return {Ext.window.MessageBox} this
91829      */
91830     updateProgress : function(value, progressText, msg){
91831         this.progressBar.updateProgress(value, progressText);
91832         if (msg){
91833             this.updateText(msg);
91834         }
91835         return this;
91836     },
91837
91838     onEsc: function() {
91839         if (this.closable !== false) {
91840             this.callParent(arguments);
91841         }
91842     },
91843
91844     /**
91845      * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's confirm).
91846      * If a callback function is passed it will be called after the user clicks either button,
91847      * and the id of the button that was clicked will be passed as the only parameter to the callback
91848      * (could also be the top-right close button).
91849      * @param {String} title The title bar text
91850      * @param {String} msg The message box body text
91851      * @param {Function} fn (optional) The callback function invoked after the message box is closed
91852      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow.
91853      * @return {Ext.window.MessageBox} this
91854      */
91855     confirm: function(cfg, msg, fn, scope) {
91856         if (Ext.isString(cfg)) {
91857             cfg = {
91858                 title: cfg,
91859                 icon: 'ext-mb-question',
91860                 msg: msg,
91861                 buttons: this.YESNO,
91862                 callback: fn,
91863                 scope: scope
91864             };
91865         }
91866         return this.show(cfg);
91867     },
91868
91869     /**
91870      * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to JavaScript's prompt).
91871      * The prompt can be a single-line or multi-line textbox.  If a callback function is passed it will be called after the user
91872      * clicks either button, and the id of the button that was clicked (could also be the top-right
91873      * close button) and the text that was entered will be passed as the two parameters to the callback.
91874      * @param {String} title The title bar text
91875      * @param {String} msg The message box body text
91876      * @param {Function} fn (optional) The callback function invoked after the message box is closed
91877      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow.
91878      * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
91879      * property, or the height in pixels to create the textbox (defaults to false / single-line)
91880      * @param {String} value (optional) Default value of the text input element (defaults to '')
91881      * @return {Ext.window.MessageBox} this
91882      */
91883     prompt : function(cfg, msg, fn, scope, multiline, value){
91884         if (Ext.isString(cfg)) {
91885             cfg = {
91886                 prompt: true,
91887                 title: cfg,
91888                 minWidth: this.minPromptWidth,
91889                 msg: msg,
91890                 buttons: this.OKCANCEL,
91891                 callback: fn,
91892                 scope: scope,
91893                 multiline: multiline,
91894                 value: value
91895             };
91896         }
91897         return this.show(cfg);
91898     },
91899
91900     /**
91901      * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
91902      * interaction while waiting for a long-running process to complete that does not have defined intervals.
91903      * You are responsible for closing the message box when the process is complete.
91904      * @param {String} msg The message box body text
91905      * @param {String} title (optional) The title bar text
91906      * @param {Object} config (optional) A {@link Ext.ProgressBar#waitConfig} object
91907      * @return {Ext.window.MessageBox} this
91908      */
91909     wait : function(cfg, title, config){
91910         if (Ext.isString(cfg)) {
91911             cfg = {
91912                 title : title,
91913                 msg : cfg,
91914                 closable: false,
91915                 wait: true,
91916                 modal: true,
91917                 minWidth: this.minProgressWidth,
91918                 waitConfig: config
91919             };
91920         }
91921         return this.show(cfg);
91922     },
91923
91924     /**
91925      * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript alert prompt).
91926      * If a callback function is passed it will be called after the user clicks the button, and the
91927      * id of the button that was clicked will be passed as the only parameter to the callback
91928      * (could also be the top-right close button).
91929      * @param {String} title The title bar text
91930      * @param {String} msg The message box body text
91931      * @param {Function} fn (optional) The callback function invoked after the message box is closed
91932      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow.
91933      * @return {Ext.window.MessageBox} this
91934      */
91935     alert: function(cfg, msg, fn, scope) {
91936         if (Ext.isString(cfg)) {
91937             cfg = {
91938                 title : cfg,
91939                 msg : msg,
91940                 buttons: this.OK,
91941                 fn: fn,
91942                 scope : scope,
91943                 minWidth: this.minWidth
91944             };
91945         }
91946         return this.show(cfg);
91947     },
91948
91949     /**
91950      * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
91951      * the user.  You are responsible for updating the progress bar as needed via {@link Ext.window.MessageBox#updateProgress}
91952      * and closing the message box when the process is complete.
91953      * @param {String} title The title bar text
91954      * @param {String} msg The message box body text
91955      * @param {String} progressText (optional) The text to display inside the progress bar (defaults to '')
91956      * @return {Ext.window.MessageBox} this
91957      */
91958     progress : function(cfg, msg, progressText){
91959         if (Ext.isString(cfg)) {
91960             cfg = {
91961                 title: cfg,
91962                 msg: msg,
91963                 progressText: progressText
91964             };
91965         }
91966         return this.show(cfg);
91967     }
91968 }, function() {
91969     Ext.MessageBox = Ext.Msg = new this();
91970 });
91971 /**
91972  * @class Ext.form.Basic
91973  * @extends Ext.util.Observable
91974
91975 Provides input field management, validation, submission, and form loading services for the collection
91976 of {@link Ext.form.field.Field Field} instances within a {@link Ext.container.Container}. It is recommended
91977 that you use a {@link Ext.form.Panel} as the form container, as that has logic to automatically
91978 hook up an instance of {@link Ext.form.Basic} (plus other conveniences related to field configuration.)
91979
91980 #Form Actions#
91981
91982 The Basic class delegates the handling of form loads and submits to instances of {@link Ext.form.action.Action}.
91983 See the various Action implementations for specific details of each one's functionality, as well as the
91984 documentation for {@link #doAction} which details the configuration options that can be specified in
91985 each action call.
91986
91987 The default submit Action is {@link Ext.form.action.Submit}, which uses an Ajax request to submit the
91988 form's values to a configured URL. To enable normal browser submission of an Ext form, use the
91989 {@link #standardSubmit} config option.
91990
91991 Note: File uploads are not performed using normal 'Ajax' techniques; see the description for
91992 {@link #hasUpload} for details.
91993
91994 #Example usage:#
91995
91996     Ext.create('Ext.form.Panel', {
91997         title: 'Basic Form',
91998         renderTo: Ext.getBody(),
91999         bodyPadding: 5,
92000         width: 350,
92001
92002         // Any configuration items here will be automatically passed along to
92003         // the Ext.form.Basic instance when it gets created.
92004
92005         // The form will submit an AJAX request to this URL when submitted
92006         url: 'save-form.php',
92007
92008         items: [{
92009             fieldLabel: 'Field',
92010             name: 'theField'
92011         }],
92012
92013         buttons: [{
92014             text: 'Submit',
92015             handler: function() {
92016                 // The getForm() method returns the Ext.form.Basic instance:
92017                 var form = this.up('form').getForm();
92018                 if (form.isValid()) {
92019                     // Submit the Ajax request and handle the response
92020                     form.submit({
92021                         success: function(form, action) {
92022                            Ext.Msg.alert('Success', action.result.msg);
92023                         },
92024                         failure: function(form, action) {
92025                             Ext.Msg.alert('Failed', action.result.msg);
92026                         }
92027                     });
92028                 }
92029             }
92030         }]
92031     });
92032
92033  * @constructor
92034  * @param {Ext.container.Container} owner The component that is the container for the form, usually a {@link Ext.form.Panel}
92035  * @param {Object} config Configuration options. These are normally specified in the config to the
92036  * {@link Ext.form.Panel} constructor, which passes them along to the BasicForm automatically.
92037  *
92038  * @markdown
92039  * @docauthor Jason Johnston <jason@sencha.com>
92040  */
92041
92042
92043
92044 Ext.define('Ext.form.Basic', {
92045     extend: 'Ext.util.Observable',
92046     alternateClassName: 'Ext.form.BasicForm',
92047     requires: ['Ext.util.MixedCollection', 'Ext.form.action.Load', 'Ext.form.action.Submit',
92048                'Ext.window.MessageBox', 'Ext.data.Errors'],
92049
92050     constructor: function(owner, config) {
92051         var me = this,
92052             onItemAddOrRemove = me.onItemAddOrRemove;
92053
92054         /**
92055          * @property owner
92056          * @type Ext.container.Container
92057          * The container component to which this BasicForm is attached.
92058          */
92059         me.owner = owner;
92060
92061         // Listen for addition/removal of fields in the owner container
92062         me.mon(owner, {
92063             add: onItemAddOrRemove,
92064             remove: onItemAddOrRemove,
92065             scope: me
92066         });
92067
92068         Ext.apply(me, config);
92069
92070         // Normalize the paramOrder to an Array
92071         if (Ext.isString(me.paramOrder)) {
92072             me.paramOrder = me.paramOrder.split(/[\s,|]/);
92073         }
92074
92075         me.addEvents(
92076             /**
92077              * @event beforeaction
92078              * Fires before any action is performed. Return false to cancel the action.
92079              * @param {Ext.form.Basic} this
92080              * @param {Ext.form.action.Action} action The {@link Ext.form.action.Action} to be performed
92081              */
92082             'beforeaction',
92083             /**
92084              * @event actionfailed
92085              * Fires when an action fails.
92086              * @param {Ext.form.Basic} this
92087              * @param {Ext.form.action.Action} action The {@link Ext.form.action.Action} that failed
92088              */
92089             'actionfailed',
92090             /**
92091              * @event actioncomplete
92092              * Fires when an action is completed.
92093              * @param {Ext.form.Basic} this
92094              * @param {Ext.form.action.Action} action The {@link Ext.form.action.Action} that completed
92095              */
92096             'actioncomplete',
92097             /**
92098              * @event validitychange
92099              * Fires when the validity of the entire form changes.
92100              * @param {Ext.form.Basic} this
92101              * @param {Boolean} valid <tt>true</tt> if the form is now valid, <tt>false</tt> if it is now invalid.
92102              */
92103             'validitychange',
92104             /**
92105              * @event dirtychange
92106              * Fires when the dirty state of the entire form changes.
92107              * @param {Ext.form.Basic} this
92108              * @param {Boolean} dirty <tt>true</tt> if the form is now dirty, <tt>false</tt> if it is no longer dirty.
92109              */
92110             'dirtychange'
92111         );
92112         me.callParent();
92113     },
92114
92115     /**
92116      * Do any post constructor initialization
92117      * @private
92118      */
92119     initialize: function(){
92120         this.initialized = true;
92121         this.onValidityChange(!this.hasInvalidField());
92122     },
92123
92124     /**
92125      * @cfg {String} method
92126      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
92127      */
92128     /**
92129      * @cfg {Ext.data.reader.Reader} reader
92130      * An Ext.data.DataReader (e.g. {@link Ext.data.reader.Xml}) to be used to read
92131      * data when executing 'load' actions. This is optional as there is built-in
92132      * support for processing JSON responses.
92133      */
92134     /**
92135      * @cfg {Ext.data.reader.Reader} errorReader
92136      * <p>An Ext.data.DataReader (e.g. {@link Ext.data.reader.Xml}) to be used to
92137      * read field error messages returned from 'submit' actions. This is optional
92138      * as there is built-in support for processing JSON responses.</p>
92139      * <p>The Records which provide messages for the invalid Fields must use the
92140      * Field name (or id) as the Record ID, and must contain a field called 'msg'
92141      * which contains the error message.</p>
92142      * <p>The errorReader does not have to be a full-blown implementation of a
92143      * Reader. It simply needs to implement a <tt>read(xhr)</tt> function
92144      * which returns an Array of Records in an object with the following
92145      * structure:</p><pre><code>
92146 {
92147     records: recordArray
92148 }
92149 </code></pre>
92150      */
92151
92152     /**
92153      * @cfg {String} url
92154      * The URL to use for form actions if one isn't supplied in the
92155      * {@link #doAction doAction} options.
92156      */
92157
92158     /**
92159      * @cfg {Object} baseParams
92160      * <p>Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.</p>
92161      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode Ext.Object.toQueryString}.</p>
92162      */
92163
92164     /**
92165      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
92166      */
92167     timeout: 30,
92168
92169     /**
92170      * @cfg {Object} api (Optional) If specified, load and submit actions will be handled
92171      * with {@link Ext.form.action.DirectLoad} and {@link Ext.form.action.DirectLoad}.
92172      * Methods which have been imported by {@link Ext.direct.Manager} can be specified here to load and submit
92173      * forms.
92174      * Such as the following:<pre><code>
92175 api: {
92176     load: App.ss.MyProfile.load,
92177     submit: App.ss.MyProfile.submit
92178 }
92179 </code></pre>
92180      * <p>Load actions can use <code>{@link #paramOrder}</code> or <code>{@link #paramsAsHash}</code>
92181      * to customize how the load method is invoked.
92182      * Submit actions will always use a standard form submit. The <tt>formHandler</tt> configuration must
92183      * be set on the associated server-side method which has been imported by {@link Ext.direct.Manager}.</p>
92184      */
92185
92186     /**
92187      * @cfg {Array/String} paramOrder <p>A list of params to be executed server side.
92188      * Defaults to <tt>undefined</tt>. Only used for the <code>{@link #api}</code>
92189      * <code>load</code> configuration.</p>
92190      * <p>Specify the params in the order in which they must be executed on the
92191      * server-side as either (1) an Array of String values, or (2) a String of params
92192      * delimited by either whitespace, comma, or pipe. For example,
92193      * any of the following would be acceptable:</p><pre><code>
92194 paramOrder: ['param1','param2','param3']
92195 paramOrder: 'param1 param2 param3'
92196 paramOrder: 'param1,param2,param3'
92197 paramOrder: 'param1|param2|param'
92198      </code></pre>
92199      */
92200
92201     /**
92202      * @cfg {Boolean} paramsAsHash Only used for the <code>{@link #api}</code>
92203      * <code>load</code> configuration. If <tt>true</tt>, parameters will be sent as a
92204      * single hash collection of named arguments (defaults to <tt>false</tt>). Providing a
92205      * <tt>{@link #paramOrder}</tt> nullifies this configuration.
92206      */
92207     paramsAsHash: false,
92208
92209     /**
92210      * @cfg {String} waitTitle
92211      * The default title to show for the waiting message box (defaults to <tt>'Please Wait...'</tt>)
92212      */
92213     waitTitle: 'Please Wait...',
92214
92215     /**
92216      * @cfg {Boolean} trackResetOnLoad If set to <tt>true</tt>, {@link #reset}() resets to the last loaded
92217      * or {@link #setValues}() data instead of when the form was first created.  Defaults to <tt>false</tt>.
92218      */
92219     trackResetOnLoad: false,
92220
92221     /**
92222      * @cfg {Boolean} standardSubmit
92223      * <p>If set to <tt>true</tt>, a standard HTML form submit is used instead
92224      * of a XHR (Ajax) style form submission. Defaults to <tt>false</tt>. All of
92225      * the field values, plus any additional params configured via {@link #baseParams}
92226      * and/or the <code>options</code> to {@link #submit}, will be included in the
92227      * values submitted in the form.</p>
92228      */
92229
92230     /**
92231      * @cfg {Mixed} waitMsgTarget
92232      * By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific
92233      * element by passing it or its id or mask the form itself by passing in true. Defaults to <tt>undefined</tt>.
92234      */
92235
92236
92237     // Private
92238     wasDirty: false,
92239
92240
92241     /**
92242      * Destroys this object.
92243      */
92244     destroy: function() {
92245         this.clearListeners();
92246     },
92247
92248     /**
92249      * @private
92250      * Handle addition or removal of descendant items. Invalidates the cached list of fields
92251      * so that {@link #getFields} will do a fresh query next time it is called. Also adds listeners
92252      * for state change events on added fields, and tracks components with formBind=true.
92253      */
92254     onItemAddOrRemove: function(parent, child) {
92255         var me = this,
92256             isAdding = !!child.ownerCt,
92257             isContainer = child.isContainer;
92258
92259         function handleField(field) {
92260             // Listen for state change events on fields
92261             me[isAdding ? 'mon' : 'mun'](field, {
92262                 validitychange: me.checkValidity,
92263                 dirtychange: me.checkDirty,
92264                 scope: me,
92265                 buffer: 100 //batch up sequential calls to avoid excessive full-form validation
92266             });
92267             // Flush the cached list of fields
92268             delete me._fields;
92269         }
92270
92271         if (child.isFormField) {
92272             handleField(child);
92273         }
92274         else if (isContainer) {
92275             // Walk down
92276             Ext.Array.forEach(child.query('[isFormField]'), handleField);
92277         }
92278
92279         // Flush the cached list of formBind components
92280         delete this._boundItems;
92281
92282         // Check form bind, but only after initial add
92283         if (me.initialized) {
92284             me.onValidityChange(!me.hasInvalidField());
92285         }
92286     },
92287
92288     /**
92289      * Return all the {@link Ext.form.field.Field} components in the owner container.
92290      * @return {Ext.util.MixedCollection} Collection of the Field objects
92291      */
92292     getFields: function() {
92293         var fields = this._fields;
92294         if (!fields) {
92295             fields = this._fields = Ext.create('Ext.util.MixedCollection');
92296             fields.addAll(this.owner.query('[isFormField]'));
92297         }
92298         return fields;
92299     },
92300
92301     getBoundItems: function() {
92302         var boundItems = this._boundItems;
92303         if (!boundItems) {
92304             boundItems = this._boundItems = Ext.create('Ext.util.MixedCollection');
92305             boundItems.addAll(this.owner.query('[formBind]'));
92306         }
92307         return boundItems;
92308     },
92309
92310     /**
92311      * Returns true if the form contains any invalid fields. No fields will be marked as invalid
92312      * as a result of calling this; to trigger marking of fields use {@link #isValid} instead.
92313      */
92314     hasInvalidField: function() {
92315         return !!this.getFields().findBy(function(field) {
92316             var preventMark = field.preventMark,
92317                 isValid;
92318             field.preventMark = true;
92319             isValid = field.isValid();
92320             field.preventMark = preventMark;
92321             return !isValid;
92322         });
92323     },
92324
92325     /**
92326      * Returns true if client-side validation on the form is successful. Any invalid fields will be
92327      * marked as invalid. If you only want to determine overall form validity without marking anything,
92328      * use {@link #hasInvalidField} instead.
92329      * @return Boolean
92330      */
92331     isValid: function() {
92332         var me = this,
92333             invalid;
92334         me.batchLayouts(function() {
92335             invalid = me.getFields().filterBy(function(field) {
92336                 return !field.validate();
92337             });
92338         });
92339         return invalid.length < 1;
92340     },
92341
92342     /**
92343      * Check whether the validity of the entire form has changed since it was last checked, and
92344      * if so fire the {@link #validitychange validitychange} event. This is automatically invoked
92345      * when an individual field's validity changes.
92346      */
92347     checkValidity: function() {
92348         var me = this,
92349             valid = !me.hasInvalidField();
92350         if (valid !== me.wasValid) {
92351             me.onValidityChange(valid);
92352             me.fireEvent('validitychange', me, valid);
92353             me.wasValid = valid;
92354         }
92355     },
92356
92357     /**
92358      * @private
92359      * Handle changes in the form's validity. If there are any sub components with
92360      * formBind=true then they are enabled/disabled based on the new validity.
92361      * @param {Boolean} valid
92362      */
92363     onValidityChange: function(valid) {
92364         var boundItems = this.getBoundItems();
92365         if (boundItems) {
92366             boundItems.each(function(cmp) {
92367                 if (cmp.disabled === valid) {
92368                     cmp.setDisabled(!valid);
92369                 }
92370             });
92371         }
92372     },
92373
92374     /**
92375      * <p>Returns true if any fields in this form have changed from their original values.</p>
92376      * <p>Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the
92377      * Fields' <em>original values</em> are updated when the values are loaded by {@link #setValues}
92378      * or {@link #loadRecord}.</p>
92379      * @return Boolean
92380      */
92381     isDirty: function() {
92382         return !!this.getFields().findBy(function(f) {
92383             return f.isDirty();
92384         });
92385     },
92386
92387     /**
92388      * Check whether the dirty state of the entire form has changed since it was last checked, and
92389      * if so fire the {@link #dirtychange dirtychange} event. This is automatically invoked
92390      * when an individual field's dirty state changes.
92391      */
92392     checkDirty: function() {
92393         var dirty = this.isDirty();
92394         if (dirty !== this.wasDirty) {
92395             this.fireEvent('dirtychange', this, dirty);
92396             this.wasDirty = dirty;
92397         }
92398     },
92399
92400     /**
92401      * <p>Returns true if the form contains a file upload field. This is used to determine the
92402      * method for submitting the form: File uploads are not performed using normal 'Ajax' techniques,
92403      * that is they are <b>not</b> performed using XMLHttpRequests. Instead a hidden <tt>&lt;form></tt>
92404      * element containing all the fields is created temporarily and submitted with its
92405      * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
92406      * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
92407      * but removed after the return data has been gathered.</p>
92408      * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
92409      * server is using JSON to send the return object, then the
92410      * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
92411      * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
92412      * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
92413      * "&lt;" as "&amp;lt;", "&amp;" as "&amp;amp;" etc.</p>
92414      * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
92415      * is created containing a <tt>responseText</tt> property in order to conform to the
92416      * requirements of event handlers and callbacks.</p>
92417      * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
92418      * and some server technologies (notably JEE) may require some custom processing in order to
92419      * retrieve parameter names and parameter values from the packet content.</p>
92420      * @return Boolean
92421      */
92422     hasUpload: function() {
92423         return !!this.getFields().findBy(function(f) {
92424             return f.isFileUpload();
92425         });
92426     },
92427
92428     /**
92429      * Performs a predefined action (an implementation of {@link Ext.form.action.Action})
92430      * to perform application-specific processing.
92431      * @param {String/Ext.form.action.Action} action The name of the predefined action type,
92432      * or instance of {@link Ext.form.action.Action} to perform.
92433      * @param {Object} options (optional) The options to pass to the {@link Ext.form.action.Action}
92434      * that will get created, if the <tt>action</tt> argument is a String.
92435      * <p>All of the config options listed below are supported by both the
92436      * {@link Ext.form.action.Submit submit} and {@link Ext.form.action.Load load}
92437      * actions unless otherwise noted (custom actions could also accept
92438      * other config options):</p><ul>
92439      *
92440      * <li><b>url</b> : String<div class="sub-desc">The url for the action (defaults
92441      * to the form's {@link #url}.)</div></li>
92442      *
92443      * <li><b>method</b> : String<div class="sub-desc">The form method to use (defaults
92444      * to the form's method, or POST if not defined)</div></li>
92445      *
92446      * <li><b>params</b> : String/Object<div class="sub-desc"><p>The params to pass
92447      * (defaults to the form's baseParams, or none if not defined)</p>
92448      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode Ext.Object.toQueryString}.</p></div></li>
92449      *
92450      * <li><b>headers</b> : Object<div class="sub-desc">Request headers to set for the action.</div></li>
92451      *
92452      * <li><b>success</b> : Function<div class="sub-desc">The callback that will
92453      * be invoked after a successful response (see top of
92454      * {@link Ext.form.action.Submit submit} and {@link Ext.form.action.Load load}
92455      * for a description of what constitutes a successful response).
92456      * The function is passed the following parameters:<ul>
92457      * <li><tt>form</tt> : The {@link Ext.form.Basic} that requested the action.</li>
92458      * <li><tt>action</tt> : The {@link Ext.form.action.Action Action} object which performed the operation.
92459      * <div class="sub-desc">The action object contains these properties of interest:<ul>
92460      * <li><tt>{@link Ext.form.action.Action#response response}</tt></li>
92461      * <li><tt>{@link Ext.form.action.Action#result result}</tt> : interrogate for custom postprocessing</li>
92462      * <li><tt>{@link Ext.form.action.Action#type type}</tt></li>
92463      * </ul></div></li></ul></div></li>
92464      *
92465      * <li><b>failure</b> : Function<div class="sub-desc">The callback that will be invoked after a
92466      * failed transaction attempt. The function is passed the following parameters:<ul>
92467      * <li><tt>form</tt> : The {@link Ext.form.Basic} that requested the action.</li>
92468      * <li><tt>action</tt> : The {@link Ext.form.action.Action Action} object which performed the operation.
92469      * <div class="sub-desc">The action object contains these properties of interest:<ul>
92470      * <li><tt>{@link Ext.form.action.Action#failureType failureType}</tt></li>
92471      * <li><tt>{@link Ext.form.action.Action#response response}</tt></li>
92472      * <li><tt>{@link Ext.form.action.Action#result result}</tt> : interrogate for custom postprocessing</li>
92473      * <li><tt>{@link Ext.form.action.Action#type type}</tt></li>
92474      * </ul></div></li></ul></div></li>
92475      *
92476      * <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the
92477      * callback functions (The <tt>this</tt> reference for the callback functions).</div></li>
92478      *
92479      * <li><b>clientValidation</b> : Boolean<div class="sub-desc">Submit Action only.
92480      * Determines whether a Form's fields are validated in a final call to
92481      * {@link Ext.form.Basic#isValid isValid} prior to submission. Set to <tt>false</tt>
92482      * to prevent this. If undefined, pre-submission field validation is performed.</div></li></ul>
92483      *
92484      * @return {Ext.form.Basic} this
92485      */
92486     doAction: function(action, options) {
92487         if (Ext.isString(action)) {
92488             action = Ext.ClassManager.instantiateByAlias('formaction.' + action, Ext.apply({}, options, {form: this}));
92489         }
92490         if (this.fireEvent('beforeaction', this, action) !== false) {
92491             this.beforeAction(action);
92492             Ext.defer(action.run, 100, action);
92493         }
92494         return this;
92495     },
92496
92497     /**
92498      * Shortcut to {@link #doAction do} a {@link Ext.form.action.Submit submit action}. This will use the
92499      * {@link Ext.form.action.Submit AJAX submit action} by default. If the {@link #standardsubmit} config is
92500      * enabled it will use a standard form element to submit, or if the {@link #api} config is present it will
92501      * use the {@link Ext.form.action.DirectLoad Ext.direct.Direct submit action}.
92502      * @param {Object} options The options to pass to the action (see {@link #doAction} for details).<br>
92503      * <p>The following code:</p><pre><code>
92504 myFormPanel.getForm().submit({
92505     clientValidation: true,
92506     url: 'updateConsignment.php',
92507     params: {
92508         newStatus: 'delivered'
92509     },
92510     success: function(form, action) {
92511        Ext.Msg.alert('Success', action.result.msg);
92512     },
92513     failure: function(form, action) {
92514         switch (action.failureType) {
92515             case Ext.form.action.Action.CLIENT_INVALID:
92516                 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
92517                 break;
92518             case Ext.form.action.Action.CONNECT_FAILURE:
92519                 Ext.Msg.alert('Failure', 'Ajax communication failed');
92520                 break;
92521             case Ext.form.action.Action.SERVER_INVALID:
92522                Ext.Msg.alert('Failure', action.result.msg);
92523        }
92524     }
92525 });
92526 </code></pre>
92527      * would process the following server response for a successful submission:<pre><code>
92528 {
92529     "success":true, // note this is Boolean, not string
92530     "msg":"Consignment updated"
92531 }
92532 </code></pre>
92533      * and the following server response for a failed submission:<pre><code>
92534 {
92535     "success":false, // note this is Boolean, not string
92536     "msg":"You do not have permission to perform this operation"
92537 }
92538 </code></pre>
92539      * @return {Ext.form.Basic} this
92540      */
92541     submit: function(options) {
92542         return this.doAction(this.standardSubmit ? 'standardsubmit' : this.api ? 'directsubmit' : 'submit', options);
92543     },
92544
92545     /**
92546      * Shortcut to {@link #doAction do} a {@link Ext.form.action.Load load action}.
92547      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
92548      * @return {Ext.form.Basic} this
92549      */
92550     load: function(options) {
92551         return this.doAction(this.api ? 'directload' : 'load', options);
92552     },
92553
92554     /**
92555      * Persists the values in this form into the passed {@link Ext.data.Model} object in a beginEdit/endEdit block.
92556      * @param {Ext.data.Record} record The record to edit
92557      * @return {Ext.form.Basic} this
92558      */
92559     updateRecord: function(record) {
92560         var fields = record.fields,
92561             values = this.getFieldValues(),
92562             name,
92563             obj = {};
92564
92565         fields.each(function(f) {
92566             name = f.name;
92567             if (name in values) {
92568                 obj[name] = values[name];
92569             }
92570         });
92571
92572         record.beginEdit();
92573         record.set(obj);
92574         record.endEdit();
92575
92576         return this;
92577     },
92578
92579     /**
92580      * Loads an {@link Ext.data.Model} into this form by calling {@link #setValues} with the
92581      * {@link Ext.data.Model#data record data}.
92582      * See also {@link #trackResetOnLoad}.
92583      * @param {Ext.data.Model} record The record to load
92584      * @return {Ext.form.Basic} this
92585      */
92586     loadRecord: function(record) {
92587         this._record = record;
92588         return this.setValues(record.data);
92589     },
92590     
92591     /**
92592      * Returns the last Ext.data.Model instance that was loaded via {@link #loadRecord}
92593      * @return {Ext.data.Model} The record
92594      */
92595     getRecord: function() {
92596         return this._record;
92597     },
92598
92599     /**
92600      * @private
92601      * Called before an action is performed via {@link #doAction}.
92602      * @param {Ext.form.action.Action} action The Action instance that was invoked
92603      */
92604     beforeAction: function(action) {
92605         var waitMsg = action.waitMsg,
92606             maskCls = Ext.baseCSSPrefix + 'mask-loading',
92607             waitMsgTarget;
92608
92609         // Call HtmlEditor's syncValue before actions
92610         this.getFields().each(function(f) {
92611             if (f.isFormField && f.syncValue) {
92612                 f.syncValue();
92613             }
92614         });
92615
92616         if (waitMsg) {
92617             waitMsgTarget = this.waitMsgTarget;
92618             if (waitMsgTarget === true) {
92619                 this.owner.el.mask(waitMsg, maskCls);
92620             } else if (waitMsgTarget) {
92621                 waitMsgTarget = this.waitMsgTarget = Ext.get(waitMsgTarget);
92622                 waitMsgTarget.mask(waitMsg, maskCls);
92623             } else {
92624                 Ext.MessageBox.wait(waitMsg, action.waitTitle || this.waitTitle);
92625             }
92626         }
92627     },
92628
92629     /**
92630      * @private
92631      * Called after an action is performed via {@link #doAction}.
92632      * @param {Ext.form.action.Action} action The Action instance that was invoked
92633      * @param {Boolean} success True if the action completed successfully, false, otherwise.
92634      */
92635     afterAction: function(action, success) {
92636         if (action.waitMsg) {
92637             var MessageBox = Ext.MessageBox,
92638                 waitMsgTarget = this.waitMsgTarget;
92639             if (waitMsgTarget === true) {
92640                 this.owner.el.unmask();
92641             } else if (waitMsgTarget) {
92642                 waitMsgTarget.unmask();
92643             } else {
92644                 MessageBox.updateProgress(1);
92645                 MessageBox.hide();
92646             }
92647         }
92648         if (success) {
92649             if (action.reset) {
92650                 this.reset();
92651             }
92652             Ext.callback(action.success, action.scope || action, [this, action]);
92653             this.fireEvent('actioncomplete', this, action);
92654         } else {
92655             Ext.callback(action.failure, action.scope || action, [this, action]);
92656             this.fireEvent('actionfailed', this, action);
92657         }
92658     },
92659
92660
92661     /**
92662      * Find a specific {@link Ext.form.field.Field} in this form by id or name.
92663      * @param {String} id The value to search for (specify either a {@link Ext.Component#id id} or
92664      * {@link Ext.form.field.Field#getName name or hiddenName}).
92665      * @return Ext.form.field.Field The first matching field, or <tt>null</tt> if none was found.
92666      */
92667     findField: function(id) {
92668         return this.getFields().findBy(function(f) {
92669             return f.id === id || f.getName() === id;
92670         });
92671     },
92672
92673
92674     /**
92675      * Mark fields in this form invalid in bulk.
92676      * @param {Array/Object} errors Either an array in the form <code>[{id:'fieldId', msg:'The message'}, ...]</code>,
92677      * an object hash of <code>{id: msg, id2: msg2}</code>, or a {@link Ext.data.Errors} object.
92678      * @return {Ext.form.Basic} this
92679      */
92680     markInvalid: function(errors) {
92681         var me = this;
92682
92683         function mark(fieldId, msg) {
92684             var field = me.findField(fieldId);
92685             if (field) {
92686                 field.markInvalid(msg);
92687             }
92688         }
92689
92690         if (Ext.isArray(errors)) {
92691             Ext.each(errors, function(err) {
92692                 mark(err.id, err.msg);
92693             });
92694         }
92695         else if (errors instanceof Ext.data.Errors) {
92696             errors.each(function(err) {
92697                 mark(err.field, err.message);
92698             });
92699         }
92700         else {
92701             Ext.iterate(errors, mark);
92702         }
92703         return this;
92704     },
92705
92706     /**
92707      * Set values for fields in this form in bulk.
92708      * @param {Array/Object} values Either an array in the form:<pre><code>
92709 [{id:'clientName', value:'Fred. Olsen Lines'},
92710  {id:'portOfLoading', value:'FXT'},
92711  {id:'portOfDischarge', value:'OSL'} ]</code></pre>
92712      * or an object hash of the form:<pre><code>
92713 {
92714     clientName: 'Fred. Olsen Lines',
92715     portOfLoading: 'FXT',
92716     portOfDischarge: 'OSL'
92717 }</code></pre>
92718      * @return {Ext.form.Basic} this
92719      */
92720     setValues: function(values) {
92721         var me = this;
92722
92723         function setVal(fieldId, val) {
92724             var field = me.findField(fieldId);
92725             if (field) {
92726                 field.setValue(val);
92727                 if (me.trackResetOnLoad) {
92728                     field.resetOriginalValue();
92729                 }
92730             }
92731         }
92732
92733         if (Ext.isArray(values)) {
92734             // array of objects
92735             Ext.each(values, function(val) {
92736                 setVal(val.id, val.value);
92737             });
92738         } else {
92739             // object hash
92740             Ext.iterate(values, setVal);
92741         }
92742         return this;
92743     },
92744
92745     /**
92746      * Retrieves the fields in the form as a set of key/value pairs, using their
92747      * {@link Ext.form.field.Field#getSubmitData getSubmitData()} method to collect the values.
92748      * If multiple fields return values under the same name those values will be combined into an Array.
92749      * This is similar to {@link #getFieldValues} except that this method collects only String values for
92750      * submission, while getFieldValues collects type-specific data values (e.g. Date objects for date fields.)
92751      * @param {Boolean} asString (optional) If true, will return the key/value collection as a single
92752      * URL-encoded param string. Defaults to false.
92753      * @param {Boolean} dirtyOnly (optional) If true, only fields that are dirty will be included in the result.
92754      * Defaults to false.
92755      * @param {Boolean} includeEmptyText (optional) If true, the configured emptyText of empty fields will be used.
92756      * Defaults to false.
92757      * @return {String/Object}
92758      */
92759     getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) {
92760         var values = {};
92761
92762         this.getFields().each(function(field) {
92763             if (!dirtyOnly || field.isDirty()) {
92764                 var data = field[useDataValues ? 'getModelData' : 'getSubmitData'](includeEmptyText);
92765                 if (Ext.isObject(data)) {
92766                     Ext.iterate(data, function(name, val) {
92767                         if (includeEmptyText && val === '') {
92768                             val = field.emptyText || '';
92769                         }
92770                         if (name in values) {
92771                             var bucket = values[name],
92772                                 isArray = Ext.isArray;
92773                             if (!isArray(bucket)) {
92774                                 bucket = values[name] = [bucket];
92775                             }
92776                             if (isArray(val)) {
92777                                 values[name] = bucket.concat(val);
92778                             } else {
92779                                 bucket.push(val);
92780                             }
92781                         } else {
92782                             values[name] = val;
92783                         }
92784                     });
92785                 }
92786             }
92787         });
92788
92789         if (asString) {
92790             values = Ext.Object.toQueryString(values);
92791         }
92792         return values;
92793     },
92794
92795     /**
92796      * Retrieves the fields in the form as a set of key/value pairs, using their
92797      * {@link Ext.form.field.Field#getModelData getModelData()} method to collect the values.
92798      * If multiple fields return values under the same name those values will be combined into an Array.
92799      * This is similar to {@link #getValues} except that this method collects type-specific data values
92800      * (e.g. Date objects for date fields) while getValues returns only String values for submission.
92801      * @param {Boolean} dirtyOnly (optional) If true, only fields that are dirty will be included in the result.
92802      * Defaults to false.
92803      * @return {Object}
92804      */
92805     getFieldValues: function(dirtyOnly) {
92806         return this.getValues(false, dirtyOnly, false, true);
92807     },
92808
92809     /**
92810      * Clears all invalid field messages in this form.
92811      * @return {Ext.form.Basic} this
92812      */
92813     clearInvalid: function() {
92814         var me = this;
92815         me.batchLayouts(function() {
92816             me.getFields().each(function(f) {
92817                 f.clearInvalid();
92818             });
92819         });
92820         return me;
92821     },
92822
92823     /**
92824      * Resets all fields in this form.
92825      * @return {Ext.form.Basic} this
92826      */
92827     reset: function() {
92828         var me = this;
92829         me.batchLayouts(function() {
92830             me.getFields().each(function(f) {
92831                 f.reset();
92832             });
92833         });
92834         return me;
92835     },
92836
92837     /**
92838      * Calls {@link Ext#apply Ext.apply} for all fields in this form with the passed object.
92839      * @param {Object} obj The object to be applied
92840      * @return {Ext.form.Basic} this
92841      */
92842     applyToFields: function(obj) {
92843         this.getFields().each(function(f) {
92844             Ext.apply(f, obj);
92845         });
92846         return this;
92847     },
92848
92849     /**
92850      * Calls {@link Ext#applyIf Ext.applyIf} for all field in this form with the passed object.
92851      * @param {Object} obj The object to be applied
92852      * @return {Ext.form.Basic} this
92853      */
92854     applyIfToFields: function(obj) {
92855         this.getFields().each(function(f) {
92856             Ext.applyIf(f, obj);
92857         });
92858         return this;
92859     },
92860
92861     /**
92862      * @private
92863      * Utility wrapper that suspends layouts of all field parent containers for the duration of a given
92864      * function. Used during full-form validation and resets to prevent huge numbers of layouts.
92865      * @param {Function} fn
92866      */
92867     batchLayouts: function(fn) {
92868         var me = this,
92869             suspended = new Ext.util.HashMap();
92870
92871         // Temporarily suspend layout on each field's immediate owner so we don't get a huge layout cascade
92872         me.getFields().each(function(field) {
92873             var ownerCt = field.ownerCt;
92874             if (!suspended.contains(ownerCt)) {
92875                 suspended.add(ownerCt);
92876                 ownerCt.oldSuspendLayout = ownerCt.suspendLayout;
92877                 ownerCt.suspendLayout = true;
92878             }
92879         });
92880
92881         // Invoke the function
92882         fn();
92883
92884         // Un-suspend the container layouts
92885         suspended.each(function(id, ct) {
92886             ct.suspendLayout = ct.oldSuspendLayout;
92887             delete ct.oldSuspendLayout;
92888         });
92889
92890         // Trigger a single layout
92891         me.owner.doComponentLayout();
92892     }
92893 });
92894
92895 /**
92896  * @class Ext.form.FieldAncestor
92897
92898 A mixin for {@link Ext.container.Container} components that are likely to have form fields in their
92899 items subtree. Adds the following capabilities:
92900
92901 - Methods for handling the addition and removal of {@link Ext.form.Labelable} and {@link Ext.form.field.Field}
92902   instances at any depth within the container.
92903 - Events ({@link #fieldvaliditychange} and {@link #fielderrorchange}) for handling changes to the state
92904   of individual fields at the container level.
92905 - Automatic application of {@link #fieldDefaults} config properties to each field added within the
92906   container, to facilitate uniform configuration of all fields.
92907
92908 This mixin is primarily for internal use by {@link Ext.form.Panel} and {@link Ext.form.FieldContainer},
92909 and should not normally need to be used directly.
92910
92911  * @markdown
92912  * @docauthor Jason Johnston <jason@sencha.com>
92913  */
92914 Ext.define('Ext.form.FieldAncestor', {
92915
92916     /**
92917      * @cfg {Object} fieldDefaults
92918      * <p>If specified, the properties in this object are used as default config values for each
92919      * {@link Ext.form.Labelable} instance (e.g. {@link Ext.form.field.Base} or {@link Ext.form.FieldContainer})
92920      * that is added as a descendant of this container. Corresponding values specified in an individual field's
92921      * own configuration, or from the {@link Ext.container.Container#defaults defaults config} of its parent container,
92922      * will take precedence. See the documentation for {@link Ext.form.Labelable} to see what config
92923      * options may be specified in the <tt>fieldDefaults</tt>.</p>
92924      * <p>Example:</p>
92925      * <pre><code>new Ext.form.Panel({
92926     fieldDefaults: {
92927         labelAlign: 'left',
92928         labelWidth: 100
92929     },
92930     items: [{
92931         xtype: 'fieldset',
92932         defaults: {
92933             labelAlign: 'top'
92934         },
92935         items: [{
92936             name: 'field1'
92937         }, {
92938             name: 'field2'
92939         }]
92940     }, {
92941         xtype: 'fieldset',
92942         items: [{
92943             name: 'field3',
92944             labelWidth: 150
92945         }, {
92946             name: 'field4'
92947         }]
92948     }]
92949 });</code></pre>
92950      * <p>In this example, field1 and field2 will get labelAlign:'top' (from the fieldset's <tt>defaults</tt>)
92951      * and labelWidth:100 (from <tt>fieldDefaults</tt>), field3 and field4 will both get labelAlign:'left' (from
92952      * <tt>fieldDefaults</tt> and field3 will use the labelWidth:150 from its own config.</p>
92953      */
92954
92955
92956     /**
92957      * @protected Initializes the FieldAncestor's state; this must be called from the initComponent method
92958      * of any components importing this mixin.
92959      */
92960     initFieldAncestor: function() {
92961         var me = this,
92962             onSubtreeChange = me.onFieldAncestorSubtreeChange;
92963
92964         me.addEvents(
92965             /**
92966              * @event fielderrorchange
92967              * Fires when the validity state of any one of the {@link Ext.form.field.Field} instances within this
92968              * container changes.
92969              * @param {Ext.form.FieldAncestor} this
92970              * @param {Ext.form.Labelable} The Field instance whose validity changed
92971              * @param {String} isValid The field's new validity state
92972              */
92973             'fieldvaliditychange',
92974
92975             /**
92976              * @event fielderrorchange
92977              * Fires when the active error message is changed for any one of the {@link Ext.form.Labelable}
92978              * instances within this container.
92979              * @param {Ext.form.FieldAncestor} this
92980              * @param {Ext.form.Labelable} The Labelable instance whose active error was changed
92981              * @param {String} error The active error message
92982              */
92983             'fielderrorchange'
92984         );
92985
92986         // Catch addition and removal of descendant fields
92987         me.on('add', onSubtreeChange, me);
92988         me.on('remove', onSubtreeChange, me);
92989
92990         me.initFieldDefaults();
92991     },
92992
92993     /**
92994      * @private Initialize the {@link #fieldDefaults} object
92995      */
92996     initFieldDefaults: function() {
92997         if (!this.fieldDefaults) {
92998             this.fieldDefaults = {};
92999         }
93000     },
93001
93002     /**
93003      * @private
93004      * Handle the addition and removal of components in the FieldAncestor component's child tree.
93005      */
93006     onFieldAncestorSubtreeChange: function(parent, child) {
93007         var me = this,
93008             isAdding = !!child.ownerCt;
93009
93010         function handleCmp(cmp) {
93011             var isLabelable = cmp.isFieldLabelable,
93012                 isField = cmp.isFormField;
93013             if (isLabelable || isField) {
93014                 if (isLabelable) {
93015                     me['onLabelable' + (isAdding ? 'Added' : 'Removed')](cmp);
93016                 }
93017                 if (isField) {
93018                     me['onField' + (isAdding ? 'Added' : 'Removed')](cmp);
93019                 }
93020             }
93021             else if (cmp.isContainer) {
93022                 Ext.Array.forEach(cmp.getRefItems(), handleCmp);
93023             }
93024         }
93025         handleCmp(child);
93026     },
93027
93028     /**
93029      * @protected Called when a {@link Ext.form.Labelable} instance is added to the container's subtree.
93030      * @param {Ext.form.Labelable} labelable The instance that was added
93031      */
93032     onLabelableAdded: function(labelable) {
93033         var me = this;
93034
93035         // buffer slightly to avoid excessive firing while sub-fields are changing en masse
93036         me.mon(labelable, 'errorchange', me.handleFieldErrorChange, me, {buffer: 10});
93037
93038         labelable.setFieldDefaults(me.fieldDefaults);
93039     },
93040
93041     /**
93042      * @protected Called when a {@link Ext.form.field.Field} instance is added to the container's subtree.
93043      * @param {Ext.form.field.Field} field The field which was added
93044      */
93045     onFieldAdded: function(field) {
93046         var me = this;
93047         me.mon(field, 'validitychange', me.handleFieldValidityChange, me);
93048     },
93049
93050     /**
93051      * @protected Called when a {@link Ext.form.Labelable} instance is removed from the container's subtree.
93052      * @param {Ext.form.Labelable} labelable The instance that was removed
93053      */
93054     onLabelableRemoved: function(labelable) {
93055         var me = this;
93056         me.mun(labelable, 'errorchange', me.handleFieldErrorChange, me);
93057     },
93058
93059     /**
93060      * @protected Called when a {@link Ext.form.field.Field} instance is removed from the container's subtree.
93061      * @param {Ext.form.field.Field} field The field which was removed
93062      */
93063     onFieldRemoved: function(field) {
93064         var me = this;
93065         me.mun(field, 'validitychange', me.handleFieldValidityChange, me);
93066     },
93067
93068     /**
93069      * @private Handle validitychange events on sub-fields; invoke the aggregated event and method
93070      */
93071     handleFieldValidityChange: function(field, isValid) {
93072         var me = this;
93073         me.fireEvent('fieldvaliditychange', me, field, isValid);
93074         me.onFieldValidityChange();
93075     },
93076
93077     /**
93078      * @private Handle errorchange events on sub-fields; invoke the aggregated event and method
93079      */
93080     handleFieldErrorChange: function(labelable, activeError) {
93081         var me = this;
93082         me.fireEvent('fielderrorchange', me, labelable, activeError);
93083         me.onFieldErrorChange();
93084     },
93085
93086     /**
93087      * @protected Fired when the validity of any field within the container changes.
93088      * @param {Ext.form.field.Field} The sub-field whose validity changed
93089      * @param {String} The new validity state
93090      */
93091     onFieldValidityChange: Ext.emptyFn,
93092
93093     /**
93094      * @protected Fired when the error message of any field within the container changes.
93095      * @param {Ext.form.Labelable} The sub-field whose active error changed
93096      * @param {String} The new active error message
93097      */
93098     onFieldErrorChange: Ext.emptyFn
93099
93100 });
93101 /**
93102  * @class Ext.layout.container.CheckboxGroup
93103  * @extends Ext.layout.container.Container
93104  * <p>This layout implements the column arrangement for {@link Ext.form.CheckboxGroup} and {@link Ext.form.RadioGroup}.
93105  * It groups the component's sub-items into columns based on the component's
93106  * {@link Ext.form.CheckboxGroup#columns columns} and {@link Ext.form.CheckboxGroup#vertical} config properties.</p>
93107  *
93108  */
93109 Ext.define('Ext.layout.container.CheckboxGroup', {
93110     extend: 'Ext.layout.container.Container',
93111     alias: ['layout.checkboxgroup'],
93112
93113
93114     onLayout: function() {
93115         var numCols = this.getColCount(),
93116             shadowCt = this.getShadowCt(),
93117             owner = this.owner,
93118             items = owner.items,
93119             shadowItems = shadowCt.items,
93120             numItems = items.length,
93121             colIndex = 0,
93122             i, numRows;
93123
93124         // Distribute the items into the appropriate column containers. We add directly to the
93125         // containers' items collection rather than calling container.add(), because we need the
93126         // checkboxes to maintain their original ownerCt. The distribution is done on each layout
93127         // in case items have been added, removed, or reordered.
93128
93129         shadowItems.each(function(col) {
93130             col.items.clear();
93131         });
93132
93133         // If columns="auto", then the number of required columns may change as checkboxes are added/removed
93134         // from the CheckboxGroup; adjust to match.
93135         while (shadowItems.length > numCols) {
93136             shadowCt.remove(shadowItems.last());
93137         }
93138         while (shadowItems.length < numCols) {
93139             shadowCt.add({
93140                 xtype: 'container',
93141                 cls: owner.groupCls,
93142                 flex: 1
93143             });
93144         }
93145
93146         if (owner.vertical) {
93147             numRows = Math.ceil(numItems / numCols);
93148             for (i = 0; i < numItems; i++) {
93149                 if (i > 0 && i % numRows === 0) {
93150                     colIndex++;
93151                 }
93152                 shadowItems.getAt(colIndex).items.add(items.getAt(i));
93153             }
93154         } else {
93155             for (i = 0; i < numItems; i++) {
93156                 colIndex = i % numCols;
93157                 shadowItems.getAt(colIndex).items.add(items.getAt(i));
93158             }
93159         }
93160
93161         if (!shadowCt.rendered) {
93162             shadowCt.render(this.getRenderTarget());
93163         } else {
93164             // Ensure all items are rendered in the correct place in the correct column - this won't
93165             // get done by the column containers themselves if their dimensions are not changing.
93166             shadowItems.each(function(col) {
93167                 var layout = col.getLayout();
93168                 layout.renderItems(layout.getLayoutItems(), layout.getRenderTarget());
93169             });
93170         }
93171
93172         shadowCt.doComponentLayout();
93173     },
93174
93175
93176     // We don't want to render any items to the owner directly, that gets handled by each column's own layout
93177     renderItems: Ext.emptyFn,
93178
93179
93180     /**
93181      * @private
93182      * Creates and returns the shadow hbox container that will be used to arrange the owner's items
93183      * into columns.
93184      */
93185     getShadowCt: function() {
93186         var me = this,
93187             shadowCt = me.shadowCt,
93188             owner, items, item, columns, columnsIsArray, numCols, i;
93189
93190         if (!shadowCt) {
93191             // Create the column containers based on the owner's 'columns' config
93192             owner = me.owner;
93193             columns = owner.columns;
93194             columnsIsArray = Ext.isArray(columns);
93195             numCols = me.getColCount();
93196             items = [];
93197             for(i = 0; i < numCols; i++) {
93198                 item = {
93199                     xtype: 'container',
93200                     cls: owner.groupCls
93201                 };
93202                 if (columnsIsArray) {
93203                     // Array can contain mixture of whole numbers, used as fixed pixel widths, and fractional
93204                     // numbers, used as relative flex values.
93205                     if (columns[i] < 1) {
93206                         item.flex = columns[i];
93207                     } else {
93208                         item.width = columns[i];
93209                     }
93210                 }
93211                 else {
93212                     // All columns the same width
93213                     item.flex = 1;
93214                 }
93215                 items.push(item);
93216             }
93217
93218             // Create the shadow container; delay rendering until after items are added to the columns
93219             shadowCt = me.shadowCt = Ext.createWidget('container', {
93220                 layout: 'hbox',
93221                 items: items,
93222                 ownerCt: owner
93223             });
93224         }
93225         
93226         return shadowCt;
93227     },
93228
93229
93230     /**
93231      * @private Get the number of columns in the checkbox group
93232      */
93233     getColCount: function() {
93234         var owner = this.owner,
93235             colsCfg = owner.columns;
93236         return Ext.isArray(colsCfg) ? colsCfg.length : (Ext.isNumber(colsCfg) ? colsCfg : owner.items.length);
93237     }
93238
93239 });
93240
93241 /**
93242  * @class Ext.form.FieldContainer
93243  * @extends Ext.container.Container
93244
93245 FieldContainer is a derivation of {@link Ext.container.Container Container} that implements the
93246 {@link Ext.form.Labelable Labelable} mixin. This allows it to be configured so that it is rendered with
93247 a {@link #fieldLabel field label} and optional {@link #msgTarget error message} around its sub-items.
93248 This is useful for arranging a group of fields or other components within a single item in a form, so
93249 that it lines up nicely with other fields. A common use is for grouping a set of related fields under
93250 a single label in a form.
93251
93252 The container's configured {@link #items} will be layed out within the field body area according to the
93253 configured {@link #layout} type. The default layout is `'autocontainer'`.
93254
93255 Like regular fields, FieldContainer can inherit its decoration configuration from the
93256 {@link Ext.form.Panel#fieldDefaults fieldDefaults} of an enclosing FormPanel. In addition,
93257 FieldContainer itself can pass {@link #fieldDefaults} to any {@link Ext.form.Labelable fields}
93258 it may itself contain.
93259
93260 If you are grouping a set of {@link Ext.form.field.Checkbox Checkbox} or {@link Ext.form.field.Radio Radio}
93261 fields in a single labeled container, consider using a {@link Ext.form.CheckboxGroup}
93262 or {@link Ext.form.RadioGroup} instead as they are specialized for handling those types.
93263 {@img Ext.form.FieldContainer/Ext.form.FieldContainer1.png Ext.form.FieldContainer component}
93264 __Example usage:__
93265
93266     Ext.create('Ext.form.Panel', {
93267         title: 'FieldContainer Example',
93268         width: 550,
93269         bodyPadding: 10,
93270     
93271         items: [{
93272             xtype: 'fieldcontainer',
93273             fieldLabel: 'Last Three Jobs',
93274             labelWidth: 100,
93275     
93276             // The body area will contain three text fields, arranged
93277             // horizontally, separated by draggable splitters.
93278             layout: 'hbox',
93279             items: [{
93280                 xtype: 'textfield',
93281                 flex: 1
93282             }, {
93283                 xtype: 'splitter'
93284             }, {
93285                 xtype: 'textfield',
93286                 flex: 1
93287             }, {
93288                 xtype: 'splitter'
93289             }, {
93290                 xtype: 'textfield',
93291                 flex: 1
93292             }]
93293         }],
93294         renderTo: Ext.getBody()
93295     });
93296
93297 __Usage of {@link #fieldDefaults}:__
93298 {@img Ext.form.FieldContainer/Ext.form.FieldContainer2.png Ext.form.FieldContainer component}
93299
93300     Ext.create('Ext.form.Panel', {
93301         title: 'FieldContainer Example',
93302         width: 350,
93303         bodyPadding: 10,
93304     
93305         items: [{
93306             xtype: 'fieldcontainer',
93307             fieldLabel: 'Your Name',
93308             labelWidth: 75,
93309             defaultType: 'textfield',
93310     
93311             // Arrange fields vertically, stretched to full width
93312             layout: 'anchor',
93313             defaults: {
93314                 layout: '100%'
93315             },
93316     
93317             // These config values will be applied to both sub-fields, except
93318             // for Last Name which will use its own msgTarget.
93319             fieldDefaults: {
93320                 msgTarget: 'under',
93321                 labelAlign: 'top'
93322             },
93323     
93324             items: [{
93325                 fieldLabel: 'First Name',
93326                 name: 'firstName'
93327             }, {
93328                 fieldLabel: 'Last Name',
93329                 name: 'lastName',
93330                 msgTarget: 'under'
93331             }]
93332         }],
93333         renderTo: Ext.getBody()
93334     });
93335
93336
93337  * @constructor
93338  * Creates a new Ext.form.FieldContainer instance.
93339  * @param {Object} config The component configuration.
93340  *
93341  * @xtype fieldcontainer
93342  * @markdown
93343  * @docauthor Jason Johnston <jason@sencha.com>
93344  */
93345 Ext.define('Ext.form.FieldContainer', {
93346     extend: 'Ext.container.Container',
93347     mixins: {
93348         labelable: 'Ext.form.Labelable',
93349         fieldAncestor: 'Ext.form.FieldAncestor'
93350     },
93351     alias: 'widget.fieldcontainer',
93352
93353     componentLayout: 'field',
93354
93355     /**
93356      * @cfg {Boolean} combineLabels
93357      * If set to true, and there is no defined {@link #fieldLabel}, the field container will automatically
93358      * generate its label by combining the labels of all the fields it contains. Defaults to false.
93359      */
93360     combineLabels: false,
93361
93362     /**
93363      * @cfg {String} labelConnector
93364      * The string to use when joining the labels of individual sub-fields, when {@link #combineLabels} is
93365      * set to true. Defaults to ', '.
93366      */
93367     labelConnector: ', ',
93368
93369     /**
93370      * @cfg {Boolean} combineErrors
93371      * If set to true, the field container will automatically combine and display the validation errors from
93372      * all the fields it contains as a single error on the container, according to the configured
93373      * {@link #msgTarget}. Defaults to false.
93374      */
93375     combineErrors: false,
93376     
93377     maskOnDisable: false,
93378
93379     initComponent: function() {
93380         var me = this,
93381             onSubCmpAddOrRemove = me.onSubCmpAddOrRemove;
93382
93383         // Init mixins
93384         me.initLabelable();
93385         me.initFieldAncestor();
93386
93387         me.callParent();
93388     },
93389
93390     /**
93391      * @protected Called when a {@link Ext.form.Labelable} instance is added to the container's subtree.
93392      * @param {Ext.form.Labelable} labelable The instance that was added
93393      */
93394     onLabelableAdded: function(labelable) {
93395         var me = this;
93396         me.mixins.fieldAncestor.onLabelableAdded.call(this, labelable);
93397         me.updateLabel();
93398     },
93399
93400     /**
93401      * @protected Called when a {@link Ext.form.Labelable} instance is removed from the container's subtree.
93402      * @param {Ext.form.Labelable} labelable The instance that was removed
93403      */
93404     onLabelableRemoved: function(labelable) {
93405         var me = this;
93406         me.mixins.fieldAncestor.onLabelableRemoved.call(this, labelable);
93407         me.updateLabel();
93408     },
93409
93410     onRender: function() {
93411         var me = this,
93412             renderSelectors = me.renderSelectors,
93413             applyIf = Ext.applyIf;
93414
93415         applyIf(renderSelectors, me.getLabelableSelectors());
93416
93417         me.callParent(arguments);
93418     },
93419
93420     initRenderTpl: function() {
93421         var me = this;
93422         if (!me.hasOwnProperty('renderTpl')) {
93423             me.renderTpl = me.getTpl('labelableRenderTpl');
93424         }
93425         return me.callParent();
93426     },
93427
93428     initRenderData: function() {
93429         return Ext.applyIf(this.callParent(), this.getLabelableRenderData());
93430     },
93431
93432     /**
93433      * Returns the combined field label if {@link #combineLabels} is set to true and if there is no
93434      * set {@link #fieldLabel}. Otherwise returns the fieldLabel like normal. You can also override
93435      * this method to provide a custom generated label.
93436      */
93437     getFieldLabel: function() {
93438         var label = this.fieldLabel || '';
93439         if (!label && this.combineLabels) {
93440             label = Ext.Array.map(this.query('[isFieldLabelable]'), function(field) {
93441                 return field.getFieldLabel();
93442             }).join(this.labelConnector);
93443         }
93444         return label;
93445     },
93446
93447     /**
93448      * @private Updates the content of the labelEl if it is rendered
93449      */
93450     updateLabel: function() {
93451         var me = this,
93452             label = me.labelEl;
93453         if (label) {
93454             label.update(me.getFieldLabel());
93455         }
93456     },
93457
93458
93459     /**
93460      * @private Fired when the error message of any field within the container changes, and updates the
93461      * combined error message to match.
93462      */
93463     onFieldErrorChange: function(field, activeError) {
93464         if (this.combineErrors) {
93465             var me = this,
93466                 oldError = me.getActiveError(),
93467                 invalidFields = Ext.Array.filter(me.query('[isFormField]'), function(field) {
93468                     return field.hasActiveError();
93469                 }),
93470                 newErrors = me.getCombinedErrors(invalidFields);
93471
93472             if (newErrors) {
93473                 me.setActiveErrors(newErrors);
93474             } else {
93475                 me.unsetActiveError();
93476             }
93477
93478             if (oldError !== me.getActiveError()) {
93479                 me.doComponentLayout();
93480             }
93481         }
93482     },
93483
93484     /**
93485      * Takes an Array of invalid {@link Ext.form.field.Field} objects and builds a combined list of error
93486      * messages from them. Defaults to prepending each message by the field name and a colon. This
93487      * can be overridden to provide custom combined error message handling, for instance changing
93488      * the format of each message or sorting the array (it is sorted in order of appearance by default).
93489      * @param {Array} invalidFields An Array of the sub-fields which are currently invalid.
93490      * @return {Array} The combined list of error messages
93491      */
93492     getCombinedErrors: function(invalidFields) {
93493         var forEach = Ext.Array.forEach,
93494             errors = [];
93495         forEach(invalidFields, function(field) {
93496             forEach(field.getActiveErrors(), function(error) {
93497                 var label = field.getFieldLabel();
93498                 errors.push((label ? label + ': ' : '') + error);
93499             });
93500         });
93501         return errors;
93502     },
93503
93504     getTargetEl: function() {
93505         return this.bodyEl || this.callParent();
93506     }
93507 });
93508
93509 /**
93510  * @class Ext.form.CheckboxGroup
93511  * @extends Ext.form.FieldContainer
93512  * <p>A {@link Ext.form.FieldContainer field container} which has a specialized layout for arranging
93513  * {@link Ext.form.field.Checkbox} controls into columns, and provides convenience {@link Ext.form.field.Field} methods
93514  * for {@link #getValue getting}, {@link #setValue setting}, and {@link #validate validating} the group
93515  * of checkboxes as a whole.</p>
93516  * <p><b>Validation:</b> Individual checkbox fields themselves have no default validation behavior, but
93517  * sometimes you want to require a user to select at least one of a group of checkboxes. CheckboxGroup
93518  * allows this by setting the config <tt>{@link #allowBlank}:false</tt>; when the user does not check at
93519  * least one of the checkboxes, the entire group will be highlighted as invalid and the
93520  * {@link #blankText error message} will be displayed according to the {@link #msgTarget} config.</p>
93521  * <p><b>Layout:</b> The default layout for CheckboxGroup makes it easy to arrange the checkboxes into
93522  * columns; see the {@link #columns} and {@link #vertical} config documentation for details. You may also
93523  * use a completely different layout by setting the {@link #layout} to one of the other supported layout
93524  * types; for instance you may wish to use a custom arrangement of hbox and vbox containers. In that case
93525  * the checkbox components at any depth will still be managed by the CheckboxGroup's validation.</p>
93526  * {@img Ext.form.RadioGroup/Ext.form.RadioGroup.png Ext.form.RadioGroup component}
93527  * <p>Example usage:</p>
93528  * <pre><code>
93529     Ext.create('Ext.form.Panel', {
93530         title: 'RadioGroup Example',
93531         width: 300,
93532         height: 125,
93533         bodyPadding: 10,
93534         renderTo: Ext.getBody(),        
93535         items:[{            
93536             xtype: 'radiogroup',
93537             fieldLabel: 'Two Columns',
93538             // Arrange radio buttons into two columns, distributed vertically
93539             columns: 2,
93540             vertical: true,
93541             items: [
93542                 {boxLabel: 'Item 1', name: 'rb', inputValue: '1'},
93543                 {boxLabel: 'Item 2', name: 'rb', inputValue: '2', checked: true},
93544                 {boxLabel: 'Item 3', name: 'rb', inputValue: '3'},
93545                 {boxLabel: 'Item 4', name: 'rb', inputValue: '4'},
93546                 {boxLabel: 'Item 5', name: 'rb', inputValue: '5'},
93547                 {boxLabel: 'Item 6', name: 'rb', inputValue: '6'}
93548             ]
93549         }]
93550     });
93551  * </code></pre>
93552  * @constructor
93553  * Creates a new CheckboxGroup
93554  * @param {Object} config Configuration options
93555  * @xtype checkboxgroup
93556  */
93557 Ext.define('Ext.form.CheckboxGroup', {
93558     extend:'Ext.form.FieldContainer',
93559     mixins: {
93560         field: 'Ext.form.field.Field'
93561     },
93562     alias: 'widget.checkboxgroup',
93563     requires: ['Ext.layout.container.CheckboxGroup', 'Ext.form.field.Base'],
93564
93565     /**
93566      * @cfg {String} name
93567      * @hide
93568      */
93569
93570     /**
93571      * @cfg {Array} items An Array of {@link Ext.form.field.Checkbox Checkbox}es or Checkbox config objects
93572      * to arrange in the group.
93573      */
93574
93575     /**
93576      * @cfg {String/Number/Array} columns Specifies the number of columns to use when displaying grouped
93577      * checkbox/radio controls using automatic layout.  This config can take several types of values:
93578      * <ul><li><b>'auto'</b> : <p class="sub-desc">The controls will be rendered one per column on one row and the width
93579      * of each column will be evenly distributed based on the width of the overall field container. This is the default.</p></li>
93580      * <li><b>Number</b> : <p class="sub-desc">If you specific a number (e.g., 3) that number of columns will be
93581      * created and the contained controls will be automatically distributed based on the value of {@link #vertical}.</p></li>
93582      * <li><b>Array</b> : <p class="sub-desc">You can also specify an array of column widths, mixing integer
93583      * (fixed width) and float (percentage width) values as needed (e.g., [100, .25, .75]). Any integer values will
93584      * be rendered first, then any float values will be calculated as a percentage of the remaining space. Float
93585      * values do not have to add up to 1 (100%) although if you want the controls to take up the entire field
93586      * container you should do so.</p></li></ul>
93587      */
93588     columns : 'auto',
93589
93590     /**
93591      * @cfg {Boolean} vertical True to distribute contained controls across columns, completely filling each column
93592      * top to bottom before starting on the next column.  The number of controls in each column will be automatically
93593      * calculated to keep columns as even as possible.  The default value is false, so that controls will be added
93594      * to columns one at a time, completely filling each row left to right before starting on the next row.
93595      */
93596     vertical : false,
93597
93598     /**
93599      * @cfg {Boolean} allowBlank False to validate that at least one item in the group is checked (defaults to true).
93600      * If no items are selected at validation time, {@link #blankText} will be used as the error text.
93601      */
93602     allowBlank : true,
93603
93604     /**
93605      * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails (defaults to "You must
93606      * select at least one item in this group")
93607      */
93608     blankText : "You must select at least one item in this group",
93609
93610     // private
93611     defaultType : 'checkboxfield',
93612
93613     // private
93614     groupCls : Ext.baseCSSPrefix + 'form-check-group',
93615
93616     /**
93617      * @cfg {String} fieldBodyCls
93618      * An extra CSS class to be applied to the body content element in addition to {@link #baseBodyCls}.
93619      * Defaults to 'x-form-checkboxgroup-body'.
93620      */
93621     fieldBodyCls: Ext.baseCSSPrefix + 'form-checkboxgroup-body',
93622
93623     // private
93624     layout: 'checkboxgroup',
93625
93626     initComponent: function() {
93627         var me = this;
93628         me.callParent();
93629         me.initField();
93630     },
93631
93632     /**
93633      * @protected
93634      * Initializes the field's value based on the initial config. If the {@link #value} config is specified
93635      * then we use that to set the value; otherwise we initialize the originalValue by querying the values of
93636      * all sub-checkboxes after they have been initialized.
93637      */
93638     initValue: function() {
93639         var me = this,
93640             valueCfg = me.value;
93641         me.originalValue = me.lastValue = valueCfg || me.getValue();
93642         if (valueCfg) {
93643             me.setValue(valueCfg);
93644         }
93645     },
93646
93647     /**
93648      * @protected
93649      * When a checkbox is added to the group, monitor it for changes
93650      */
93651     onFieldAdded: function(field) {
93652         var me = this;
93653         if (field.isCheckbox) {
93654             me.mon(field, 'change', me.checkChange, me);
93655         }
93656         me.callParent(arguments);
93657     },
93658
93659     onFieldRemoved: function(field) {
93660         var me = this;
93661         if (field.isCheckbox) {
93662             me.mun(field, 'change', me.checkChange, me);
93663         }
93664         me.callParent(arguments);
93665     },
93666
93667     // private override - the group value is a complex object, compare using object serialization
93668     isEqual: function(value1, value2) {
93669         var toQueryString = Ext.Object.toQueryString;
93670         return toQueryString(value1) === toQueryString(value2);
93671     },
93672
93673     /**
93674      * Runs CheckboxGroup's validations and returns an array of any errors. The only error by default
93675      * is if allowBlank is set to true and no items are checked.
93676      * @return {Array} Array of all validation errors
93677      */
93678     getErrors: function() {
93679         var errors = [];
93680         if (!this.allowBlank && Ext.isEmpty(this.getChecked())) {
93681             errors.push(this.blankText);
93682         }
93683         return errors;
93684     },
93685
93686     /**
93687      * @private Returns all checkbox components within the container
93688      */
93689     getBoxes: function() {
93690         return this.query('[isCheckbox]');
93691     },
93692
93693     /**
93694      * @private Convenience function which calls the given function for every checkbox in the group
93695      * @param {Function} fn The function to call
93696      * @param {Object} scope Optional scope object
93697      */
93698     eachBox: function(fn, scope) {
93699         Ext.Array.forEach(this.getBoxes(), fn, scope || this);
93700     },
93701
93702     /**
93703      * Returns an Array of all checkboxes in the container which are currently checked
93704      * @return {Array} Array of Ext.form.field.Checkbox components
93705      */
93706     getChecked: function() {
93707         return Ext.Array.filter(this.getBoxes(), function(cb) {
93708             return cb.getValue();
93709         });
93710     },
93711
93712     // private override
93713     isDirty: function(){
93714         return Ext.Array.some(this.getBoxes(), function(cb) {
93715             return cb.isDirty();
93716         });
93717     },
93718
93719     // private override
93720     setReadOnly: function(readOnly) {
93721         this.eachBox(function(cb) {
93722             cb.setReadOnly(readOnly);
93723         });
93724         this.readOnly = readOnly;
93725     },
93726
93727     /**
93728      * Resets the checked state of all {@link Ext.form.field.Checkbox checkboxes} in the group to their
93729      * originally loaded values and clears any validation messages.
93730      * See {@link Ext.form.Basic}.{@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
93731      */
93732     reset: function() {
93733         var me = this,
93734             hadError = me.hasActiveError(),
93735             preventMark = me.preventMark;
93736         me.preventMark = true;
93737         me.batchChanges(function() {
93738             me.eachBox(function(cb) {
93739                 cb.reset();
93740             });
93741         });
93742         me.preventMark = preventMark;
93743         me.unsetActiveError();
93744         if (hadError) {
93745             me.doComponentLayout();
93746         }
93747     },
93748
93749     // private override
93750     resetOriginalValue: function() {
93751         // Defer resetting of originalValue until after all sub-checkboxes have been reset so we get
93752         // the correct data from getValue()
93753         Ext.defer(function() {
93754             this.callParent();
93755         }, 1, this);
93756     },
93757
93758
93759     /**
93760      * <p>Sets the value(s) of all checkboxes in the group. The expected format is an Object of
93761      * name-value pairs corresponding to the names of the checkboxes in the group. Each pair can
93762      * have either a single or multiple values:</p>
93763      * <ul>
93764      *   <li>A single Boolean or String value will be passed to the <code>setValue</code> method of the
93765      *   checkbox with that name. See the rules in {@link Ext.form.field.Checkbox#setValue} for accepted values.</li>
93766      *   <li>An Array of String values will be matched against the {@link Ext.form.field.Checkbox#inputValue inputValue}
93767      *   of checkboxes in the group with that name; those checkboxes whose inputValue exists in the array will be
93768      *   checked and others will be unchecked.</li>
93769      * </ul>
93770      * <p>If a checkbox's name is not in the mapping at all, it will be unchecked.</p>
93771      * <p>An example:</p>
93772      * <pre><code>var myCheckboxGroup = new Ext.form.CheckboxGroup({
93773     columns: 3,
93774     items: [{
93775         name: 'cb1',
93776         boxLabel: 'Single 1'
93777     }, {
93778         name: 'cb2',
93779         boxLabel: 'Single 2'
93780     }, {
93781         name: 'cb3',
93782         boxLabel: 'Single 3'
93783     }, {
93784         name: 'cbGroup',
93785         boxLabel: 'Grouped 1'
93786         inputValue: 'value1'
93787     }, {
93788         name: 'cbGroup',
93789         boxLabel: 'Grouped 2'
93790         inputValue: 'value2'
93791     }, {
93792         name: 'cbGroup',
93793         boxLabel: 'Grouped 3'
93794         inputValue: 'value3'
93795     }]
93796 });
93797
93798 myCheckboxGroup.setValue({
93799     cb1: true,
93800     cb3: false,
93801     cbGroup: ['value1', 'value3']
93802 });</code></pre>
93803      * <p>The above code will cause the checkbox named 'cb1' to be checked, as well as the first and third
93804      * checkboxes named 'cbGroup'. The other three checkboxes will be unchecked.</p>
93805      * @param {Object} value The mapping of checkbox names to values.
93806      * @return {Ext.form.CheckboxGroup} this
93807      */
93808     setValue: function(value) {
93809         var me = this;
93810         me.batchChanges(function() {
93811             me.eachBox(function(cb) {
93812                 var name = cb.getName(),
93813                     cbValue = false;
93814                 if (value && name in value) {
93815                     if (Ext.isArray(value[name])) {
93816                         cbValue = Ext.Array.contains(value[name], cb.inputValue);
93817                     } else {
93818                         // single value, let the checkbox's own setValue handle conversion
93819                         cbValue = value[name];
93820                     }
93821                 }
93822                 cb.setValue(cbValue);
93823             });
93824         });
93825         return me;
93826     },
93827
93828
93829     /**
93830      * <p>Returns an object containing the values of all checked checkboxes within the group. Each key-value pair
93831      * in the object corresponds to a checkbox {@link Ext.form.field.Checkbox#name name}. If there is only one checked
93832      * checkbox with a particular name, the value of that pair will be the String
93833      * {@link Ext.form.field.Checkbox#inputValue inputValue} of that checkbox. If there are multiple checked checkboxes
93834      * with that name, the value of that pair will be an Array of the selected inputValues.</p>
93835      * <p>The object format returned from this method can also be passed directly to the {@link #setValue} method.</p>
93836      * <p>NOTE: In Ext 3, this method returned an array of Checkbox components; this was changed to make it more
93837      * consistent with other field components and with the {@link #setValue} argument signature. If you need the old
93838      * behavior in Ext 4+, use the {@link #getChecked} method instead.</p>
93839      */
93840     getValue: function() {
93841         var values = {};
93842         this.eachBox(function(cb) {
93843             var name = cb.getName(),
93844                 inputValue = cb.inputValue,
93845                 bucket;
93846             if (cb.getValue()) {
93847                 if (name in values) {
93848                     bucket = values[name];
93849                     if (!Ext.isArray(bucket)) {
93850                         bucket = values[name] = [bucket];
93851                     }
93852                     bucket.push(inputValue);
93853                 } else {
93854                     values[name] = inputValue;
93855                 }
93856             }
93857         });
93858         return values;
93859     },
93860
93861     /*
93862      * Don't return any data for submit; the form will get the info from the individual checkboxes themselves.
93863      */
93864     getSubmitData: function() {
93865         return null;
93866     },
93867
93868     /*
93869      * Don't return any data for the model; the form will get the info from the individual checkboxes themselves.
93870      */
93871     getModelData: function() {
93872         return null;
93873     },
93874
93875     validate: function() {
93876         var me = this,
93877             errors = me.getErrors(),
93878             isValid = Ext.isEmpty(errors),
93879             wasValid = !me.hasActiveError();
93880
93881         if (isValid) {
93882             me.unsetActiveError();
93883         } else {
93884             me.setActiveError(errors);
93885         }
93886         if (isValid !== wasValid) {
93887             me.fireEvent('validitychange', me, isValid);
93888             me.doComponentLayout();
93889         }
93890
93891         return isValid;
93892     }
93893
93894 }, function() {
93895
93896     this.borrow(Ext.form.field.Base, ['markInvalid', 'clearInvalid']);
93897
93898 });
93899
93900
93901 /**
93902  * @private
93903  * Private utility class for managing all {@link Ext.form.field.Checkbox} fields grouped by name.
93904  */
93905 Ext.define('Ext.form.CheckboxManager', {
93906     extend: 'Ext.util.MixedCollection',
93907     singleton: true,
93908
93909     getByName: function(name) {
93910         return this.filterBy(function(item) {
93911             return item.name == name;
93912         });
93913     },
93914
93915     getWithValue: function(name, value) {
93916         return this.filterBy(function(item) {
93917             return item.name == name && item.inputValue == value;
93918         });
93919     },
93920
93921     getChecked: function(name) {
93922         return this.filterBy(function(item) {
93923             return item.name == name && item.checked;
93924         });
93925     }
93926 });
93927
93928 /**
93929  * @class Ext.form.FieldSet
93930  * @extends Ext.container.Container
93931  * 
93932  * A container for grouping sets of fields, rendered as a HTML `fieldset` element. The {@link #title}
93933  * config will be rendered as the fieldset's `legend`.
93934  * 
93935  * While FieldSets commonly contain simple groups of fields, they are general {@link Ext.container.Container Containers}
93936  * and may therefore contain any type of components in their {@link #items}, including other nested containers.
93937  * The default {@link #layout} for the FieldSet's items is `'anchor'`, but it can be configured to use any other
93938  * layout type.
93939  * 
93940  * FieldSets may also be collapsed if configured to do so; this can be done in two ways:
93941  * 
93942  * 1. Set the {@link #collapsible} config to true; this will result in a collapse button being rendered next to
93943  *    the {@link #title legend title}, or:
93944  * 2. Set the {@link #checkboxToggle} config to true; this is similar to using {@link #collapsible} but renders
93945  *    a {@link Ext.form.field.Checkbox checkbox} in place of the toggle button. The fieldset will be expanded when the
93946  *    checkbox is checked and collapsed when it is unchecked. The checkbox will also be included in the
93947  *    {@link Ext.form.Basic#submit form submit parameters} using the {@link #checkboxName} as its parameter name.
93948  *
93949  * {@img Ext.form.FieldSet/Ext.form.FieldSet.png Ext.form.FieldSet component}
93950  *
93951  * ## Example usage
93952  * 
93953  *     Ext.create('Ext.form.Panel', {
93954  *         title: 'Simple Form with FieldSets',
93955  *         labelWidth: 75, // label settings here cascade unless overridden
93956  *         url: 'save-form.php',
93957  *         frame: true,
93958  *         bodyStyle: 'padding:5px 5px 0',
93959  *         width: 550,
93960  *         renderTo: Ext.getBody(),
93961  *         layout: 'column', // arrange fieldsets side by side
93962  *         defaults: {
93963  *             bodyPadding: 4
93964  *         },
93965  *         items: [{
93966  *             // Fieldset in Column 1 - collapsible via toggle button
93967  *             xtype:'fieldset',
93968  *             columnWidth: 0.5,
93969  *             title: 'Fieldset 1',
93970  *             collapsible: true,
93971  *             defaultType: 'textfield',
93972  *             defaults: {anchor: '100%'},
93973  *             layout: 'anchor',
93974  *             items :[{
93975  *                 fieldLabel: 'Field 1',
93976  *                 name: 'field1'
93977  *             }, {
93978  *                 fieldLabel: 'Field 2',
93979  *                 name: 'field2'
93980  *             }]
93981  *         }, {
93982  *             // Fieldset in Column 2 - collapsible via checkbox, collapsed by default, contains a panel
93983  *             xtype:'fieldset',
93984  *             title: 'Show Panel', // title or checkboxToggle creates fieldset header
93985  *             columnWidth: 0.5,
93986  *             checkboxToggle: true,
93987  *             collapsed: true, // fieldset initially collapsed
93988  *             layout:'anchor',
93989  *             items :[{
93990  *                 xtype: 'panel',
93991  *                 anchor: '100%',
93992  *                 title: 'Panel inside a fieldset',
93993  *                 frame: true,
93994  *                 height: 52
93995  *             }]
93996  *         }]
93997  *     });
93998  * 
93999  * @constructor
94000  * Create a new FieldSet
94001  * @param {Object} config Configuration options
94002  * @xtype fieldset
94003  * @docauthor Jason Johnston <jason@sencha.com>
94004  */
94005 Ext.define('Ext.form.FieldSet', {
94006     extend: 'Ext.container.Container',
94007     alias: 'widget.fieldset',
94008     uses: ['Ext.form.field.Checkbox', 'Ext.panel.Tool', 'Ext.layout.container.Anchor', 'Ext.layout.component.FieldSet'],
94009
94010     /**
94011      * @cfg {String} title
94012      * A title to be displayed in the fieldset's legend. May contain HTML markup.
94013      */
94014
94015     /**
94016      * @cfg {Boolean} checkboxToggle
94017      * Set to <tt>true</tt> to render a checkbox into the fieldset frame just
94018      * in front of the legend to expand/collapse the fieldset when the checkbox is toggled. (defaults
94019      * to <tt>false</tt>). This checkbox will be included in form submits using the {@link #checkboxName}.
94020      */
94021
94022     /**
94023      * @cfg {String} checkboxName
94024      * The name to assign to the fieldset's checkbox if <tt>{@link #checkboxToggle} = true</tt>
94025      * (defaults to <tt>'[fieldset id]-checkbox'</tt>).
94026      */
94027
94028     /**
94029      * @cfg {Boolean} collapsible
94030      * Set to <tt>true</tt> to make the fieldset collapsible and have the expand/collapse toggle button automatically
94031      * rendered into the legend element, <tt>false</tt> to keep the fieldset statically sized with no collapse
94032      * button (defaults to <tt>false</tt>). Another option is to configure <tt>{@link #checkboxToggle}</tt>.
94033      * Use the {@link #collapsed} config to collapse the fieldset by default.
94034      */
94035
94036     /**
94037      * @cfg {Boolean} collapsed
94038      * Set to <tt>true</tt> to render the fieldset as collapsed by default. If {@link #checkboxToggle} is specified,
94039      * the checkbox will also be unchecked by default.
94040      */
94041     collapsed: false,
94042
94043     /**
94044      * @property legend
94045      * @type Ext.Component
94046      * The component for the fieldset's legend. Will only be defined if the configuration requires a legend
94047      * to be created, by setting the {@link #title} or {@link #checkboxToggle} options.
94048      */
94049
94050     /**
94051      * @cfg {String} baseCls The base CSS class applied to the fieldset (defaults to <tt>'x-fieldset'</tt>).
94052      */
94053     baseCls: Ext.baseCSSPrefix + 'fieldset',
94054
94055     /**
94056      * @cfg {String} layout The {@link Ext.container.Container#layout} for the fieldset's immediate child items.
94057      * Defaults to <tt>'anchor'</tt>.
94058      */
94059     layout: 'anchor',
94060
94061     componentLayout: 'fieldset',
94062
94063     // No aria role necessary as fieldset has its own recognized semantics
94064     ariaRole: '',
94065
94066     renderTpl: ['<div class="{baseCls}-body"></div>'],
94067     
94068     maskOnDisable: false,
94069
94070     getElConfig: function(){
94071         return {tag: 'fieldset', id: this.id};
94072     },
94073
94074     initComponent: function() {
94075         var me = this,
94076             baseCls = me.baseCls;
94077
94078         me.callParent();
94079
94080         // Create the Legend component if needed
94081         me.initLegend();
94082
94083         // Add body el selector
94084         Ext.applyIf(me.renderSelectors, {
94085             body: '.' + baseCls + '-body'
94086         });
94087
94088         if (me.collapsed) {
94089             me.addCls(baseCls + '-collapsed');
94090             me.collapse();
94091         }
94092     },
94093
94094     // private
94095     onRender: function(container, position) {
94096         this.callParent(arguments);
94097         // Make sure the legend is created and rendered
94098         this.initLegend();
94099     },
94100
94101     /**
94102      * @private
94103      * Initialize and render the legend component if necessary
94104      */
94105     initLegend: function() {
94106         var me = this,
94107             legendItems,
94108             legend = me.legend;
94109
94110         // Create the legend component if needed and it hasn't been already
94111         if (!legend && (me.title || me.checkboxToggle || me.collapsible)) {
94112             legendItems = [];
94113
94114             // Checkbox
94115             if (me.checkboxToggle) {
94116                 legendItems.push(me.createCheckboxCmp());
94117             }
94118             // Toggle button
94119             else if (me.collapsible) {
94120                 legendItems.push(me.createToggleCmp());
94121             }
94122
94123             // Title
94124             legendItems.push(me.createTitleCmp());
94125
94126             legend = me.legend = Ext.create('Ext.container.Container', {
94127                 baseCls: me.baseCls + '-header',
94128                 ariaRole: '',
94129                 getElConfig: function(){
94130                     return {tag: 'legend', cls: this.baseCls};
94131                 },
94132                 items: legendItems
94133             });
94134         }
94135
94136         // Make sure legend is rendered if the fieldset is rendered
94137         if (legend && !legend.rendered && me.rendered) {
94138             me.legend.render(me.el, me.body); //insert before body element
94139         }
94140     },
94141
94142     /**
94143      * @protected
94144      * Creates the legend title component. This is only called internally, but could be overridden in subclasses
94145      * to customize the title component.
94146      * @return Ext.Component
94147      */
94148     createTitleCmp: function() {
94149         var me = this;
94150         me.titleCmp = Ext.create('Ext.Component', {
94151             html: me.title,
94152             cls: me.baseCls + '-header-text'
94153         });
94154         return me.titleCmp;
94155         
94156     },
94157
94158     /**
94159      * @property checkboxCmp
94160      * @type Ext.form.field.Checkbox
94161      * Refers to the {@link Ext.form.field.Checkbox} component that is added next to the title in the legend. Only
94162      * populated if the fieldset is configured with <tt>{@link #checkboxToggle}:true</tt>.
94163      */
94164
94165     /**
94166      * @protected
94167      * Creates the checkbox component. This is only called internally, but could be overridden in subclasses
94168      * to customize the checkbox's configuration or even return an entirely different component type.
94169      * @return Ext.Component
94170      */
94171     createCheckboxCmp: function() {
94172         var me = this,
94173             suffix = '-checkbox';
94174             
94175         me.checkboxCmp = Ext.create('Ext.form.field.Checkbox', {
94176             name: me.checkboxName || me.id + suffix,
94177             cls: me.baseCls + '-header' + suffix,
94178             checked: !me.collapsed,
94179             listeners: {
94180                 change: me.onCheckChange,
94181                 scope: me
94182             }
94183         });
94184         return me.checkboxCmp;
94185     },
94186
94187     /**
94188      * @property toggleCmp
94189      * @type Ext.panel.Tool
94190      * Refers to the {@link Ext.panel.Tool} component that is added as the collapse/expand button next
94191      * to the title in the legend. Only populated if the fieldset is configured with <tt>{@link #collapsible}:true</tt>.
94192      */
94193
94194     /**
94195      * @protected
94196      * Creates the toggle button component. This is only called internally, but could be overridden in
94197      * subclasses to customize the toggle component.
94198      * @return Ext.Component
94199      */
94200     createToggleCmp: function() {
94201         var me = this;
94202         me.toggleCmp = Ext.create('Ext.panel.Tool', {
94203             type: 'toggle',
94204             handler: me.toggle,
94205             scope: me
94206         });
94207         return me.toggleCmp;
94208     },
94209     
94210     /**
94211      * Sets the title of this fieldset
94212      * @param {String} title The new title
94213      * @return {Ext.form.FieldSet} this
94214      */
94215     setTitle: function(title) {
94216         var me = this;
94217         me.title = title;
94218         me.initLegend();
94219         me.titleCmp.update(title);
94220         return me;
94221     },
94222     
94223     getTargetEl : function() {
94224         return this.body || this.frameBody || this.el;
94225     },
94226     
94227     getContentTarget: function() {
94228         return this.body;
94229     },
94230     
94231     /**
94232      * @private
94233      * Include the legend component in the items for ComponentQuery
94234      */
94235     getRefItems: function(deep) {
94236         var refItems = this.callParent(arguments),
94237             legend = this.legend;
94238
94239         // Prepend legend items to ensure correct order
94240         if (legend) {
94241             refItems.unshift(legend);
94242             if (deep) {
94243                 refItems.unshift.apply(refItems, legend.getRefItems(true));
94244             }
94245         }
94246         return refItems;
94247     },
94248
94249     /**
94250      * Expands the fieldset.
94251      * @return {Ext.form.FieldSet} this
94252      */
94253     expand : function(){
94254         return this.setExpanded(true);
94255     },
94256     
94257     /**
94258      * Collapses the fieldset.
94259      * @return {Ext.form.FieldSet} this
94260      */
94261     collapse : function() {
94262         return this.setExpanded(false);
94263     },
94264
94265     /**
94266      * @private Collapse or expand the fieldset
94267      */
94268     setExpanded: function(expanded) {
94269         var me = this,
94270             checkboxCmp = me.checkboxCmp,
94271             toggleCmp = me.toggleCmp;
94272
94273         expanded = !!expanded;
94274         
94275         if (checkboxCmp) {
94276             checkboxCmp.setValue(expanded);
94277         }
94278         
94279         if (expanded) {
94280             me.removeCls(me.baseCls + '-collapsed');
94281         } else {
94282             me.addCls(me.baseCls + '-collapsed');
94283         }
94284         me.collapsed = !expanded;
94285         me.doComponentLayout();
94286         return me;
94287     },
94288
94289     /**
94290      * Toggle the fieldset's collapsed state to the opposite of what it is currently
94291      */
94292     toggle: function() {
94293         this.setExpanded(!!this.collapsed);
94294     },
94295
94296     /**
94297      * @private Handle changes in the checkbox checked state
94298      */
94299     onCheckChange: function(cmp, checked) {
94300         this.setExpanded(checked);
94301     },
94302
94303     beforeDestroy : function() {
94304         var legend = this.legend;
94305         if (legend) {
94306             legend.destroy();
94307         }
94308         this.callParent();
94309     }
94310 });
94311
94312 /**
94313  * @class Ext.form.Label
94314  * @extends Ext.Component
94315
94316 Produces a standalone `<label />` element which can be inserted into a form and be associated with a field
94317 in that form using the {@link #forId} property.
94318
94319 **NOTE:** in most cases it will be more appropriate to use the {@link Ext.form.Labelable#fieldLabel fieldLabel}
94320 and associated config properties ({@link Ext.form.Labelable#labelAlign}, {@link Ext.form.Labelable#labelWidth},
94321 etc.) in field components themselves, as that allows labels to be uniformly sized throughout the form.
94322 Ext.form.Label should only be used when your layout can not be achieved with the standard
94323 {@link Ext.form.Labelable field layout}.
94324
94325 You will likely be associating the label with a field component that extends {@link Ext.form.field.Base}, so
94326 you should make sure the {@link #forId} is set to the same value as the {@link Ext.form.field.Base#inputId inputId}
94327 of that field.
94328
94329 The label's text can be set using either the {@link #text} or {@link #html} configuration properties; the
94330 difference between the two is that the former will automatically escape HTML characters when rendering, while
94331 the latter will not.
94332 {@img Ext.form.Label/Ext.form.Label.png Ext.form.Label component}
94333 #Example usage:#
94334
94335 This example creates a Label after its associated Text field, an arrangement that cannot currently
94336 be achieved using the standard Field layout's labelAlign.
94337
94338     Ext.create('Ext.form.Panel', {
94339         title: 'Field with Label',
94340         width: 400,
94341         bodyPadding: 10,
94342         renderTo: Ext.getBody(),
94343         layout: {
94344             type: 'hbox',
94345             align: 'middle'
94346         },
94347         items: [{
94348             xtype: 'textfield',
94349             hideLabel: true,
94350             flex: 1
94351         }, {
94352             xtype: 'label',
94353             forId: 'myFieldId',
94354             text: 'My Awesome Field',
94355             margins: '0 0 0 10'
94356         }]
94357     });
94358
94359  * @constructor
94360  * Creates a new Label component.
94361  * @param {Ext.core.Element/String/Object} config The configuration options.
94362  * 
94363  * @xtype label
94364  * @markdown
94365  * @docauthor Jason Johnston <jason@sencha.com>
94366  */
94367 Ext.define('Ext.form.Label', {
94368     extend:'Ext.Component',
94369     alias: 'widget.label',
94370     requires: ['Ext.util.Format'],
94371
94372     /**
94373      * @cfg {String} text The plain text to display within the label (defaults to ''). If you need to include HTML
94374      * tags within the label's innerHTML, use the {@link #html} config instead.
94375      */
94376     /**
94377      * @cfg {String} forId The id of the input element to which this label will be bound via the standard HTML 'for'
94378      * attribute. If not specified, the attribute will not be added to the label. In most cases you will be
94379      * associating the label with a {@link Ext.form.field.Base} component, so you should make sure this matches
94380      * the {@link Ext.form.field.Base#inputId inputId} of that field.
94381      */
94382     /**
94383      * @cfg {String} html An HTML fragment that will be used as the label's innerHTML (defaults to '').
94384      * Note that if {@link #text} is specified it will take precedence and this value will be ignored.
94385      */
94386     
94387     maskOnDisable: false,
94388     getElConfig: function(){
94389         var me = this;
94390         return {
94391             tag: 'label', 
94392             id: me.id, 
94393             htmlFor: me.forId || '',
94394             html: me.text ? Ext.util.Format.htmlEncode(me.text) : (me.html || '') 
94395         };
94396     },
94397
94398     /**
94399      * Updates the label's innerHTML with the specified string.
94400      * @param {String} text The new label text
94401      * @param {Boolean} encode (optional) False to skip HTML-encoding the text when rendering it
94402      * to the label (defaults to true which encodes the value). This might be useful if you want to include
94403      * tags in the label's innerHTML rather than rendering them as string literals per the default logic.
94404      * @return {Label} this
94405      */
94406     setText : function(text, encode){
94407         var me = this;
94408         
94409         encode = encode !== false;
94410         if(encode) {
94411             me.text = text;
94412             delete me.html;
94413         } else {
94414             me.html = text;
94415             delete me.text;
94416         }
94417         
94418         if(me.rendered){
94419             me.el.dom.innerHTML = encode !== false ? Ext.util.Format.htmlEncode(text) : text;
94420         }
94421         return this;
94422     }
94423 });
94424
94425
94426 /**
94427  * @class Ext.form.Panel
94428  * @extends Ext.panel.Panel
94429
94430 FormPanel provides a standard container for forms. It is essentially a standard {@link Ext.panel.Panel} which
94431 automatically creates a {@link Ext.form.Basic BasicForm} for managing any {@link Ext.form.field.Field}
94432 objects that are added as descendants of the panel. It also includes conveniences for configuring and
94433 working with the BasicForm and the collection of Fields.
94434
94435 __Layout__
94436
94437 By default, FormPanel is configured with `{@link Ext.layout.container.Anchor layout:'anchor'}` for
94438 the layout of its immediate child items. This can be changed to any of the supported container layouts.
94439 The layout of sub-containers is configured in {@link Ext.container.Container#layout the standard way}.
94440
94441 __BasicForm__
94442
94443 Although **not listed** as configuration options of FormPanel, the FormPanel class accepts all
94444 of the config options supported by the {@link Ext.form.Basic} class, and will pass them along to
94445 the internal BasicForm when it is created.
94446
94447 **Note**: If subclassing FormPanel, any configuration options for the BasicForm must be applied to
94448 the `initialConfig` property of the FormPanel. Applying {@link Ext.form.Basic BasicForm}
94449 configuration settings to `this` will *not* affect the BasicForm's configuration.
94450
94451 The following events fired by the BasicForm will be re-fired by the FormPanel and can therefore be
94452 listened for on the FormPanel itself:
94453
94454 - {@link Ext.form.Basic#beforeaction beforeaction}
94455 - {@link Ext.form.Basic#actionfailed actionfailed}
94456 - {@link Ext.form.Basic#actioncomplete actioncomplete}
94457 - {@link Ext.form.Basic#validitychange validitychange}
94458 - {@link Ext.form.Basic#dirtychange dirtychange}
94459
94460 __Field Defaults__
94461
94462 The {@link #fieldDefaults} config option conveniently allows centralized configuration of default values
94463 for all fields added as descendants of the FormPanel. Any config option recognized by implementations
94464 of {@link Ext.form.Labelable} may be included in this object. See the {@link #fieldDefaults} documentation
94465 for details of how the defaults are applied.
94466
94467 __Form Validation__
94468
94469 With the default configuration, form fields are validated on-the-fly while the user edits their values.
94470 This can be controlled on a per-field basis (or via the {@link #fieldDefaults} config) with the field
94471 config properties {@link Ext.form.field.Field#validateOnChange} and {@link Ext.form.field.Base#checkChangeEvents},
94472 and the FormPanel's config properties {@link #pollForChanges} and {@link #pollInterval}.
94473
94474 Any component within the FormPanel can be configured with `formBind: true`. This will cause that
94475 component to be automatically disabled when the form is invalid, and enabled when it is valid. This is most
94476 commonly used for Button components to prevent submitting the form in an invalid state, but can be used on
94477 any component type.
94478
94479 For more information on form validation see the following:
94480
94481 - {@link Ext.form.field.Field#validateOnChange}
94482 - {@link #pollForChanges} and {@link #pollInterval}
94483 - {@link Ext.form.field.VTypes}
94484 - {@link Ext.form.Basic#doAction BasicForm.doAction clientValidation notes}
94485
94486 __Form Submission__
94487
94488 By default, Ext Forms are submitted through Ajax, using {@link Ext.form.action.Action}. See the documentation for
94489 {@link Ext.form.Basic} for details.
94490 {@img Ext.form.FormPanel/Ext.form.FormPanel.png Ext.form.FormPanel FormPanel component}
94491 __Example usage:__
94492
94493     Ext.create('Ext.form.Panel', {
94494         title: 'Simple Form',
94495         bodyPadding: 5,
94496         width: 350,
94497         
94498         // The form will submit an AJAX request to this URL when submitted
94499         url: 'save-form.php',
94500         
94501         // Fields will be arranged vertically, stretched to full width
94502         layout: 'anchor',
94503         defaults: {
94504             anchor: '100%'
94505         },
94506         
94507         // The fields
94508         defaultType: 'textfield',
94509         items: [{
94510             fieldLabel: 'First Name',
94511             name: 'first',
94512             allowBlank: false
94513         },{
94514             fieldLabel: 'Last Name',
94515             name: 'last',
94516             allowBlank: false
94517         }],
94518         
94519         // Reset and Submit buttons
94520         buttons: [{
94521             text: 'Reset',
94522             handler: function() {
94523                 this.up('form').getForm().reset();
94524             }
94525         }, {
94526             text: 'Submit',
94527             formBind: true, //only enabled once the form is valid
94528             disabled: true,
94529             handler: function() {
94530                 var form = this.up('form').getForm();
94531                 if (form.isValid()) {
94532                     form.submit({
94533                         success: function(form, action) {
94534                            Ext.Msg.alert('Success', action.result.msg);
94535                         },
94536                         failure: function(form, action) {
94537                             Ext.Msg.alert('Failed', action.result.msg);
94538                         }
94539                     });
94540                 }
94541             }
94542         }],
94543         renderTo: Ext.getBody()
94544     });
94545
94546  * @constructor
94547  * @param {Object} config Configuration options
94548  * @xtype form
94549  *
94550  * @markdown
94551  * @docauthor Jason Johnston <jason@sencha.com>
94552  */
94553 Ext.define('Ext.form.Panel', {
94554     extend:'Ext.panel.Panel',
94555     mixins: {
94556         fieldAncestor: 'Ext.form.FieldAncestor'
94557     },
94558     alias: 'widget.form',
94559     alternateClassName: ['Ext.FormPanel', 'Ext.form.FormPanel'],
94560     requires: ['Ext.form.Basic', 'Ext.util.TaskRunner'],
94561
94562     /**
94563      * @cfg {Boolean} pollForChanges
94564      * If set to <tt>true</tt>, sets up an interval task (using the {@link #pollInterval}) in which the 
94565      * panel's fields are repeatedly checked for changes in their values. This is in addition to the normal detection
94566      * each field does on its own input element, and is not needed in most cases. It does, however, provide a
94567      * means to absolutely guarantee detection of all changes including some edge cases in some browsers which
94568      * do not fire native events. Defaults to <tt>false</tt>.
94569      */
94570
94571     /**
94572      * @cfg {Number} pollInterval
94573      * Interval in milliseconds at which the form's fields are checked for value changes. Only used if
94574      * the {@link #pollForChanges} option is set to <tt>true</tt>. Defaults to 500 milliseconds.
94575      */
94576
94577     /**
94578      * @cfg {String} layout The {@link Ext.container.Container#layout} for the form panel's immediate child items.
94579      * Defaults to <tt>'anchor'</tt>.
94580      */
94581     layout: 'anchor',
94582
94583     ariaRole: 'form',
94584
94585     initComponent: function() {
94586         var me = this;
94587         
94588         if (me.frame) {
94589             me.border = false;
94590         }
94591         
94592         me.initFieldAncestor();
94593         me.callParent();
94594
94595         me.relayEvents(me.form, [
94596             'beforeaction',
94597             'actionfailed',
94598             'actioncomplete',
94599             'validitychange',
94600             'dirtychange'
94601         ]);
94602
94603         // Start polling if configured
94604         if (me.pollForChanges) {
94605             me.startPolling(me.pollInterval || 500);
94606         }
94607     },
94608
94609     initItems: function() {
94610         // Create the BasicForm
94611         var me = this;
94612         
94613         me.form = me.createForm();
94614         me.callParent();
94615         me.form.initialize();
94616     },
94617
94618     /**
94619      * @private
94620      */
94621     createForm: function() {
94622         return Ext.create('Ext.form.Basic', this, Ext.applyIf({listeners: {}}, this.initialConfig));
94623     },
94624
94625     /**
94626      * Provides access to the {@link Ext.form.Basic Form} which this Panel contains.
94627      * @return {Ext.form.Basic} The {@link Ext.form.Basic Form} which this Panel contains.
94628      */
94629     getForm: function() {
94630         return this.form;
94631     },
94632     
94633     /**
94634      * Loads an {@link Ext.data.Model} into this form (internally just calls {@link Ext.form.Basic#loadRecord})
94635      * See also {@link #trackResetOnLoad}.
94636      * @param {Ext.data.Model} record The record to load
94637      * @return {Ext.form.Basic} The Ext.form.Basic attached to this FormPanel
94638      */
94639     loadRecord: function(record) {
94640         return this.getForm().loadRecord(record);
94641     },
94642     
94643     /**
94644      * Returns the currently loaded Ext.data.Model instance if one was loaded via {@link #loadRecord}.
94645      * @return {Ext.data.Model} The loaded instance
94646      */
94647     getRecord: function() {
94648         return this.getForm().getRecord();
94649     },
94650     
94651     /**
94652      * Convenience function for fetching the current value of each field in the form. This is the same as calling
94653      * {@link Ext.form.Basic#getValues this.getForm().getValues()}
94654      * @return {Object} The current form field values, keyed by field name
94655      */
94656     getValues: function() {
94657         return this.getForm().getValues();
94658     },
94659
94660     beforeDestroy: function() {
94661         this.stopPolling();
94662         this.form.destroy();
94663         this.callParent();
94664     },
94665
94666     /**
94667      * This is a proxy for the underlying BasicForm's {@link Ext.form.Basic#load} call.
94668      * @param {Object} options The options to pass to the action (see {@link Ext.form.Basic#load} and
94669      * {@link Ext.form.Basic#doAction} for details)
94670      */
94671     load: function(options) {
94672         this.form.load(options);
94673     },
94674
94675     /**
94676      * This is a proxy for the underlying BasicForm's {@link Ext.form.Basic#submit} call.
94677      * @param {Object} options The options to pass to the action (see {@link Ext.form.Basic#submit} and
94678      * {@link Ext.form.Basic#doAction} for details)
94679      */
94680     submit: function(options) {
94681         this.form.submit(options);
94682     },
94683
94684     /*
94685      * Inherit docs, not using onDisable because it only gets fired
94686      * when the component is rendered.
94687      */
94688     disable: function(silent) {
94689         this.callParent(arguments);
94690         this.form.getFields().each(function(field) {
94691             field.disable();
94692         });
94693     },
94694
94695     /*
94696      * Inherit docs, not using onEnable because it only gets fired
94697      * when the component is rendered.
94698      */
94699     enable: function(silent) {
94700         this.callParent(arguments);
94701         this.form.getFields().each(function(field) {
94702             field.enable();
94703         });
94704     },
94705
94706     /**
94707      * Start an interval task to continuously poll all the fields in the form for changes in their
94708      * values. This is normally started automatically by setting the {@link #pollForChanges} config.
94709      * @param {Number} interval The interval in milliseconds at which the check should run.
94710      */
94711     startPolling: function(interval) {
94712         this.stopPolling();
94713         var task = Ext.create('Ext.util.TaskRunner', interval);
94714         task.start({
94715             interval: 0,
94716             run: this.checkChange,
94717             scope: this
94718         });
94719         this.pollTask = task;
94720     },
94721
94722     /**
94723      * Stop a running interval task that was started by {@link #startPolling}.
94724      */
94725     stopPolling: function() {
94726         var task = this.pollTask;
94727         if (task) {
94728             task.stopAll();
94729             delete this.pollTask;
94730         }
94731     },
94732
94733     /**
94734      * Forces each field within the form panel to 
94735      * {@link Ext.form.field.Field#checkChange check if its value has changed}.
94736      */
94737     checkChange: function() {
94738         this.form.getFields().each(function(field) {
94739             field.checkChange();
94740         });
94741     }
94742 });
94743
94744 /**
94745  * @class Ext.form.RadioGroup
94746  * @extends Ext.form.CheckboxGroup
94747  * <p>A {@link Ext.form.FieldContainer field container} which has a specialized layout for arranging
94748  * {@link Ext.form.field.Radio} controls into columns, and provides convenience {@link Ext.form.field.Field} methods
94749  * for {@link #getValue getting}, {@link #setValue setting}, and {@link #validate validating} the group
94750  * of radio buttons as a whole.</p>
94751  * <p><b>Validation:</b> Individual radio buttons themselves have no default validation behavior, but
94752  * sometimes you want to require a user to select one of a group of radios. RadioGroup
94753  * allows this by setting the config <tt>{@link #allowBlank}:false</tt>; when the user does not check at
94754  * one of the radio buttons, the entire group will be highlighted as invalid and the
94755  * {@link #blankText error message} will be displayed according to the {@link #msgTarget} config.</p>
94756  * <p><b>Layout:</b> The default layout for RadioGroup makes it easy to arrange the radio buttons into
94757  * columns; see the {@link #columns} and {@link #vertical} config documentation for details. You may also
94758  * use a completely different layout by setting the {@link #layout} to one of the other supported layout
94759  * types; for instance you may wish to use a custom arrangement of hbox and vbox containers. In that case
94760  * the Radio components at any depth will still be managed by the RadioGroup's validation.</p>
94761  * <p>Example usage:</p>
94762  * <pre><code>
94763 var myRadioGroup = new Ext.form.RadioGroup({
94764     id: 'myGroup',
94765     xtype: 'radiogroup',
94766     fieldLabel: 'Single Column',
94767     // Arrange radio buttons into three columns, distributed vertically
94768     columns: 3,
94769     vertical: true,
94770     items: [
94771         {boxLabel: 'Item 1', name: 'rb', inputValue: '1'},
94772         {boxLabel: 'Item 2', name: 'rb', inputValue: '2', checked: true},
94773         {boxLabel: 'Item 3', name: 'rb', inputValue: '3'}
94774         {boxLabel: 'Item 4', name: 'rb', inputValue: '4'}
94775         {boxLabel: 'Item 5', name: 'rb', inputValue: '5'}
94776         {boxLabel: 'Item 6', name: 'rb', inputValue: '6'}
94777     ]
94778 });
94779  * </code></pre>
94780  * @constructor
94781  * Creates a new RadioGroup
94782  * @param {Object} config Configuration options
94783  * @xtype radiogroup
94784  */
94785 Ext.define('Ext.form.RadioGroup', {
94786     extend: 'Ext.form.CheckboxGroup',
94787     alias: 'widget.radiogroup',
94788
94789     /**
94790      * @cfg {Array} items An Array of {@link Ext.form.field.Radio Radio}s or Radio config objects
94791      * to arrange in the group.
94792      */
94793     /**
94794      * @cfg {Boolean} allowBlank True to allow every item in the group to be blank (defaults to true).
94795      * If allowBlank = false and no items are selected at validation time, {@link @blankText} will
94796      * be used as the error text.
94797      */
94798     allowBlank : true,
94799     /**
94800      * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails
94801      * (defaults to 'You must select one item in this group')
94802      */
94803     blankText : 'You must select one item in this group',
94804     
94805     // private
94806     defaultType : 'radiofield',
94807     
94808     // private
94809     groupCls : Ext.baseCSSPrefix + 'form-radio-group',
94810
94811     getBoxes: function() {
94812         return this.query('[isRadio]');
94813     }
94814
94815 });
94816
94817 /**
94818  * @private
94819  * Private utility class for managing all {@link Ext.form.field.Radio} fields grouped by name.
94820  */
94821 Ext.define('Ext.form.RadioManager', {
94822     extend: 'Ext.util.MixedCollection',
94823     singleton: true,
94824
94825     getByName: function(name) {
94826         return this.filterBy(function(item) {
94827             return item.name == name;
94828         });
94829     },
94830
94831     getWithValue: function(name, value) {
94832         return this.filterBy(function(item) {
94833             return item.name == name && item.inputValue == value;
94834         });
94835     },
94836
94837     getChecked: function(name) {
94838         return this.findBy(function(item) {
94839             return item.name == name && item.checked;
94840         });
94841     }
94842 });
94843
94844 /**
94845  * @class Ext.form.action.DirectLoad
94846  * @extends Ext.form.action.Load
94847  * <p>Provides {@link Ext.direct.Manager} support for loading form data.</p>
94848  * <p>This example illustrates usage of Ext.direct.Direct to <b>load</b> a form through Ext.Direct.</p>
94849  * <pre><code>
94850 var myFormPanel = new Ext.form.Panel({
94851     // configs for FormPanel
94852     title: 'Basic Information',
94853     renderTo: document.body,
94854     width: 300, height: 160,
94855     padding: 10,
94856
94857     // configs apply to child items
94858     defaults: {anchor: '100%'},
94859     defaultType: 'textfield',
94860     items: [{
94861         fieldLabel: 'Name',
94862         name: 'name'
94863     },{
94864         fieldLabel: 'Email',
94865         name: 'email'
94866     },{
94867         fieldLabel: 'Company',
94868         name: 'company'
94869     }],
94870
94871     // configs for BasicForm
94872     api: {
94873         // The server-side method to call for load() requests
94874         load: Profile.getBasicInfo,
94875         // The server-side must mark the submit handler as a 'formHandler'
94876         submit: Profile.updateBasicInfo
94877     },
94878     // specify the order for the passed params
94879     paramOrder: ['uid', 'foo']
94880 });
94881
94882 // load the form
94883 myFormPanel.getForm().load({
94884     // pass 2 arguments to server side getBasicInfo method (len=2)
94885     params: {
94886         foo: 'bar',
94887         uid: 34
94888     }
94889 });
94890  * </code></pre>
94891  * The data packet sent to the server will resemble something like:
94892  * <pre><code>
94893 [
94894     {
94895         "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
94896         "data":[34,"bar"] // note the order of the params
94897     }
94898 ]
94899  * </code></pre>
94900  * The form will process a data packet returned by the server that is similar
94901  * to the following format:
94902  * <pre><code>
94903 [
94904     {
94905         "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
94906         "result":{
94907             "success":true,
94908             "data":{
94909                 "name":"Fred Flintstone",
94910                 "company":"Slate Rock and Gravel",
94911                 "email":"fred.flintstone@slaterg.com"
94912             }
94913         }
94914     }
94915 ]
94916  * </code></pre>
94917  */
94918 Ext.define('Ext.form.action.DirectLoad', {
94919     extend:'Ext.form.action.Load',
94920     requires: ['Ext.direct.Manager'],
94921     alternateClassName: 'Ext.form.Action.DirectLoad',
94922     alias: 'formaction.directload',
94923
94924     type: 'directload',
94925
94926     run: function() {
94927         this.form.api.load.apply(window, this.getArgs());
94928     },
94929
94930     /**
94931      * @private
94932      * Build the arguments to be sent to the Direct call.
94933      * @return Array
94934      */
94935     getArgs: function() {
94936         var me = this,
94937             args = [],
94938             form = me.form,
94939             paramOrder = form.paramOrder,
94940             params = me.getParams(),
94941             i, len;
94942
94943         // If a paramOrder was specified, add the params into the argument list in that order.
94944         if (paramOrder) {
94945             for (i = 0, len = paramOrder.length; i < len; i++) {
94946                 args.push(params[paramOrder[i]]);
94947             }
94948         }
94949         // If paramsAsHash was specified, add all the params as a single object argument.
94950         else if (form.paramsAsHash) {
94951             args.push(params);
94952         }
94953
94954         // Add the callback and scope to the end of the arguments list
94955         args.push(me.onSuccess, me);
94956
94957         return args;
94958     },
94959
94960     // Direct actions have already been processed and therefore
94961     // we can directly set the result; Direct Actions do not have
94962     // a this.response property.
94963     processResponse: function(result) {
94964         return (this.result = result);
94965     },
94966
94967     onSuccess: function(result, trans) {
94968         if (trans.type == Ext.direct.Manager.self.exceptions.SERVER) {
94969             result = {};
94970         }
94971         this.callParent([result]);
94972     }
94973 });
94974
94975
94976
94977 /**
94978  * @class Ext.form.action.DirectSubmit
94979  * @extends Ext.form.action.Submit
94980  * <p>Provides Ext.direct support for submitting form data.</p>
94981  * <p>This example illustrates usage of Ext.direct.Direct to <b>submit</b> a form through Ext.Direct.</p>
94982  * <pre><code>
94983 var myFormPanel = new Ext.form.Panel({
94984     // configs for FormPanel
94985     title: 'Basic Information',
94986     renderTo: document.body,
94987     width: 300, height: 160,
94988     padding: 10,
94989     buttons:[{
94990         text: 'Submit',
94991         handler: function(){
94992             myFormPanel.getForm().submit({
94993                 params: {
94994                     foo: 'bar',
94995                     uid: 34
94996                 }
94997             });
94998         }
94999     }],
95000
95001     // configs apply to child items
95002     defaults: {anchor: '100%'},
95003     defaultType: 'textfield',
95004     items: [{
95005         fieldLabel: 'Name',
95006         name: 'name'
95007     },{
95008         fieldLabel: 'Email',
95009         name: 'email'
95010     },{
95011         fieldLabel: 'Company',
95012         name: 'company'
95013     }],
95014
95015     // configs for BasicForm
95016     api: {
95017         // The server-side method to call for load() requests
95018         load: Profile.getBasicInfo,
95019         // The server-side must mark the submit handler as a 'formHandler'
95020         submit: Profile.updateBasicInfo
95021     },
95022     // specify the order for the passed params
95023     paramOrder: ['uid', 'foo']
95024 });
95025  * </code></pre>
95026  * The data packet sent to the server will resemble something like:
95027  * <pre><code>
95028 {
95029     "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
95030     "result":{
95031         "success":true,
95032         "id":{
95033             "extAction":"Profile","extMethod":"updateBasicInfo",
95034             "extType":"rpc","extTID":"6","extUpload":"false",
95035             "name":"Aaron Conran","email":"aaron@sencha.com","company":"Sencha Inc."
95036         }
95037     }
95038 }
95039  * </code></pre>
95040  * The form will process a data packet returned by the server that is similar
95041  * to the following:
95042  * <pre><code>
95043 // sample success packet (batched requests)
95044 [
95045     {
95046         "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":3,
95047         "result":{
95048             "success":true
95049         }
95050     }
95051 ]
95052
95053 // sample failure packet (one request)
95054 {
95055         "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
95056         "result":{
95057             "errors":{
95058                 "email":"already taken"
95059             },
95060             "success":false,
95061             "foo":"bar"
95062         }
95063 }
95064  * </code></pre>
95065  * Also see the discussion in {@link Ext.form.action.DirectLoad}.
95066  */
95067 Ext.define('Ext.form.action.DirectSubmit', {
95068     extend:'Ext.form.action.Submit',
95069     requires: ['Ext.direct.Manager'],
95070     alternateClassName: 'Ext.form.Action.DirectSubmit',
95071     alias: 'formaction.directsubmit',
95072
95073     type: 'directsubmit',
95074
95075     doSubmit: function() {
95076         var me = this,
95077             callback = Ext.Function.bind(me.onSuccess, me),
95078             formEl = me.buildForm();
95079         me.form.api.submit(formEl, callback, me);
95080         Ext.removeNode(formEl);
95081     },
95082
95083     // Direct actions have already been processed and therefore
95084     // we can directly set the result; Direct Actions do not have
95085     // a this.response property.
95086     processResponse: function(result) {
95087         return (this.result = result);
95088     },
95089
95090     onSuccess: function(response, trans) {
95091         if (trans.type === Ext.direct.Manager.self.exceptions.SERVER) {
95092             response = {};
95093         }
95094         this.callParent([response]);
95095     }
95096 });
95097
95098 /**
95099  * @class Ext.form.action.StandardSubmit
95100  * @extends Ext.form.action.Submit
95101  * <p>A class which handles submission of data from {@link Ext.form.Basic Form}s using a standard
95102  * <tt>&lt;form&gt;</tt> element submit. It does not handle the response from the submit.</p>
95103  * <p>If validation of the form fields fails, the Form's {@link Ext.form.Basic#afterAction} method
95104  * will be called. Otherwise, afterAction will not be called.</p>
95105  * <p>Instances of this class are only created by a {@link Ext.form.Basic Form} when
95106  * {@link Ext.form.Basic#submit submit}ting, when the form's {@link Ext.form.Basic#standardSubmit}
95107  * config option is <tt>true</tt>.</p>
95108  */
95109 Ext.define('Ext.form.action.StandardSubmit', {
95110     extend:'Ext.form.action.Submit',
95111     alias: 'formaction.standardsubmit',
95112
95113     /**
95114      * @cfg {String} target
95115      * Optional <tt>target</tt> attribute to be used for the form when submitting. If not specified,
95116      * the target will be the current window/frame.
95117      */
95118
95119     /**
95120      * @private
95121      * Perform the form submit. Creates and submits a temporary form element containing an input element for each
95122      * field value returned by {@link Ext.form.Basic#getValues}, plus any configured {@link #params params} or
95123      * {@link Ext.form.Basic#baseParams baseParams}.
95124      */
95125     doSubmit: function() {
95126         var form = this.buildForm();
95127         form.submit();
95128         Ext.removeNode(form);
95129     }
95130
95131 });
95132
95133 /**
95134  * @class Ext.form.field.Checkbox
95135  * @extends Ext.form.field.Base
95136
95137 Single checkbox field. Can be used as a direct replacement for traditional checkbox fields. Also serves as a
95138 parent class for {@link Ext.form.field.Radio radio buttons}.
95139
95140 __Labeling:__ In addition to the {@link Ext.form.Labelable standard field labeling options}, checkboxes
95141 may be given an optional {@link #boxLabel} which will be displayed immediately after checkbox. Also see
95142 {@link Ext.form.CheckboxGroup} for a convenient method of grouping related checkboxes.
95143
95144 __Values:__
95145 The main value of a checkbox is a boolean, indicating whether or not the checkbox is checked.
95146 The following values will check the checkbox:
95147 * `true`
95148 * `'true'`
95149 * `'1'`
95150 * `'on'`
95151
95152 Any other value will uncheck the checkbox.
95153
95154 In addition to the main boolean value, you may also specify a separate {@link #inputValue}. This will be
95155 sent as the parameter value when the form is {@link Ext.form.Basic#submit submitted}. You will want to set
95156 this value if you have multiple checkboxes with the same {@link #name}. If not specified, the value `on`
95157 will be used.
95158 {@img Ext.form.Checkbox/Ext.form.Checkbox.png Ext.form.Checkbox Checkbox component}
95159 __Example usage:__
95160
95161     Ext.create('Ext.form.Panel', {
95162         bodyPadding: 10,
95163         width      : 300,
95164         title      : 'Pizza Order',
95165         items: [
95166             {
95167                 xtype      : 'fieldcontainer',
95168                 fieldLabel : 'Toppings',
95169                 defaultType: 'checkboxfield',
95170                 items: [
95171                     {
95172                         boxLabel  : 'Anchovies',
95173                         name      : 'topping',
95174                         inputValue: '1',
95175                         id        : 'checkbox1'
95176                     }, {
95177                         boxLabel  : 'Artichoke Hearts',
95178                         name      : 'topping',
95179                         inputValue: '2',
95180                         checked   : true,
95181                         id        : 'checkbox2'
95182                     }, {
95183                         boxLabel  : 'Bacon',
95184                         name      : 'topping',
95185                         inputValue: '3',
95186                         id        : 'checkbox3'
95187                     }
95188                 ]
95189             }
95190         ],
95191         bbar: [
95192             {
95193                 text: 'Select Bacon',
95194                 handler: function() {
95195                     var checkbox = Ext.getCmp('checkbox3');
95196                     checkbox.setValue(true);
95197                 }
95198             },
95199             '-',
95200             {
95201                 text: 'Select All',
95202                 handler: function() {
95203                     var checkbox1 = Ext.getCmp('checkbox1'),
95204                         checkbox2 = Ext.getCmp('checkbox2'),
95205                         checkbox3 = Ext.getCmp('checkbox3');
95206     
95207                     checkbox1.setValue(true);
95208                     checkbox2.setValue(true);
95209                     checkbox3.setValue(true);
95210                 }
95211             },
95212             {
95213                 text: 'Deselect All',
95214                 handler: function() {
95215                     var checkbox1 = Ext.getCmp('checkbox1'),
95216                         checkbox2 = Ext.getCmp('checkbox2'),
95217                         checkbox3 = Ext.getCmp('checkbox3');
95218     
95219                     checkbox1.setValue(false);
95220                     checkbox2.setValue(false);
95221                     checkbox3.setValue(false);
95222                 }
95223             }
95224         ],
95225         renderTo: Ext.getBody()
95226     });
95227
95228  * @constructor
95229  * Creates a new Checkbox
95230  * @param {Object} config Configuration options
95231  * @xtype checkboxfield
95232  * @docauthor Robert Dougan <rob@sencha.com>
95233  * @markdown
95234  */
95235 Ext.define('Ext.form.field.Checkbox', {
95236     extend: 'Ext.form.field.Base',
95237     alias: ['widget.checkboxfield', 'widget.checkbox'],
95238     alternateClassName: 'Ext.form.Checkbox',
95239     requires: ['Ext.XTemplate', 'Ext.form.CheckboxManager'],
95240
95241     fieldSubTpl: [
95242         '<tpl if="boxLabel && boxLabelAlign == \'before\'">',
95243             '<label class="{boxLabelCls} {boxLabelCls}-{boxLabelAlign}" for="{id}">{boxLabel}</label>',
95244         '</tpl>',
95245         // Creates not an actual checkbox, but a button which is given aria role="checkbox" and
95246         // styled with a custom checkbox image. This allows greater control and consistency in
95247         // styling, and using a button allows it to gain focus and handle keyboard nav properly.
95248         '<input type="button" id="{id}" ',
95249             '<tpl if="tabIdx">tabIndex="{tabIdx}" </tpl>',
95250             'class="{fieldCls} {typeCls}" autocomplete="off" hidefocus="true" />',
95251         '<tpl if="boxLabel && boxLabelAlign == \'after\'">',
95252             '<label class="{boxLabelCls} {boxLabelCls}-{boxLabelAlign}" for="{id}">{boxLabel}</label>',
95253         '</tpl>',
95254         {
95255             disableFormats: true,
95256             compiled: true
95257         }
95258     ],
95259
95260     isCheckbox: true,
95261
95262     /**
95263      * @cfg {String} focusCls The CSS class to use when the checkbox receives focus
95264      * (defaults to <tt>'x-form-cb-focus'</tt>)
95265      */
95266     focusCls: Ext.baseCSSPrefix + 'form-cb-focus',
95267
95268     /**
95269      * @cfg {String} fieldCls The default CSS class for the checkbox (defaults to <tt>'x-form-field'</tt>)
95270      */
95271
95272     /**
95273      * @cfg {String} fieldBodyCls
95274      * An extra CSS class to be applied to the body content element in addition to {@link #fieldBodyCls}.
95275      * Defaults to 'x-form-cb-wrap.
95276      */
95277     fieldBodyCls: Ext.baseCSSPrefix + 'form-cb-wrap',
95278
95279     /**
95280      * @cfg {Boolean} checked <tt>true</tt> if the checkbox should render initially checked (defaults to <tt>false</tt>)
95281      */
95282     checked: false,
95283
95284     /**
95285      * @cfg {String} checkedCls The CSS class added to the component's main element when it is in the checked state.
95286      */
95287     checkedCls: Ext.baseCSSPrefix + 'form-cb-checked',
95288
95289     /**
95290      * @cfg {String} boxLabel An optional text label that will appear next to the checkbox. Whether it appears before
95291      * or after the checkbox is determined by the {@link #boxLabelAlign} config (defaults to after).
95292      */
95293
95294     /**
95295      * @cfg {String} boxLabelCls The CSS class to be applied to the {@link #boxLabel} element
95296      */
95297     boxLabelCls: Ext.baseCSSPrefix + 'form-cb-label',
95298
95299     /**
95300      * @cfg {String} boxLabelAlign The position relative to the checkbox where the {@link #boxLabel} should
95301      * appear. Recognized values are <tt>'before'</tt> and <tt>'after'</tt>. Defaults to <tt>'after'</tt>.
95302      */
95303     boxLabelAlign: 'after',
95304
95305     /**
95306      * @cfg {String} inputValue The value that should go into the generated input element's value attribute and
95307      * should be used as the parameter value when submitting as part of a form. Defaults to <tt>"on"</tt>.
95308      */
95309     inputValue: 'on',
95310
95311     /**
95312      * @cfg {String} uncheckedValue If configured, this will be submitted as the checkbox's value during form
95313      * submit if the checkbox is unchecked. By default this is undefined, which results in nothing being
95314      * submitted for the checkbox field when the form is submitted (the default behavior of HTML checkboxes).
95315      */
95316
95317     /**
95318      * @cfg {Function} handler A function called when the {@link #checked} value changes (can be used instead of
95319      * handling the {@link #change change event}). The handler is passed the following parameters:
95320      * <div class="mdetail-params"><ul>
95321      * <li><b>checkbox</b> : Ext.form.field.Checkbox<div class="sub-desc">The Checkbox being toggled.</div></li>
95322      * <li><b>checked</b> : Boolean<div class="sub-desc">The new checked state of the checkbox.</div></li>
95323      * </ul></div>
95324      */
95325
95326     /**
95327      * @cfg {Object} scope An object to use as the scope ('this' reference) of the {@link #handler} function
95328      * (defaults to this Checkbox).
95329      */
95330
95331     // private overrides
95332     checkChangeEvents: [],
95333     inputType: 'checkbox',
95334     ariaRole: 'checkbox',
95335
95336     // private
95337     onRe: /^on$/i,
95338
95339     initComponent: function(){
95340         this.callParent(arguments);
95341         this.getManager().add(this);
95342     },
95343
95344     initValue: function() {
95345         var me = this,
95346             checked = !!me.checked;
95347
95348         /**
95349          * The original value of the field as configured in the {@link #checked} configuration, or
95350          * as loaded by the last form load operation if the form's {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
95351          * setting is <code>true</code>.
95352          * @type Mixed
95353          * @property originalValue
95354          */
95355         me.originalValue = me.lastValue = checked;
95356
95357         // Set the initial checked state
95358         me.setValue(checked);
95359     },
95360
95361     // private
95362     onRender : function(ct, position) {
95363         var me = this;
95364         Ext.applyIf(me.renderSelectors, {
95365             /**
95366              * @property boxLabelEl
95367              * @type Ext.core.Element
95368              * A reference to the label element created for the {@link #boxLabel}. Only present if the
95369              * component has been rendered and has a boxLabel configured.
95370              */
95371             boxLabelEl: 'label.' + me.boxLabelCls
95372         });
95373         Ext.applyIf(me.subTplData, {
95374             boxLabel: me.boxLabel,
95375             boxLabelCls: me.boxLabelCls,
95376             boxLabelAlign: me.boxLabelAlign
95377         });
95378
95379         me.callParent(arguments);
95380     },
95381
95382     initEvents: function() {
95383         var me = this;
95384         me.callParent();
95385         me.mon(me.inputEl, 'click', me.onBoxClick, me);
95386     },
95387
95388     /**
95389      * @private Handle click on the checkbox button
95390      */
95391     onBoxClick: function(e) {
95392         var me = this;
95393         if (!me.disabled && !me.readOnly) {
95394             this.setValue(!this.checked);
95395         }
95396     },
95397
95398     /**
95399      * Returns the checked state of the checkbox.
95400      * @return {Boolean} True if checked, else false
95401      */
95402     getRawValue: function() {
95403         return this.checked;
95404     },
95405
95406     /**
95407      * Returns the checked state of the checkbox.
95408      * @return {Boolean} True if checked, else false
95409      */
95410     getValue: function() {
95411         return this.checked;
95412     },
95413
95414     /**
95415      * Returns the submit value for the checkbox which can be used when submitting forms.
95416      * @return {Boolean/null} True if checked; otherwise either the {@link #uncheckedValue} or null.
95417      */
95418     getSubmitValue: function() {
95419         return this.checked ? this.inputValue : (this.uncheckedValue || null);
95420     },
95421
95422     getModelData: function() {
95423         return this.getSubmitData();
95424     },
95425
95426     /**
95427      * Sets the checked state of the checkbox.
95428      * @param {Boolean/String} value The following values will check the checkbox:
95429      * <code>true, 'true', '1', or 'on'</code>, as well as a String that matches the {@link #inputValue}.
95430      * Any other value will uncheck the checkbox.
95431      * @return {Boolean} the new checked state of the checkbox
95432      */
95433     setRawValue: function(value) {
95434         var me = this,
95435             inputEl = me.inputEl,
95436             inputValue = me.inputValue,
95437             checked = (value === true || value === 'true' || value === '1' ||
95438                       ((Ext.isString(value) && inputValue) ? value == inputValue : me.onRe.test(value)));
95439
95440         if (inputEl) {
95441             inputEl.dom.setAttribute('aria-checked', checked);
95442             me[checked ? 'addCls' : 'removeCls'](me.checkedCls);
95443         }
95444
95445         me.checked = me.rawValue = checked;
95446         return checked;
95447     },
95448
95449     /**
95450      * Sets the checked state of the checkbox, and invokes change detection.
95451      * @param {Boolean/String} checked The following values will check the checkbox:
95452      * <code>true, 'true', '1', or 'on'</code>, as well as a String that matches the {@link #inputValue}.
95453      * Any other value will uncheck the checkbox.
95454      * @return {Ext.form.field.Checkbox} this
95455      */
95456     setValue: function(checked) {
95457         var me = this;
95458
95459         // If an array of strings is passed, find all checkboxes in the group with the same name as this
95460         // one and check all those whose inputValue is in the array, unchecking all the others. This is to
95461         // facilitate setting values from Ext.form.Basic#setValues, but is not publicly documented as we
95462         // don't want users depending on this behavior.
95463         if (Ext.isArray(checked)) {
95464             me.getManager().getByName(me.name).each(function(cb) {
95465                 cb.setValue(Ext.Array.contains(checked, cb.inputValue));
95466             });
95467         } else {
95468             me.callParent(arguments);
95469         }
95470
95471         return me;
95472     },
95473
95474     // private
95475     valueToRaw: function(value) {
95476         // No extra conversion for checkboxes
95477         return value;
95478     },
95479
95480     /**
95481      * @private
95482      * Called when the checkbox's checked state changes. Invokes the {@link #handler} callback
95483      * function if specified.
95484      */
95485     onChange: function(newVal, oldVal) {
95486         var me = this,
95487             handler = me.handler;
95488         if (handler) {
95489             handler.call(me.scope || me, me, newVal);
95490         }
95491         me.callParent(arguments);
95492     },
95493
95494     // inherit docs
95495     getManager: function() {
95496         return Ext.form.CheckboxManager;
95497     },
95498
95499     onEnable: function() {
95500         var me = this,
95501             inputEl = me.inputEl;
95502         me.callParent();
95503         if (inputEl) {
95504             // Can still be disabled if the field is readOnly
95505             inputEl.dom.disabled = me.readOnly;
95506         }
95507     },
95508
95509     setReadOnly: function(readOnly) {
95510         var me = this,
95511             inputEl = me.inputEl;
95512         if (inputEl) {
95513             // Set the button to disabled when readonly
95514             inputEl.dom.disabled = readOnly || me.disabled;
95515         }
95516         me.readOnly = readOnly;
95517     },
95518
95519     /**
95520      * @protected Calculate and return the natural width of the bodyEl. It's possible that the initial
95521      * rendering will cause the boxLabel to wrap and give us a bad width, so we must prevent wrapping
95522      * while measuring.
95523      */
95524     getBodyNaturalWidth: function() {
95525         var me = this,
95526             bodyEl = me.bodyEl,
95527             ws = 'white-space',
95528             width;
95529         bodyEl.setStyle(ws, 'nowrap');
95530         width = bodyEl.getWidth();
95531         bodyEl.setStyle(ws, '');
95532         return width;
95533     }
95534
95535 });
95536
95537 /**
95538  * @private
95539  * @class Ext.layout.component.field.Trigger
95540  * @extends Ext.layout.component.field.Field
95541  * Layout class for {@link Ext.form.field.Trigger} fields. Adjusts the input field size to accommodate
95542  * the trigger button(s).
95543  * @private
95544  */
95545
95546 Ext.define('Ext.layout.component.field.Trigger', {
95547
95548     /* Begin Definitions */
95549
95550     alias: ['layout.triggerfield'],
95551
95552     extend: 'Ext.layout.component.field.Field',
95553
95554     /* End Definitions */
95555
95556     type: 'triggerfield',
95557
95558     sizeBodyContents: function(width, height) {
95559         var me = this,
95560             owner = me.owner,
95561             inputEl = owner.inputEl,
95562             triggerWrap = owner.triggerWrap,
95563             triggerWidth = owner.getTriggerWidth();
95564
95565         // If we or our ancestor is hidden, we can get a triggerWidth calculation
95566         // of 0.  We don't want to resize in this case.
95567         if (owner.hideTrigger || owner.readOnly || triggerWidth > 0) {
95568             // Decrease the field's width by the width of the triggers. Both the field and the triggerWrap
95569             // are floated left in CSS so they'll stack up side by side.
95570             me.setElementSize(inputEl, Ext.isNumber(width) ? width - triggerWidth : width);
95571     
95572             // Explicitly set the triggerWrap's width, to prevent wrapping
95573             triggerWrap.setWidth(triggerWidth);
95574         }
95575     }
95576 });
95577 /**
95578  * @class Ext.view.View
95579  * @extends Ext.view.AbstractView
95580  *
95581  * A mechanism for displaying data using custom layout templates and formatting. DataView uses an {@link Ext.XTemplate}
95582  * as its internal templating mechanism, and is bound to an {@link Ext.data.Store}
95583  * so that as the data in the store changes the view is automatically updated to reflect the changes.  The view also
95584  * provides built-in behavior for many common events that can occur for its contained items including click, doubleclick,
95585  * mouseover, mouseout, etc. as well as a built-in selection model. <b>In order to use these features, an {@link #itemSelector}
95586  * config must be provided for the DataView to determine what nodes it will be working with.</b>
95587  *
95588  * <p>The example below binds a DataView to a {@link Ext.data.Store} and renders it into an {@link Ext.panel.Panel}.</p>
95589  * {@img Ext.DataView/Ext.DataView.png Ext.DataView component}
95590  * <pre><code>
95591     Ext.regModel('Image', {
95592         Fields: [
95593             {name:'src', type:'string'},
95594             {name:'caption', type:'string'}
95595         ]
95596     });
95597     
95598     Ext.create('Ext.data.Store', {
95599         id:'imagesStore',
95600         model: 'Image',
95601         data: [
95602             {src:'http://www.sencha.com/img/20110215-feat-drawing.png', caption:'Drawing & Charts'},
95603             {src:'http://www.sencha.com/img/20110215-feat-data.png', caption:'Advanced Data'},
95604             {src:'http://www.sencha.com/img/20110215-feat-html5.png', caption:'Overhauled Theme'},
95605             {src:'http://www.sencha.com/img/20110215-feat-perf.png', caption:'Performance Tuned'}            
95606         ]
95607     });
95608     
95609     var imageTpl = new Ext.XTemplate(
95610         '<tpl for=".">',
95611             '<div style="thumb-wrap">',
95612               '<img src="{src}" />',
95613               '<br/><span>{caption}</span>',
95614             '</div>',
95615         '</tpl>'
95616     );
95617     
95618     Ext.create('Ext.DataView', {
95619         store: Ext.data.StoreManager.lookup('imagesStore'),
95620         tpl: imageTpl,
95621         itemSelector: 'div.thumb-wrap',
95622         emptyText: 'No images available',
95623         renderTo: Ext.getBody()
95624     });
95625  * </code></pre>
95626  * @xtype dataview
95627  */
95628 Ext.define('Ext.view.View', {
95629     extend: 'Ext.view.AbstractView',
95630     alternateClassName: 'Ext.view.View',
95631     alias: 'widget.dataview',
95632     
95633     inheritableStatics: {
95634         EventMap: {
95635             mousedown: 'MouseDown',
95636             mouseup: 'MouseUp',
95637             click: 'Click',
95638             dblclick: 'DblClick',
95639             contextmenu: 'ContextMenu',
95640             mouseover: 'MouseOver',
95641             mouseout: 'MouseOut',
95642             mouseenter: 'MouseEnter',
95643             mouseleave: 'MouseLeave',
95644             keydown: 'KeyDown'
95645         }
95646     },
95647     
95648     addCmpEvents: function() {
95649         this.addEvents(
95650             /**
95651              * @event beforeitemmousedown
95652              * Fires before the mousedown event on an item is processed. Returns false to cancel the default action.
95653              * @param {Ext.view.View} this
95654              * @param {Ext.data.Model} record The record that belongs to the item
95655              * @param {HTMLElement} item The item's element
95656              * @param {Number} index The item's index
95657              * @param {Ext.EventObject} e The raw event object
95658              */
95659             'beforeitemmousedown',
95660             /**
95661              * @event beforeitemmouseup
95662              * Fires before the mouseup event on an item is processed. Returns false to cancel the default action.
95663              * @param {Ext.view.View} this
95664              * @param {Ext.data.Model} record The record that belongs to the item
95665              * @param {HTMLElement} item The item's element
95666              * @param {Number} index The item's index
95667              * @param {Ext.EventObject} e The raw event object
95668              */
95669             'beforeitemmouseup',
95670             /**
95671              * @event beforeitemmouseenter
95672              * Fires before the mouseenter event on an item is processed. Returns false to cancel the default action.
95673              * @param {Ext.view.View} this
95674              * @param {Ext.data.Model} record The record that belongs to the item
95675              * @param {HTMLElement} item The item's element
95676              * @param {Number} index The item's index
95677              * @param {Ext.EventObject} e The raw event object
95678              */
95679             'beforeitemmouseenter',
95680             /**
95681              * @event beforeitemmouseleave
95682              * Fires before the mouseleave event on an item is processed. Returns false to cancel the default action.
95683              * @param {Ext.view.View} this
95684              * @param {Ext.data.Model} record The record that belongs to the item
95685              * @param {HTMLElement} item The item's element
95686              * @param {Number} index The item's index
95687              * @param {Ext.EventObject} e The raw event object
95688              */
95689             'beforeitemmouseleave',
95690             /**
95691              * @event beforeitemclick
95692              * Fires before the click event on an item is processed. Returns false to cancel the default action.
95693              * @param {Ext.view.View} this
95694              * @param {Ext.data.Model} record The record that belongs to the item
95695              * @param {HTMLElement} item The item's element
95696              * @param {Number} index The item's index
95697              * @param {Ext.EventObject} e The raw event object
95698              */
95699             'beforeitemclick',
95700             /**
95701              * @event beforeitemdblclick
95702              * Fires before the dblclick event on an item is processed. Returns false to cancel the default action.
95703              * @param {Ext.view.View} this
95704              * @param {Ext.data.Model} record The record that belongs to the item
95705              * @param {HTMLElement} item The item's element
95706              * @param {Number} index The item's index
95707              * @param {Ext.EventObject} e The raw event object
95708              */
95709             'beforeitemdblclick',
95710             /**
95711              * @event beforeitemcontextmenu
95712              * Fires before the contextmenu event on an item is processed. Returns false to cancel the default action.
95713              * @param {Ext.view.View} this
95714              * @param {Ext.data.Model} record The record that belongs to the item
95715              * @param {HTMLElement} item The item's element
95716              * @param {Number} index The item's index
95717              * @param {Ext.EventObject} e The raw event object
95718              */
95719             'beforeitemcontextmenu',
95720             /**
95721              * @event beforeitemkeydown
95722              * Fires before the keydown event on an item is processed. Returns false to cancel the default action.
95723              * @param {Ext.view.View} this
95724              * @param {Ext.data.Model} record The record that belongs to the item
95725              * @param {HTMLElement} item The item's element
95726              * @param {Number} index The item's index
95727              * @param {Ext.EventObject} e The raw event object. Use {@link Ext.EventObject#getKey getKey()} to retrieve the key that was pressed.
95728              */
95729             'beforeitemkeydown',
95730             /**
95731              * @event itemmousedown
95732              * Fires when there is a mouse down on an item
95733              * @param {Ext.view.View} this
95734              * @param {Ext.data.Model} record The record that belongs to the item
95735              * @param {HTMLElement} item The item's element
95736              * @param {Number} index The item's index
95737              * @param {Ext.EventObject} e The raw event object
95738              */
95739             'itemmousedown',
95740             /**
95741              * @event itemmouseup
95742              * Fires when there is a mouse up on an item
95743              * @param {Ext.view.View} this
95744              * @param {Ext.data.Model} record The record that belongs to the item
95745              * @param {HTMLElement} item The item's element
95746              * @param {Number} index The item's index
95747              * @param {Ext.EventObject} e The raw event object
95748              */
95749             'itemmouseup',
95750             /**
95751              * @event itemmouseenter
95752              * Fires when the mouse enters an item.
95753              * @param {Ext.view.View} this
95754              * @param {Ext.data.Model} record The record that belongs to the item
95755              * @param {HTMLElement} item The item's element
95756              * @param {Number} index The item's index
95757              * @param {Ext.EventObject} e The raw event object
95758              */
95759             'itemmouseenter',
95760             /**
95761              * @event itemmouseleave
95762              * Fires when the mouse leaves an item.
95763              * @param {Ext.view.View} this
95764              * @param {Ext.data.Model} record The record that belongs to the item
95765              * @param {HTMLElement} item The item's element
95766              * @param {Number} index The item's index
95767              * @param {Ext.EventObject} e The raw event object
95768              */
95769             'itemmouseleave',
95770             /**
95771              * @event itemclick
95772              * Fires when an item is clicked.
95773              * @param {Ext.view.View} this
95774              * @param {Ext.data.Model} record The record that belongs to the item
95775              * @param {HTMLElement} item The item's element
95776              * @param {Number} index The item's index
95777              * @param {Ext.EventObject} e The raw event object
95778              */
95779             'itemclick',
95780             /**
95781              * @event itemdblclick
95782              * Fires when an item is double clicked.
95783              * @param {Ext.view.View} this
95784              * @param {Ext.data.Model} record The record that belongs to the item
95785              * @param {HTMLElement} item The item's element
95786              * @param {Number} index The item's index
95787              * @param {Ext.EventObject} e The raw event object
95788              */
95789             'itemdblclick',
95790             /**
95791              * @event itemcontextmenu
95792              * Fires when an item is right clicked.
95793              * @param {Ext.view.View} this
95794              * @param {Ext.data.Model} record The record that belongs to the item
95795              * @param {HTMLElement} item The item's element
95796              * @param {Number} index The item's index
95797              * @param {Ext.EventObject} e The raw event object
95798              */
95799             'itemcontextmenu',
95800             /**
95801              * @event itemkeydown
95802              * Fires when a key is pressed while an item is currently selected.
95803              * @param {Ext.view.View} this
95804              * @param {Ext.data.Model} record The record that belongs to the item
95805              * @param {HTMLElement} item The item's element
95806              * @param {Number} index The item's index
95807              * @param {Ext.EventObject} e The raw event object. Use {@link Ext.EventObject#getKey getKey()} to retrieve the key that was pressed.
95808              */
95809             'itemkeydown',
95810             /**
95811              * @event beforecontainermousedown
95812              * Fires before the mousedown event on the container is processed. Returns false to cancel the default action.
95813              * @param {Ext.view.View} this
95814              * @param {Ext.EventObject} e The raw event object
95815              */
95816             'beforecontainermousedown',
95817             /**
95818              * @event beforecontainermouseup
95819              * Fires before the mouseup event on the container is processed. Returns false to cancel the default action.
95820              * @param {Ext.view.View} this
95821              * @param {Ext.EventObject} e The raw event object
95822              */
95823             'beforecontainermouseup',
95824             /**
95825              * @event beforecontainermouseover
95826              * Fires before the mouseover event on the container is processed. Returns false to cancel the default action.
95827              * @param {Ext.view.View} this
95828              * @param {Ext.EventObject} e The raw event object
95829              */
95830             'beforecontainermouseover',
95831             /**
95832              * @event beforecontainermouseout
95833              * Fires before the mouseout event on the container is processed. Returns false to cancel the default action.
95834              * @param {Ext.view.View} this
95835              * @param {Ext.EventObject} e The raw event object
95836              */
95837             'beforecontainermouseout',
95838             /**
95839              * @event beforecontainerclick
95840              * Fires before the click event on the container is processed. Returns false to cancel the default action.
95841              * @param {Ext.view.View} this
95842              * @param {Ext.EventObject} e The raw event object
95843              */
95844             'beforecontainerclick',
95845             /**
95846              * @event beforecontainerdblclick
95847              * Fires before the dblclick event on the container is processed. Returns false to cancel the default action.
95848              * @param {Ext.view.View} this
95849              * @param {Ext.EventObject} e The raw event object
95850              */
95851             'beforecontainerdblclick',
95852             /**
95853              * @event beforecontainercontextmenu
95854              * Fires before the contextmenu event on the container is processed. Returns false to cancel the default action.
95855              * @param {Ext.view.View} this
95856              * @param {Ext.EventObject} e The raw event object
95857              */
95858             'beforecontainercontextmenu',
95859             /**
95860              * @event beforecontainerkeydown
95861              * Fires before the keydown event on the container is processed. Returns false to cancel the default action.
95862              * @param {Ext.view.View} this
95863              * @param {Ext.EventObject} e The raw event object. Use {@link Ext.EventObject#getKey getKey()} to retrieve the key that was pressed.
95864              */
95865             'beforecontainerkeydown',
95866             /**
95867              * @event containermouseup
95868              * Fires when there is a mouse up on the container
95869              * @param {Ext.view.View} this
95870              * @param {Ext.EventObject} e The raw event object
95871              */
95872             'containermouseup',
95873             /**
95874              * @event containermouseover
95875              * Fires when you move the mouse over the container.
95876              * @param {Ext.view.View} this
95877              * @param {Ext.EventObject} e The raw event object
95878              */
95879             'containermouseover',
95880             /**
95881              * @event containermouseout
95882              * Fires when you move the mouse out of the container.
95883              * @param {Ext.view.View} this
95884              * @param {Ext.EventObject} e The raw event object
95885              */
95886             'containermouseout',
95887             /**
95888              * @event containerclick
95889              * Fires when the container is clicked.
95890              * @param {Ext.view.View} this
95891              * @param {Ext.EventObject} e The raw event object
95892              */
95893             'containerclick',
95894             /**
95895              * @event containerdblclick
95896              * Fires when the container is double clicked.
95897              * @param {Ext.view.View} this
95898              * @param {Ext.EventObject} e The raw event object
95899              */
95900             'containerdblclick',
95901             /**
95902              * @event containercontextmenu
95903              * Fires when the container is right clicked.
95904              * @param {Ext.view.View} this
95905              * @param {Ext.EventObject} e The raw event object
95906              */
95907             'containercontextmenu',
95908             /**
95909              * @event containerkeydown
95910              * Fires when a key is pressed while the container is focused, and no item is currently selected.
95911              * @param {Ext.view.View} this
95912              * @param {Ext.EventObject} e The raw event object. Use {@link Ext.EventObject#getKey getKey()} to retrieve the key that was pressed.
95913              */
95914             'containerkeydown',
95915             
95916             /**
95917              * @event selectionchange
95918              * Fires when the selected nodes change. Relayed event from the underlying selection model.
95919              * @param {Ext.view.View} this
95920              * @param {Array} selections Array of the selected nodes
95921              */
95922             'selectionchange',
95923             /**
95924              * @event beforeselect
95925              * Fires before a selection is made. If any handlers return false, the selection is cancelled.
95926              * @param {Ext.view.View} this
95927              * @param {HTMLElement} node The node to be selected
95928              * @param {Array} selections Array of currently selected nodes
95929              */
95930             'beforeselect'
95931         );
95932     },
95933     // private
95934     afterRender: function(){
95935         var me = this, 
95936             listeners;
95937         
95938         me.callParent();
95939
95940         listeners = {
95941             scope: me,
95942             click: me.handleEvent,
95943             mousedown: me.handleEvent,
95944             mouseup: me.handleEvent,
95945             dblclick: me.handleEvent,
95946             contextmenu: me.handleEvent,
95947             mouseover: me.handleEvent,
95948             mouseout: me.handleEvent,
95949             keydown: me.handleEvent
95950         };
95951         
95952         me.mon(me.getTargetEl(), listeners);
95953         
95954         if (me.store) {
95955             me.bindStore(me.store, true);
95956         }
95957     },
95958     
95959     handleEvent: function(e) {
95960         if (this.processUIEvent(e) !== false) {
95961             this.processSpecialEvent(e);
95962         }
95963     },
95964     
95965     // Private template method
95966     processItemEvent: Ext.emptyFn,
95967     processContainerEvent: Ext.emptyFn,
95968     processSpecialEvent: Ext.emptyFn,
95969     
95970     processUIEvent: function(e, type) {
95971         type = type || e.type;
95972         var me = this,
95973             item = e.getTarget(me.getItemSelector(), me.getTargetEl()),
95974             map = this.statics().EventMap,
95975             index, record;
95976         
95977         if (!item) {
95978             // There is this weird bug when you hover over the border of a cell it is saying
95979             // the target is the table.
95980             // BrowserBug: IE6 & 7. If me.mouseOverItem has been removed and is no longer
95981             // in the DOM then accessing .offsetParent will throw an "Unspecified error." exception.
95982             // typeof'ng and checking to make sure the offsetParent is an object will NOT throw
95983             // this hard exception.
95984             if (type == 'mouseover' && me.mouseOverItem && typeof me.mouseOverItem.offsetParent === "object" && Ext.fly(me.mouseOverItem).getRegion().contains(e.getPoint())) {
95985                 item = me.mouseOverItem;
95986             }
95987             
95988             // Try to get the selected item to handle the keydown event, otherwise we'll just fire a container keydown event
95989             if (type == 'keydown') {
95990                 record = me.getSelectionModel().getLastSelected();
95991                 if (record) {
95992                     item = me.getNode(record);
95993                 }
95994             }
95995         }
95996         
95997         if (item) {
95998             index = me.indexOf(item);
95999             if (!record) {
96000                 record = me.getRecord(item);
96001             }
96002             
96003             if (me.processItemEvent(type, record, item, index, e) === false) {
96004                 return false;
96005             }
96006             
96007             type = me.isNewItemEvent(type, item, e);
96008             if (type === false) {
96009                 return false;
96010             }
96011             
96012             if (
96013                 (me['onBeforeItem' + map[type]](record, item, index, e) === false) ||
96014                 (me.fireEvent('beforeitem' + type, me, record, item, index, e) === false) ||
96015                 (me['onItem' + map[type]](record, item, index, e) === false)
96016             ) { 
96017                 return false;
96018             }
96019             
96020             me.fireEvent('item' + type, me, record, item, index, e);
96021         } 
96022         else {
96023             if (
96024                 (me.processContainerEvent(type, e) === false) ||
96025                 (me['onBeforeContainer' + map[type]](e) === false) ||
96026                 (me.fireEvent('beforecontainer' + type, me, e) === false) ||
96027                 (me['onContainer' + map[type]](e) === false)
96028             ) {
96029                 return false;
96030             }
96031             
96032             me.fireEvent('container' + type, me, e);
96033         }
96034         
96035         return true;
96036     },
96037     
96038     isNewItemEvent: function(type, item, e) {
96039         var me = this,
96040             overItem = me.mouseOverItem,
96041             contains,
96042             isItem;
96043             
96044         switch (type) {
96045             case 'mouseover':
96046                 if (item === overItem) {
96047                     return false;
96048                 }
96049                 me.mouseOverItem = item;
96050                 return 'mouseenter';
96051             break;
96052             
96053             case 'mouseout':
96054                /*
96055                 * Need an extra check here to see if it's the parent element. See the
96056                 * comment re: the browser bug at the start of processUIEvent
96057                 */
96058                 if (overItem && typeof overItem.offsetParent === "object") {
96059                     contains = Ext.fly(me.mouseOverItem).getRegion().contains(e.getPoint());
96060                     isItem = Ext.fly(e.getTarget()).hasCls(me.itemSelector);
96061                     if (contains && isItem) {
96062                         return false;
96063                     }
96064                 }
96065                 me.mouseOverItem = null;
96066                 return 'mouseleave';
96067             break;
96068         }
96069         return type;
96070     },
96071     
96072     // private
96073     onItemMouseEnter: function(record, item, index, e) {
96074         if (this.trackOver) {
96075             this.highlightItem(item);
96076         }
96077     },
96078
96079     // private
96080     onItemMouseLeave : function(record, item, index, e) {
96081         if (this.trackOver) {
96082             this.clearHighlight();
96083         }
96084     },
96085
96086     // @private, template methods
96087     onItemMouseDown: Ext.emptyFn,
96088     onItemMouseUp: Ext.emptyFn,
96089     onItemClick: Ext.emptyFn,
96090     onItemDblClick: Ext.emptyFn,
96091     onItemContextMenu: Ext.emptyFn,
96092     onItemKeyDown: Ext.emptyFn,
96093     onBeforeItemMouseDown: Ext.emptyFn,
96094     onBeforeItemMouseUp: Ext.emptyFn,
96095     onBeforeItemMouseEnter: Ext.emptyFn,
96096     onBeforeItemMouseLeave: Ext.emptyFn,
96097     onBeforeItemClick: Ext.emptyFn,
96098     onBeforeItemDblClick: Ext.emptyFn,
96099     onBeforeItemContextMenu: Ext.emptyFn,
96100     onBeforeItemKeyDown: Ext.emptyFn,
96101     
96102     // @private, template methods
96103     onContainerMouseDown: Ext.emptyFn,
96104     onContainerMouseUp: Ext.emptyFn,
96105     onContainerMouseOver: Ext.emptyFn,
96106     onContainerMouseOut: Ext.emptyFn,
96107     onContainerClick: Ext.emptyFn,
96108     onContainerDblClick: Ext.emptyFn,
96109     onContainerContextMenu: Ext.emptyFn,
96110     onContainerKeyDown: Ext.emptyFn,
96111     onBeforeContainerMouseDown: Ext.emptyFn,
96112     onBeforeContainerMouseUp: Ext.emptyFn,
96113     onBeforeContainerMouseOver: Ext.emptyFn,
96114     onBeforeContainerMouseOut: Ext.emptyFn,
96115     onBeforeContainerClick: Ext.emptyFn,
96116     onBeforeContainerDblClick: Ext.emptyFn,
96117     onBeforeContainerContextMenu: Ext.emptyFn,
96118     onBeforeContainerKeyDown: Ext.emptyFn,
96119     
96120     /**
96121      * Highlight a given item in the DataView. This is called by the mouseover handler if {@link #overItemCls}
96122      * and {@link #trackOver} are configured, but can also be called manually by other code, for instance to
96123      * handle stepping through the list via keyboard navigation.
96124      * @param {HTMLElement} item The item to highlight
96125      */
96126     highlightItem: function(item) {
96127         var me = this;
96128         me.clearHighlight();
96129         me.highlightedItem = item;
96130         Ext.fly(item).addCls(me.overItemCls);
96131     },
96132
96133     /**
96134      * Un-highlight the currently highlighted item, if any.
96135      */
96136     clearHighlight: function() {
96137         var me = this,
96138             highlighted = me.highlightedItem;
96139             
96140         if (highlighted) {
96141             Ext.fly(highlighted).removeCls(me.overItemCls);
96142             delete me.highlightedItem;
96143         }
96144     },
96145
96146     refresh: function() {
96147         this.clearHighlight();
96148         this.callParent(arguments);
96149     }
96150 });
96151 /**
96152  * Component layout for {@link Ext.view.BoundList}. Handles constraining the height to the configured maxHeight.
96153  * @class Ext.layout.component.BoundList
96154  * @extends Ext.layout.component.Component
96155  * @private
96156  */
96157 Ext.define('Ext.layout.component.BoundList', {
96158     extend: 'Ext.layout.component.Component',
96159     alias: 'layout.boundlist',
96160
96161     type: 'component',
96162
96163     beforeLayout: function() {
96164         return this.callParent(arguments) || this.owner.refreshed > 0;
96165     },
96166
96167     onLayout : function(width, height) {
96168         var me = this,
96169             owner = me.owner,
96170             floating = owner.floating,
96171             el = owner.el,
96172             xy = el.getXY(),
96173             isNumber = Ext.isNumber,
96174             minWidth, maxWidth, minHeight, maxHeight,
96175             naturalWidth, naturalHeight, constrainedWidth, constrainedHeight, undef;
96176
96177         if (floating) {
96178             // Position offscreen so the natural width is not affected by the viewport's right edge
96179             el.setXY([-9999,-9999]);
96180         }
96181
96182         // Calculate initial layout
96183         me.setTargetSize(width, height);
96184
96185         // Handle min/maxWidth for auto-width
96186         if (!isNumber(width)) {
96187             minWidth = owner.minWidth;
96188             maxWidth = owner.maxWidth;
96189             if (isNumber(minWidth) || isNumber(maxWidth)) {
96190                 naturalWidth = el.getWidth();
96191                 if (naturalWidth < minWidth) {
96192                     constrainedWidth = minWidth;
96193                 }
96194                 else if (naturalWidth > maxWidth) {
96195                     constrainedWidth = maxWidth;
96196                 }
96197                 if (constrainedWidth) {
96198                     me.setTargetSize(constrainedWidth);
96199                 }
96200             }
96201         }
96202         // Handle min/maxHeight for auto-height
96203         if (!isNumber(height)) {
96204             minHeight = owner.minHeight;
96205             maxHeight = owner.maxHeight;
96206             if (isNumber(minHeight) || isNumber(maxHeight)) {
96207                 naturalHeight = el.getHeight();
96208                 if (naturalHeight < minHeight) {
96209                     constrainedHeight = minHeight;
96210                 }
96211                 else if (naturalHeight > maxHeight) {
96212                     constrainedHeight = maxHeight;
96213                 }
96214                 if (constrainedHeight) {
96215                     me.setTargetSize(undef, constrainedHeight);
96216                 }
96217             }
96218         }
96219
96220         if (floating) {
96221             // Restore position
96222             el.setXY(xy);
96223         }
96224     },
96225
96226     afterLayout: function() {
96227         var me = this,
96228             toolbar = me.owner.pagingToolbar;
96229         me.callParent();
96230         if (toolbar) {
96231             toolbar.doComponentLayout();
96232         }
96233     },
96234
96235     setTargetSize : function(width, height) {
96236         var me = this,
96237             owner = me.owner,
96238             listHeight = null,
96239             toolbar;
96240
96241         // Size the listEl
96242         if (Ext.isNumber(height)) {
96243             listHeight = height - owner.el.getFrameWidth('tb');
96244             toolbar = owner.pagingToolbar;
96245             if (toolbar) {
96246                 listHeight -= toolbar.getHeight();
96247             }
96248         }
96249         me.setElementSize(owner.listEl, null, listHeight);
96250
96251         me.callParent(arguments);
96252     }
96253
96254 });
96255
96256 /**
96257  * @class Ext.toolbar.TextItem
96258  * @extends Ext.toolbar.Item
96259  *
96260  * A simple class that renders text directly into a toolbar.
96261  *
96262  * ## Example usage
96263  *
96264  * {@img Ext.toolbar.TextItem/Ext.toolbar.TextItem.png TextItem component}
96265  *
96266  *     Ext.create('Ext.panel.Panel', {
96267  *         title: 'Panel with TextItem',
96268  *         width: 300,
96269  *         height: 200,
96270  *         tbar: [
96271  *             {xtype: 'tbtext', text: 'Sample TextItem'}
96272  *         ],
96273  *         renderTo: Ext.getBody()
96274  *     });
96275  *
96276  * @constructor
96277  * Creates a new TextItem
96278  * @param {Object} text A text string, or a config object containing a <tt>text</tt> property
96279  * @xtype tbtext
96280  */
96281 Ext.define('Ext.toolbar.TextItem', {
96282     extend: 'Ext.toolbar.Item',
96283     requires: ['Ext.XTemplate'],
96284     alias: 'widget.tbtext',
96285     alternateClassName: 'Ext.Toolbar.TextItem',
96286     
96287     /**
96288      * @cfg {String} text The text to be used as innerHTML (html tags are accepted)
96289      */
96290     text: '',
96291     
96292     renderTpl: '{text}',
96293     //
96294     baseCls: Ext.baseCSSPrefix + 'toolbar-text',
96295     
96296     onRender : function() {
96297         Ext.apply(this.renderData, {
96298             text: this.text
96299         });
96300         this.callParent(arguments);
96301     },
96302
96303     /**
96304      * Updates this item's text, setting the text to be used as innerHTML.
96305      * @param {String} t The text to display (html accepted).
96306      */
96307     setText : function(t) {
96308         if (this.rendered) {
96309             this.el.update(t);
96310             this.ownerCt.doLayout(); // In case an empty text item (centered at zero height) receives new text.
96311         } else {
96312             this.text = t;
96313         }
96314     }
96315 });
96316 /**
96317  * @class Ext.form.field.Trigger
96318  * @extends Ext.form.field.Text
96319  * <p>Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
96320  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
96321  * overriding {@link #onTriggerClick}. You can create a Trigger field directly, as it renders exactly like a combobox
96322  * for which you can provide a custom implementation. 
96323  * {@img Ext.form.field.Trigger/Ext.form.field.Trigger.png Ext.form.field.Trigger component}
96324  * For example:</p>
96325  * <pre><code>
96326     Ext.define('Ext.ux.CustomTrigger', {
96327         extend: 'Ext.form.field.Trigger',
96328         alias: 'widget.customtrigger',
96329         
96330         // override onTriggerClick
96331         onTriggerClick: function() {
96332             Ext.Msg.alert('Status', 'You clicked my trigger!');
96333         }
96334     });
96335     
96336     Ext.create('Ext.form.FormPanel', {
96337         title: 'Form with TriggerField',
96338         bodyPadding: 5,
96339         width: 350,
96340         renderTo: Ext.getBody(),
96341         items:[{
96342             xtype: 'customtrigger',
96343             fieldLabel: 'Sample Trigger',
96344             emptyText: 'click the trigger',
96345         }]
96346     });
96347 </code></pre>
96348  *
96349  * <p>However, in general you will most likely want to use Trigger as the base class for a reusable component.
96350  * {@link Ext.form.field.Date} and {@link Ext.form.field.ComboBox} are perfect examples of this.</p>
96351  *
96352  * @constructor
96353  * Create a new Trigger field.
96354  * @param {Object} config Configuration options (valid {@Ext.form.field.Text} config options will also be applied
96355  * to the base Text field)
96356  * @xtype triggerfield
96357  */
96358 Ext.define('Ext.form.field.Trigger', {
96359     extend:'Ext.form.field.Text',
96360     alias: ['widget.triggerfield', 'widget.trigger'],
96361     requires: ['Ext.core.DomHelper', 'Ext.util.ClickRepeater', 'Ext.layout.component.field.Trigger'],
96362     alternateClassName: ['Ext.form.TriggerField', 'Ext.form.TwinTriggerField', 'Ext.form.Trigger'],
96363
96364     fieldSubTpl: [
96365         '<input id="{id}" type="{type}" ',
96366             '<tpl if="name">name="{name}" </tpl>',
96367             '<tpl if="size">size="{size}" </tpl>',
96368             '<tpl if="tabIdx">tabIndex="{tabIdx}" </tpl>',
96369             'class="{fieldCls} {typeCls}" autocomplete="off" />',
96370         '<div class="{triggerWrapCls}" role="presentation">',
96371             '{triggerEl}',
96372             '<div class="{clearCls}" role="presentation"></div>',
96373         '</div>',
96374         {
96375             compiled: true,
96376             disableFormats: true
96377         }
96378     ],
96379
96380     /**
96381      * @cfg {String} triggerCls
96382      * An additional CSS class used to style the trigger button.  The trigger will always get the
96383      * {@link #triggerBaseCls} by default and <tt>triggerCls</tt> will be <b>appended</b> if specified.
96384      * Defaults to undefined.
96385      */
96386
96387     /**
96388      * @cfg {String} triggerBaseCls
96389      * The base CSS class that is always added to the trigger button. The {@link #triggerCls} will be
96390      * appended in addition to this class.
96391      */
96392     triggerBaseCls: Ext.baseCSSPrefix + 'form-trigger',
96393
96394     /**
96395      * @cfg {String} triggerWrapCls
96396      * The CSS class that is added to the div wrapping the trigger button(s).
96397      */
96398     triggerWrapCls: Ext.baseCSSPrefix + 'form-trigger-wrap',
96399
96400     /**
96401      * @cfg {Boolean} hideTrigger <tt>true</tt> to hide the trigger element and display only the base
96402      * text field (defaults to <tt>false</tt>)
96403      */
96404     hideTrigger: false,
96405
96406     /**
96407      * @cfg {Boolean} editable <tt>false</tt> to prevent the user from typing text directly into the field;
96408      * the field can only have its value set via an action invoked by the trigger. (defaults to <tt>true</tt>).
96409      */
96410     editable: true,
96411
96412     /**
96413      * @cfg {Boolean} readOnly <tt>true</tt> to prevent the user from changing the field, and
96414      * hides the trigger.  Supercedes the editable and hideTrigger options if the value is true.
96415      * (defaults to <tt>false</tt>)
96416      */
96417     readOnly: false,
96418
96419     /**
96420      * @cfg {Boolean} selectOnFocus <tt>true</tt> to select any existing text in the field immediately on focus.
96421      * Only applies when <tt>{@link #editable editable} = true</tt> (defaults to <tt>false</tt>).
96422      */
96423
96424     /**
96425      * @cfg {Boolean} repeatTriggerClick <tt>true</tt> to attach a {@link Ext.util.ClickRepeater click repeater}
96426      * to the trigger. Defaults to <tt>false</tt>.
96427      */
96428     repeatTriggerClick: false,
96429
96430
96431     /**
96432      * @hide
96433      * @method autoSize
96434      */
96435     autoSize: Ext.emptyFn,
96436     // private
96437     monitorTab: true,
96438     // private
96439     mimicing: false,
96440     // private
96441     triggerIndexRe: /trigger-index-(\d+)/,
96442
96443     componentLayout: 'triggerfield',
96444
96445     initComponent: function() {
96446         this.wrapFocusCls = this.triggerWrapCls + '-focus';
96447         this.callParent(arguments);
96448     },
96449
96450     // private
96451     onRender: function(ct, position) {
96452         var me = this,
96453             triggerCls,
96454             triggerBaseCls = me.triggerBaseCls,
96455             triggerWrapCls = me.triggerWrapCls,
96456             triggerConfigs = [],
96457             i;
96458
96459         // triggerCls is a synonym for trigger1Cls, so copy it.
96460         // TODO this trigger<n>Cls API design doesn't feel clean, especially where it butts up against the
96461         // single triggerCls config. Should rethink this, perhaps something more structured like a list of
96462         // trigger config objects that hold cls, handler, etc.
96463         if (!me.trigger1Cls) {
96464             me.trigger1Cls = me.triggerCls;
96465         }
96466
96467         // Create as many trigger elements as we have trigger<n>Cls configs, but always at least one
96468         for (i = 0; (triggerCls = me['trigger' + (i + 1) + 'Cls']) || i < 1; i++) {
96469             triggerConfigs.push({
96470                 cls: [Ext.baseCSSPrefix + 'trigger-index-' + i, triggerBaseCls, triggerCls].join(' '),
96471                 role: 'button'
96472             });
96473         }
96474         triggerConfigs[i - 1].cls += ' ' + triggerBaseCls + '-last';
96475
96476         Ext.applyIf(me.renderSelectors, {
96477             /**
96478              * @property triggerWrap
96479              * @type Ext.core.Element
96480              * A reference to the div element wrapping the trigger button(s). Only set after the field has been rendered.
96481              */
96482             triggerWrap: '.' + triggerWrapCls
96483         });
96484         Ext.applyIf(me.subTplData, {
96485             triggerWrapCls: triggerWrapCls,
96486             triggerEl: Ext.core.DomHelper.markup(triggerConfigs),
96487             clearCls: me.clearCls
96488         });
96489
96490         me.callParent(arguments);
96491
96492         /**
96493          * @property triggerEl
96494          * @type Ext.CompositeElement
96495          * A composite of all the trigger button elements. Only set after the field has been rendered.
96496          */
96497         me.triggerEl = Ext.select('.' + triggerBaseCls, true, me.triggerWrap.dom);
96498
96499         me.doc = Ext.isIE ? Ext.getBody() : Ext.getDoc();
96500         me.initTrigger();
96501     },
96502
96503     onEnable: function() {
96504         this.callParent();
96505         this.triggerWrap.unmask();
96506     },
96507     
96508     onDisable: function() {
96509         this.callParent();
96510         this.triggerWrap.mask();
96511     },
96512     
96513     afterRender: function() {
96514         this.callParent();
96515         this.updateEditState();
96516     },
96517
96518     updateEditState: function() {
96519         var me = this,
96520             inputEl = me.inputEl,
96521             triggerWrap = me.triggerWrap,
96522             noeditCls = Ext.baseCSSPrefix + 'trigger-noedit',
96523             displayed,
96524             readOnly;
96525
96526         if (me.rendered) {
96527             if (me.readOnly) {
96528                 inputEl.addCls(noeditCls);
96529                 readOnly = true;
96530                 displayed = false;
96531             } else {
96532                 if (me.editable) {
96533                     inputEl.removeCls(noeditCls);
96534                     readOnly = false;
96535                 } else {
96536                     inputEl.addCls(noeditCls);
96537                     readOnly = true;
96538                 }
96539                 displayed = !me.hideTrigger;
96540             }
96541
96542             triggerWrap.setDisplayed(displayed);
96543             inputEl.dom.readOnly = readOnly;
96544             me.doComponentLayout();
96545         }
96546     },
96547
96548     /**
96549      * Get the total width of the trigger button area. Only useful after the field has been rendered.
96550      * @return {Number} The trigger width
96551      */
96552     getTriggerWidth: function() {
96553         var me = this,
96554             triggerWrap = me.triggerWrap,
96555             totalTriggerWidth = 0;
96556         if (triggerWrap && !me.hideTrigger && !me.readOnly) {
96557             me.triggerEl.each(function(trigger) {
96558                 totalTriggerWidth += trigger.getWidth();
96559             });
96560             totalTriggerWidth += me.triggerWrap.getFrameWidth('lr');
96561         }
96562         return totalTriggerWidth;
96563     },
96564
96565     setHideTrigger: function(hideTrigger) {
96566         if (hideTrigger != this.hideTrigger) {
96567             this.hideTrigger = hideTrigger;
96568             this.updateEditState();
96569         }
96570     },
96571
96572     /**
96573      * @param {Boolean} editable True to allow the user to directly edit the field text
96574      * Allow or prevent the user from directly editing the field text.  If false is passed,
96575      * the user will only be able to modify the field using the trigger.  Will also add
96576      * a click event to the text field which will call the trigger. This method
96577      * is the runtime equivalent of setting the 'editable' config option at config time.
96578      */
96579     setEditable: function(editable) {
96580         if (editable != this.editable) {
96581             this.editable = editable;
96582             this.updateEditState();
96583         }
96584     },
96585
96586     /**
96587      * @param {Boolean} readOnly True to prevent the user changing the field and explicitly
96588      * hide the trigger.
96589      * Setting this to true will superceed settings editable and hideTrigger.
96590      * Setting this to false will defer back to editable and hideTrigger. This method
96591      * is the runtime equivalent of setting the 'readOnly' config option at config time.
96592      */
96593     setReadOnly: function(readOnly) {
96594         if (readOnly != this.readOnly) {
96595             this.readOnly = readOnly;
96596             this.updateEditState();
96597         }
96598     },
96599
96600     // private
96601     initTrigger: function() {
96602         var me = this,
96603             triggerWrap = me.triggerWrap,
96604             triggerEl = me.triggerEl;
96605
96606         if (me.repeatTriggerClick) {
96607             me.triggerRepeater = Ext.create('Ext.util.ClickRepeater', triggerWrap, {
96608                 preventDefault: true,
96609                 handler: function(cr, e) {
96610                     me.onTriggerWrapClick(e);
96611                 }
96612             });
96613         } else {
96614             me.mon(me.triggerWrap, 'click', me.onTriggerWrapClick, me);
96615         }
96616
96617         triggerEl.addClsOnOver(me.triggerBaseCls + '-over');
96618         triggerEl.each(function(el, c, i) {
96619             el.addClsOnOver(me['trigger' + (i + 1) + 'Cls'] + '-over');
96620         });
96621         triggerEl.addClsOnClick(me.triggerBaseCls + '-click');
96622         triggerEl.each(function(el, c, i) {
96623             el.addClsOnClick(me['trigger' + (i + 1) + 'Cls'] + '-click');
96624         });
96625     },
96626
96627     // private
96628     onDestroy: function() {
96629         var me = this;
96630         Ext.destroyMembers(me, 'triggerRepeater', 'triggerWrap', 'triggerEl');
96631         delete me.doc;
96632         me.callParent();
96633     },
96634
96635     // private
96636     onFocus: function() {
96637         var me = this;
96638         this.callParent();
96639         if (!me.mimicing) {
96640             me.bodyEl.addCls(me.wrapFocusCls);
96641             me.mimicing = true;
96642             me.mon(me.doc, 'mousedown', me.mimicBlur, me, {
96643                 delay: 10
96644             });
96645             if (me.monitorTab) {
96646                 me.on('specialkey', me.checkTab, me);
96647             }
96648         }
96649     },
96650
96651     // private
96652     checkTab: function(me, e) {
96653         if (!this.ignoreMonitorTab && e.getKey() == e.TAB) {
96654             this.triggerBlur();
96655         }
96656     },
96657
96658     // private
96659     onBlur: Ext.emptyFn,
96660
96661     // private
96662     mimicBlur: function(e) {
96663         if (!this.isDestroyed && !this.bodyEl.contains(e.target) && this.validateBlur(e)) {
96664             this.triggerBlur();
96665         }
96666     },
96667
96668     // private
96669     triggerBlur: function() {
96670         var me = this;
96671         me.mimicing = false;
96672         me.mun(me.doc, 'mousedown', me.mimicBlur, me);
96673         if (me.monitorTab && me.inputEl) {
96674             me.un('specialkey', me.checkTab, me);
96675         }
96676         Ext.form.field.Trigger.superclass.onBlur.call(me);
96677         if (me.bodyEl) {
96678             me.bodyEl.removeCls(me.wrapFocusCls);
96679         }
96680     },
96681
96682     beforeBlur: Ext.emptyFn,
96683
96684     // private
96685     // This should be overridden by any subclass that needs to check whether or not the field can be blurred.
96686     validateBlur: function(e) {
96687         return true;
96688     },
96689
96690     // private
96691     // process clicks upon triggers.
96692     // determine which trigger index, and dispatch to the appropriate click handler
96693     onTriggerWrapClick: function(e) {
96694         var me = this,
96695             t = e && e.getTarget('.' + Ext.baseCSSPrefix + 'form-trigger', null),
96696             match = t && t.className.match(me.triggerIndexRe),
96697             idx,
96698             triggerClickMethod;
96699
96700         if (match && !me.readOnly) {
96701             idx = parseInt(match[1], 10);
96702             triggerClickMethod = me['onTrigger' + (idx + 1) + 'Click'] || me.onTriggerClick;
96703             if (triggerClickMethod) {
96704                 triggerClickMethod.call(me, e);
96705             }
96706         }
96707     },
96708
96709     /**
96710      * The function that should handle the trigger's click event.  This method does nothing by default
96711      * until overridden by an implementing function.  See Ext.form.field.ComboBox and Ext.form.field.Date for
96712      * sample implementations.
96713      * @method
96714      * @param {Ext.EventObject} e
96715      */
96716     onTriggerClick: Ext.emptyFn
96717
96718     /**
96719      * @cfg {Boolean} grow @hide
96720      */
96721     /**
96722      * @cfg {Number} growMin @hide
96723      */
96724     /**
96725      * @cfg {Number} growMax @hide
96726      */
96727 });
96728
96729 /**
96730  * @class Ext.form.field.Picker
96731  * @extends Ext.form.field.Trigger
96732  * <p>An abstract class for fields that have a single trigger which opens a "picker" popup below
96733  * the field, e.g. a combobox menu list or a date picker. It provides a base implementation for
96734  * toggling the picker's visibility when the trigger is clicked, as well as keyboard navigation
96735  * and some basic events. Sizing and alignment of the picker can be controlled via the {@link #matchFieldWidth}
96736  * and {@link #pickerAlign}/{@link #pickerOffset} config properties respectively.</p>
96737  * <p>You would not normally use this class directly, but instead use it as the parent class for
96738  * a specific picker field implementation. Subclasses must implement the {@link #createPicker} method
96739  * to create a picker component appropriate for the field.</p>
96740  *
96741  * @xtype pickerfield
96742  * @constructor
96743  * Create a new picker field
96744  * @param {Object} config
96745  */
96746 Ext.define('Ext.form.field.Picker', {
96747     extend: 'Ext.form.field.Trigger',
96748     alias: 'widget.pickerfield',
96749     alternateClassName: 'Ext.form.Picker',
96750     requires: ['Ext.util.KeyNav'],
96751
96752     /**
96753      * @cfg {Boolean} matchFieldWidth
96754      * Whether the picker dropdown's width should be explicitly set to match the width of the field.
96755      * Defaults to <tt>true</tt>.
96756      */
96757     matchFieldWidth: true,
96758
96759     /**
96760      * @cfg {String} pickerAlign
96761      * The {@link Ext.core.Element#alignTo alignment position} with which to align the picker. Defaults
96762      * to <tt>"tl-bl?"</tt>
96763      */
96764     pickerAlign: 'tl-bl?',
96765
96766     /**
96767      * @cfg {Array} pickerOffset
96768      * An offset [x,y] to use in addition to the {@link #pickerAlign} when positioning the picker.
96769      * Defaults to undefined.
96770      */
96771
96772     /**
96773      * @cfg {String} openCls
96774      * A class to be added to the field's {@link #bodyEl} element when the picker is opened. Defaults
96775      * to 'x-pickerfield-open'.
96776      */
96777     openCls: Ext.baseCSSPrefix + 'pickerfield-open',
96778
96779     /**
96780      * @property isExpanded
96781      * @type Boolean
96782      * True if the picker is currently expanded, false if not.
96783      */
96784
96785     /**
96786      * @cfg {Boolean} editable <tt>false</tt> to prevent the user from typing text directly into the field;
96787      * the field can only have its value set via selecting a value from the picker. In this state, the picker
96788      * can also be opened by clicking directly on the input field itself.
96789      * (defaults to <tt>true</tt>).
96790      */
96791     editable: true,
96792
96793
96794     initComponent: function() {
96795         this.callParent();
96796
96797         // Custom events
96798         this.addEvents(
96799             /**
96800              * @event expand
96801              * Fires when the field's picker is expanded.
96802              * @param {Ext.form.field.Picker} field This field instance
96803              */
96804             'expand',
96805             /**
96806              * @event collapse
96807              * Fires when the field's picker is collapsed.
96808              * @param {Ext.form.field.Picker} field This field instance
96809              */
96810             'collapse',
96811             /**
96812              * @event select
96813              * Fires when a value is selected via the picker.
96814              * @param {Ext.form.field.Picker} field This field instance
96815              * @param {Mixed} value The value that was selected. The exact type of this value is dependent on
96816              * the individual field and picker implementations.
96817              */
96818             'select'
96819         );
96820     },
96821
96822
96823     initEvents: function() {
96824         var me = this;
96825         me.callParent();
96826
96827         // Add handlers for keys to expand/collapse the picker
96828         me.keyNav = Ext.create('Ext.util.KeyNav', me.inputEl, {
96829             down: function() {
96830                 if (!me.isExpanded) {
96831                     // Don't call expand() directly as there may be additional processing involved before
96832                     // expanding, e.g. in the case of a ComboBox query.
96833                     me.onTriggerClick();
96834                 }
96835             },
96836             esc: me.collapse,
96837             scope: me,
96838             forceKeyDown: true
96839         });
96840
96841         // Non-editable allows opening the picker by clicking the field
96842         if (!me.editable) {
96843             me.mon(me.inputEl, 'click', me.onTriggerClick, me);
96844         }
96845
96846         // Disable native browser autocomplete
96847         if (Ext.isGecko) {
96848             me.inputEl.dom.setAttribute('autocomplete', 'off');
96849         }
96850     },
96851
96852
96853     /**
96854      * Expand this field's picker dropdown.
96855      */
96856     expand: function() {
96857         var me = this,
96858             bodyEl, picker, collapseIf;
96859
96860         if (me.rendered && !me.isExpanded && !me.isDestroyed) {
96861             bodyEl = me.bodyEl;
96862             picker = me.getPicker();
96863             collapseIf = me.collapseIf;
96864
96865             // show the picker and set isExpanded flag
96866             picker.show();
96867             me.isExpanded = true;
96868             me.alignPicker();
96869             bodyEl.addCls(me.openCls);
96870
96871             // monitor clicking and mousewheel
96872             me.mon(Ext.getDoc(), {
96873                 mousewheel: collapseIf,
96874                 mousedown: collapseIf,
96875                 scope: me
96876             });
96877
96878             me.fireEvent('expand', me);
96879             me.onExpand();
96880         }
96881     },
96882
96883     onExpand: Ext.emptyFn,
96884
96885     /**
96886      * @protected
96887      * Aligns the picker to the
96888      */
96889     alignPicker: function() {
96890         var me = this,
96891             picker, isAbove,
96892             aboveSfx = '-above';
96893
96894         if (this.isExpanded) {
96895             picker = me.getPicker();
96896             if (me.matchFieldWidth) {
96897                 // Auto the height (it will be constrained by min and max width) unless there are no records to display.
96898                 picker.setSize(me.bodyEl.getWidth(), picker.store && picker.store.getCount() ? null : 0);
96899             }
96900             if (picker.isFloating()) {
96901                 picker.alignTo(me.inputEl, me.pickerAlign, me.pickerOffset);
96902
96903                 // add the {openCls}-above class if the picker was aligned above
96904                 // the field due to hitting the bottom of the viewport
96905                 isAbove = picker.el.getY() < me.inputEl.getY();
96906                 me.bodyEl[isAbove ? 'addCls' : 'removeCls'](me.openCls + aboveSfx);
96907                 picker.el[isAbove ? 'addCls' : 'removeCls'](picker.baseCls + aboveSfx);
96908             }
96909         }
96910     },
96911
96912     /**
96913      * Collapse this field's picker dropdown.
96914      */
96915     collapse: function() {
96916         if (this.isExpanded && !this.isDestroyed) {
96917             var me = this,
96918                 openCls = me.openCls,
96919                 picker = me.picker,
96920                 doc = Ext.getDoc(),
96921                 collapseIf = me.collapseIf,
96922                 aboveSfx = '-above';
96923
96924             // hide the picker and set isExpanded flag
96925             picker.hide();
96926             me.isExpanded = false;
96927
96928             // remove the openCls
96929             me.bodyEl.removeCls([openCls, openCls + aboveSfx]);
96930             picker.el.removeCls(picker.baseCls + aboveSfx);
96931
96932             // remove event listeners
96933             doc.un('mousewheel', collapseIf, me);
96934             doc.un('mousedown', collapseIf, me);
96935
96936             me.fireEvent('collapse', me);
96937             me.onCollapse();
96938         }
96939     },
96940
96941     onCollapse: Ext.emptyFn,
96942
96943
96944     /**
96945      * @private
96946      * Runs on mousewheel and mousedown of doc to check to see if we should collapse the picker
96947      */
96948     collapseIf: function(e) {
96949         var me = this;
96950         if (!me.isDestroyed && !e.within(me.bodyEl, false, true) && !e.within(me.picker.el, false, true)) {
96951             me.collapse();
96952         }
96953     },
96954
96955     /**
96956      * Return a reference to the picker component for this field, creating it if necessary by
96957      * calling {@link #createPicker}.
96958      * @return {Ext.Component} The picker component
96959      */
96960     getPicker: function() {
96961         var me = this;
96962         return me.picker || (me.picker = me.createPicker());
96963     },
96964
96965     /**
96966      * Create and return the component to be used as this field's picker. Must be implemented
96967      * by subclasses of Picker.
96968      * @return {Ext.Component} The picker component
96969      */
96970     createPicker: Ext.emptyFn,
96971
96972     /**
96973      * Handles the trigger click; by default toggles between expanding and collapsing the
96974      * picker component.
96975      */
96976     onTriggerClick: function() {
96977         var me = this;
96978         if (!me.readOnly && !me.disabled) {
96979             if (me.isExpanded) {
96980                 me.collapse();
96981             } else {
96982                 me.expand();
96983             }
96984             me.inputEl.focus();
96985         }
96986     },
96987
96988     mimicBlur: function(e) {
96989         var me = this,
96990             picker = me.picker;
96991         // ignore mousedown events within the picker element
96992         if (!picker || !e.within(picker.el, false, true)) {
96993             me.callParent(arguments);
96994         }
96995     },
96996
96997     onDestroy : function(){
96998         var me = this;
96999         Ext.destroy(me.picker, me.keyNav);
97000         me.callParent();
97001     }
97002
97003 });
97004
97005
97006 /**
97007  * @class Ext.form.field.Spinner
97008  * @extends Ext.form.field.Trigger
97009  * <p>A field with a pair of up/down spinner buttons. This class is not normally instantiated directly,
97010  * instead it is subclassed and the {@link #onSpinUp} and {@link #onSpinDown} methods are implemented
97011  * to handle when the buttons are clicked. A good example of this is the {@link Ext.form.field.Number} field
97012  * which uses the spinner to increment and decrement the field's value by its {@link Ext.form.field.Number#step step}
97013  * config value.</p>
97014  * {@img Ext.form.field.Spinner/Ext.form.field.Spinner.png Ext.form.field.Spinner field}
97015  * For example:
97016      Ext.define('Ext.ux.CustomSpinner', {
97017         extend: 'Ext.form.field.Spinner',
97018         alias: 'widget.customspinner',
97019         
97020         // override onSpinUp (using step isn't neccessary)
97021         onSpinUp: function() {
97022             var me = this;
97023             if (!me.readOnly) {
97024                 var val = me.step; // set the default value to the step value
97025                 if(me.getValue() !== '') {
97026                     val = parseInt(me.getValue().slice(0, -5)); // gets rid of " Pack"
97027                 }                          
97028                 me.setValue((val + me.step) + ' Pack');
97029             }
97030         },
97031         
97032         // override onSpinDown
97033         onSpinDown: function() {
97034             var me = this;
97035             if (!me.readOnly) {
97036                 if(me.getValue() !== '') {
97037                     val = parseInt(me.getValue().slice(0, -5)); // gets rid of " Pack"
97038                 }            
97039                 me.setValue((val - me.step) + ' Pack');
97040             }
97041         }
97042     });
97043     
97044     Ext.create('Ext.form.FormPanel', {
97045         title: 'Form with SpinnerField',
97046         bodyPadding: 5,
97047         width: 350,
97048         renderTo: Ext.getBody(),
97049         items:[{
97050             xtype: 'customspinner',
97051             fieldLabel: 'How Much Beer?',
97052             step: 6
97053         }]
97054     });
97055  * <p>By default, pressing the up and down arrow keys will also trigger the onSpinUp and onSpinDown methods;
97056  * to prevent this, set <tt>{@link #keyNavEnabled} = false</tt>.</p>
97057  *
97058  * @constructor
97059  * Creates a new Spinner field
97060  * @param {Object} config Configuration options
97061  * @xtype spinnerfield
97062  */
97063 Ext.define('Ext.form.field.Spinner', {
97064     extend: 'Ext.form.field.Trigger',
97065     alias: 'widget.spinnerfield',
97066     alternateClassName: 'Ext.form.Spinner',
97067     requires: ['Ext.util.KeyNav'],
97068
97069     trigger1Cls: Ext.baseCSSPrefix + 'form-spinner-up',
97070     trigger2Cls: Ext.baseCSSPrefix + 'form-spinner-down',
97071
97072     /**
97073      * @cfg {Boolean} spinUpEnabled
97074      * Specifies whether the up spinner button is enabled. Defaults to <tt>true</tt>. To change this
97075      * after the component is created, use the {@link #setSpinUpEnabled} method.
97076      */
97077     spinUpEnabled: true,
97078
97079     /**
97080      * @cfg {Boolean} spinDownEnabled
97081      * Specifies whether the down spinner button is enabled. Defaults to <tt>true</tt>. To change this
97082      * after the component is created, use the {@link #setSpinDownEnabled} method.
97083      */
97084     spinDownEnabled: true,
97085
97086     /**
97087      * @cfg {Boolean} keyNavEnabled
97088      * Specifies whether the up and down arrow keys should trigger spinning up and down.
97089      * Defaults to <tt>true</tt>.
97090      */
97091     keyNavEnabled: true,
97092
97093     /**
97094      * @cfg {Boolean} mouseWheelEnabled
97095      * Specifies whether the mouse wheel should trigger spinning up and down while the field has
97096      * focus. Defaults to <tt>true</tt>.
97097      */
97098     mouseWheelEnabled: true,
97099
97100     /**
97101      * @cfg {Boolean} repeatTriggerClick Whether a {@link Ext.util.ClickRepeater click repeater} should be
97102      * attached to the spinner buttons. Defaults to <tt>true</tt>.
97103      */
97104     repeatTriggerClick: true,
97105
97106     /**
97107      * This method is called when the spinner up button is clicked, or when the up arrow key is pressed
97108      * if {@link #keyNavEnabled} is <tt>true</tt>. Must be implemented by subclasses.
97109      */
97110     onSpinUp: Ext.emptyFn,
97111
97112     /**
97113      * This method is called when the spinner down button is clicked, or when the down arrow key is pressed
97114      * if {@link #keyNavEnabled} is <tt>true</tt>. Must be implemented by subclasses.
97115      */
97116     onSpinDown: Ext.emptyFn,
97117
97118     initComponent: function() {
97119         this.callParent();
97120
97121         this.addEvents(
97122             /**
97123              * @event spin
97124              * Fires when the spinner is made to spin up or down.
97125              * @param {Ext.form.field.Spinner} this
97126              * @param {String} direction Either 'up' if spinning up, or 'down' if spinning down.
97127              */
97128             'spin',
97129
97130             /**
97131              * @event spinup
97132              * Fires when the spinner is made to spin up.
97133              * @param {Ext.form.field.Spinner} this
97134              */
97135             'spinup',
97136
97137             /**
97138              * @event spindown
97139              * Fires when the spinner is made to spin down.
97140              * @param {Ext.form.field.Spinner} this
97141              */
97142             'spindown'
97143         );
97144     },
97145
97146     /**
97147      * @private override
97148      */
97149     onRender: function() {
97150         var me = this,
97151             triggers;
97152
97153         me.callParent(arguments);
97154         triggers = me.triggerEl;
97155
97156         /**
97157          * @property spinUpEl
97158          * @type Ext.core.Element
97159          * The spinner up button element
97160          */
97161         me.spinUpEl = triggers.item(0);
97162         /**
97163          * @property spinDownEl
97164          * @type Ext.core.Element
97165          * The spinner down button element
97166          */
97167         me.spinDownEl = triggers.item(1);
97168
97169         // Set initial enabled/disabled states
97170         me.setSpinUpEnabled(me.spinUpEnabled);
97171         me.setSpinDownEnabled(me.spinDownEnabled);
97172
97173         // Init up/down arrow keys
97174         if (me.keyNavEnabled) {
97175             me.spinnerKeyNav = Ext.create('Ext.util.KeyNav', me.inputEl, {
97176                 scope: me,
97177                 up: me.spinUp,
97178                 down: me.spinDown
97179             });
97180         }
97181
97182         // Init mouse wheel
97183         if (me.mouseWheelEnabled) {
97184             me.mon(me.bodyEl, 'mousewheel', me.onMouseWheel, me);
97185         }
97186     },
97187
97188     /**
97189      * @private override
97190      * Since the triggers are stacked, only measure the width of one of them.
97191      */
97192     getTriggerWidth: function() {
97193         return this.hideTrigger || this.readOnly ? 0 : this.spinUpEl.getWidth() + this.triggerWrap.getFrameWidth('lr');
97194     },
97195
97196     /**
97197      * @private Handles the spinner up button clicks.
97198      */
97199     onTrigger1Click: function() {
97200         this.spinUp();
97201     },
97202
97203     /**
97204      * @private Handles the spinner down button clicks.
97205      */
97206     onTrigger2Click: function() {
97207         this.spinDown();
97208     },
97209
97210     /**
97211      * Triggers the spinner to step up; fires the {@link #spin} and {@link #spinup} events and calls the
97212      * {@link #onSpinUp} method. Does nothing if the field is {@link #disabled} or if {@link #spinUpEnabled}
97213      * is false.
97214      */
97215     spinUp: function() {
97216         var me = this;
97217         if (me.spinUpEnabled && !me.disabled) {
97218             me.fireEvent('spin', me, 'up');
97219             me.fireEvent('spinup', me);
97220             me.onSpinUp();
97221         }
97222     },
97223
97224     /**
97225      * Triggers the spinner to step down; fires the {@link #spin} and {@link #spindown} events and calls the
97226      * {@link #onSpinDown} method. Does nothing if the field is {@link #disabled} or if {@link #spinDownEnabled}
97227      * is false.
97228      */
97229     spinDown: function() {
97230         var me = this;
97231         if (me.spinDownEnabled && !me.disabled) {
97232             me.fireEvent('spin', me, 'down');
97233             me.fireEvent('spindown', me);
97234             me.onSpinDown();
97235         }
97236     },
97237
97238     /**
97239      * Sets whether the spinner up button is enabled.
97240      * @param {Boolean} enabled true to enable the button, false to disable it.
97241      */
97242     setSpinUpEnabled: function(enabled) {
97243         var me = this,
97244             wasEnabled = me.spinUpEnabled;
97245         me.spinUpEnabled = enabled;
97246         if (wasEnabled !== enabled && me.rendered) {
97247             me.spinUpEl[enabled ? 'removeCls' : 'addCls'](me.trigger1Cls + '-disabled');
97248         }
97249     },
97250
97251     /**
97252      * Sets whether the spinner down button is enabled.
97253      * @param {Boolean} enabled true to enable the button, false to disable it.
97254      */
97255     setSpinDownEnabled: function(enabled) {
97256         var me = this,
97257             wasEnabled = me.spinDownEnabled;
97258         me.spinDownEnabled = enabled;
97259         if (wasEnabled !== enabled && me.rendered) {
97260             me.spinDownEl[enabled ? 'removeCls' : 'addCls'](me.trigger2Cls + '-disabled');
97261         }
97262     },
97263
97264     /**
97265      * @private
97266      * Handles mousewheel events on the field
97267      */
97268     onMouseWheel: function(e) {
97269         var me = this,
97270             delta;
97271         if (me.hasFocus) {
97272             delta = e.getWheelDelta();
97273             if (delta > 0) {
97274                 me.spinUp();
97275             }
97276             else if (delta < 0) {
97277                 me.spinDown();
97278             }
97279             e.stopEvent();
97280         }
97281     },
97282
97283     onDestroy: function() {
97284         Ext.destroyMembers(this, 'spinnerKeyNav', 'spinUpEl', 'spinDownEl');
97285         this.callParent();
97286     }
97287
97288 });
97289 /**
97290  * @class Ext.form.field.Number
97291  * @extends Ext.form.field.Spinner
97292
97293 A numeric text field that provides automatic keystroke filtering to disallow non-numeric characters,
97294 and numeric validation to limit the value to a range of valid numbers. The range of acceptable number
97295 values can be controlled by setting the {@link #minValue} and {@link #maxValue} configs, and fractional
97296 decimals can be disallowed by setting {@link #allowDecimals} to `false`.
97297
97298 By default, the number field is also rendered with a set of up/down spinner buttons and has
97299 up/down arrow key and mouse wheel event listeners attached for incrementing/decrementing the value by the
97300 {@link #step} value. To hide the spinner buttons set `{@link #hideTrigger hideTrigger}:true`; to disable the arrow key
97301 and mouse wheel handlers set `{@link #keyNavEnabled keyNavEnabled}:false` and
97302 `{@link #mouseWheelEnabled mouseWheelEnabled}:false`. See the example below.
97303
97304 #Example usage:#
97305 {@img Ext.form.Number/Ext.form.Number1.png Ext.form.Number component}
97306     Ext.create('Ext.form.Panel', {
97307         title: 'On The Wall',
97308         width: 300,
97309         bodyPadding: 10,
97310         renderTo: Ext.getBody(),
97311         items: [{
97312             xtype: 'numberfield',
97313             anchor: '100%',
97314             name: 'bottles',
97315             fieldLabel: 'Bottles of Beer',
97316             value: 99,
97317             maxValue: 99,
97318             minValue: 0
97319         }],
97320         buttons: [{
97321             text: 'Take one down, pass it around',
97322             handler: function() {
97323                 this.up('form').down('[name=bottles]').spinDown();
97324             }
97325         }]
97326     });
97327
97328 #Removing UI Enhancements#
97329 {@img Ext.form.Number/Ext.form.Number2.png Ext.form.Number component}
97330     Ext.create('Ext.form.Panel', {
97331         title: 'Personal Info',
97332         width: 300,
97333         bodyPadding: 10,
97334         renderTo: Ext.getBody(),        
97335         items: [{
97336             xtype: 'numberfield',
97337             anchor: '100%',
97338             name: 'age',
97339             fieldLabel: 'Age',
97340             minValue: 0, //prevents negative numbers
97341     
97342             // Remove spinner buttons, and arrow key and mouse wheel listeners
97343             hideTrigger: true,
97344             keyNavEnabled: false,
97345             mouseWheelEnabled: false
97346         }]
97347     });
97348
97349 #Using Step#
97350     Ext.create('Ext.form.Panel', {
97351         renderTo: Ext.getBody(),
97352         title: 'Step',
97353         width: 300,
97354         bodyPadding: 10,
97355         items: [{
97356             xtype: 'numberfield',
97357             anchor: '100%',
97358             name: 'evens',
97359             fieldLabel: 'Even Numbers',
97360
97361             // Set step so it skips every other number
97362             step: 2,
97363             value: 0,
97364
97365             // Add change handler to force user-entered numbers to evens
97366             listeners: {
97367                 change: function(field, value) {
97368                     value = parseInt(value, 10);
97369                     field.setValue(value + value % 2);
97370                 }
97371             }
97372         }]
97373     });
97374
97375
97376  * @constructor
97377  * Creates a new Number field
97378  * @param {Object} config Configuration options
97379  *
97380  * @xtype numberfield
97381  * @markdown
97382  * @docauthor Jason Johnston <jason@sencha.com>
97383  */
97384 Ext.define('Ext.form.field.Number', {
97385     extend:'Ext.form.field.Spinner',
97386     alias: 'widget.numberfield',
97387     alternateClassName: ['Ext.form.NumberField', 'Ext.form.Number'],
97388
97389     /**
97390      * @cfg {RegExp} stripCharsRe @hide
97391      */
97392     /**
97393      * @cfg {RegExp} maskRe @hide
97394      */
97395
97396     /**
97397      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
97398      */
97399     allowDecimals : true,
97400
97401     /**
97402      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
97403      */
97404     decimalSeparator : '.',
97405
97406     /**
97407      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
97408      */
97409     decimalPrecision : 2,
97410
97411     /**
97412      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY). Will be used by
97413      * the field's validation logic, and for
97414      * {@link Ext.form.field.Spinner#setSpinUpEnabled enabling/disabling the down spinner button}.
97415      */
97416     minValue: Number.NEGATIVE_INFINITY,
97417
97418     /**
97419      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE). Will be used by
97420      * the field's validation logic, and for
97421      * {@link Ext.form.field.Spinner#setSpinUpEnabled enabling/disabling the up spinner button}.
97422      */
97423     maxValue: Number.MAX_VALUE,
97424
97425     /**
97426      * @cfg {Number} step Specifies a numeric interval by which the field's value will be incremented or
97427      * decremented when the user invokes the spinner. Defaults to <tt>1</tt>.
97428      */
97429     step: 1,
97430
97431     /**
97432      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to 'The minimum
97433      * value for this field is {minValue}')
97434      */
97435     minText : 'The minimum value for this field is {0}',
97436
97437     /**
97438      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to 'The maximum
97439      * value for this field is {maxValue}')
97440      */
97441     maxText : 'The maximum value for this field is {0}',
97442
97443     /**
97444      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
97445      * if a valid character like '.' or '-' is left in the field with no number (defaults to '{value} is not a valid number')
97446      */
97447     nanText : '{0} is not a valid number',
97448
97449     /**
97450      * @cfg {String} negativeText Error text to display if the value is negative and {@link #minValue} is set to
97451      * <tt>0</tt>. This is used instead of the {@link #minText} in that circumstance only.
97452      */
97453     negativeText : 'The value cannot be negative',
97454
97455     /**
97456      * @cfg {String} baseChars The base set of characters to evaluate as valid numbers (defaults to '0123456789').
97457      */
97458     baseChars : '0123456789',
97459
97460     /**
97461      * @cfg {Boolean} autoStripChars True to automatically strip not allowed characters from the field. Defaults to <tt>false</tt>
97462      */
97463     autoStripChars: false,
97464
97465     initComponent: function() {
97466         var me = this,
97467             allowed;
97468
97469         this.callParent();
97470
97471         me.setMinValue(me.minValue);
97472         me.setMaxValue(me.maxValue);
97473
97474         // Build regexes for masking and stripping based on the configured options
97475         allowed = me.baseChars + '';
97476         if (me.allowDecimals) {
97477             allowed += me.decimalSeparator;
97478         }
97479         if (me.minValue < 0) {
97480             allowed += '-';
97481         }
97482         allowed = Ext.String.escapeRegex(allowed);
97483         me.maskRe = new RegExp('[' + allowed + ']');
97484         if (me.autoStripChars) {
97485             me.stripCharsRe = new RegExp('[^' + allowed + ']', 'gi');
97486         }
97487     },
97488
97489     /**
97490      * Runs all of Number's validations and returns an array of any errors. Note that this first
97491      * runs Text's validations, so the returned array is an amalgamation of all field errors.
97492      * The additional validations run test that the value is a number, and that it is within the
97493      * configured min and max values.
97494      * @param {Mixed} value The value to get errors for (defaults to the current field value)
97495      * @return {Array} All validation errors for this field
97496      */
97497     getErrors: function(value) {
97498         var me = this,
97499             errors = me.callParent(arguments),
97500             format = Ext.String.format,
97501             num;
97502
97503         value = Ext.isDefined(value) ? value : this.processRawValue(this.getRawValue());
97504
97505         if (value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
97506              return errors;
97507         }
97508
97509         value = String(value).replace(me.decimalSeparator, '.');
97510
97511         if(isNaN(value)){
97512             errors.push(format(me.nanText, value));
97513         }
97514
97515         num = me.parseValue(value);
97516
97517         if (me.minValue === 0 && num < 0) {
97518             errors.push(this.negativeText);
97519         }
97520         else if (num < me.minValue) {
97521             errors.push(format(me.minText, me.minValue));
97522         }
97523
97524         if (num > me.maxValue) {
97525             errors.push(format(me.maxText, me.maxValue));
97526         }
97527
97528
97529         return errors;
97530     },
97531
97532     rawToValue: function(rawValue) {
97533         return this.fixPrecision(this.parseValue(rawValue)) || rawValue || null;
97534     },
97535
97536     valueToRaw: function(value) {
97537         var me = this,
97538             decimalSeparator = me.decimalSeparator;
97539         value = me.parseValue(value);
97540         value = me.fixPrecision(value);
97541         value = Ext.isNumber(value) ? value : parseFloat(String(value).replace(decimalSeparator, '.'));
97542         value = isNaN(value) ? '' : String(value).replace('.', decimalSeparator);
97543         return value;
97544     },
97545
97546     onChange: function() {
97547         var me = this,
97548             value = me.getValue(),
97549             valueIsNull = value === null;
97550
97551         me.callParent(arguments);
97552
97553         // Update the spinner buttons
97554         me.setSpinUpEnabled(valueIsNull || value < me.maxValue);
97555         me.setSpinDownEnabled(valueIsNull || value > me.minValue);
97556     },
97557
97558     /**
97559      * Replaces any existing {@link #minValue} with the new value.
97560      * @param {Number} value The minimum value
97561      */
97562     setMinValue : function(value) {
97563         this.minValue = Ext.Number.from(value, Number.NEGATIVE_INFINITY);
97564     },
97565
97566     /**
97567      * Replaces any existing {@link #maxValue} with the new value.
97568      * @param {Number} value The maximum value
97569      */
97570     setMaxValue: function(value) {
97571         this.maxValue = Ext.Number.from(value, Number.MAX_VALUE);
97572     },
97573
97574     // private
97575     parseValue : function(value) {
97576         value = parseFloat(String(value).replace(this.decimalSeparator, '.'));
97577         return isNaN(value) ? null : value;
97578     },
97579
97580     /**
97581      * @private
97582      *
97583      */
97584     fixPrecision : function(value) {
97585         var me = this,
97586             nan = isNaN(value),
97587             precision = me.decimalPrecision;
97588
97589         if (nan || !value) {
97590             return nan ? '' : value;
97591         } else if (!me.allowDecimals || precision <= 0) {
97592             precision = 0;
97593         }
97594
97595         return parseFloat(Ext.Number.toFixed(parseFloat(value), precision));
97596     },
97597
97598     beforeBlur : function() {
97599         var me = this,
97600             v = me.parseValue(me.getRawValue());
97601
97602         if (!Ext.isEmpty(v)) {
97603             me.setValue(v);
97604         }
97605     },
97606
97607     onSpinUp: function() {
97608         var me = this;
97609         if (!me.readOnly) {
97610             me.setValue(Ext.Number.constrain(me.getValue() + me.step, me.minValue, me.maxValue));
97611         }
97612     },
97613
97614     onSpinDown: function() {
97615         var me = this;
97616         if (!me.readOnly) {
97617             me.setValue(Ext.Number.constrain(me.getValue() - me.step, me.minValue, me.maxValue));
97618         }
97619     }
97620 });
97621
97622 /**
97623  * @class Ext.toolbar.Paging
97624  * @extends Ext.toolbar.Toolbar
97625  * <p>As the amount of records increases, the time required for the browser to render
97626  * them increases. Paging is used to reduce the amount of data exchanged with the client.
97627  * Note: if there are more records/rows than can be viewed in the available screen area, vertical
97628  * scrollbars will be added.</p>
97629  * <p>Paging is typically handled on the server side (see exception below). The client sends
97630  * parameters to the server side, which the server needs to interpret and then respond with the
97631  * appropriate data.</p>
97632  * <p><b>Ext.toolbar.Paging</b> is a specialized toolbar that is bound to a {@link Ext.data.Store}
97633  * and provides automatic paging control. This Component {@link Ext.data.Store#load load}s blocks
97634  * of data into the <tt>{@link #store}</tt> by passing {@link Ext.data.Store#paramNames paramNames} used for
97635  * paging criteria.</p>
97636  *
97637  * {@img Ext.toolbar.Paging/Ext.toolbar.Paging.png Ext.toolbar.Paging component}
97638  *
97639  * <p>PagingToolbar is typically used as one of the Grid's toolbars:</p>
97640  * <pre><code>
97641  *    var itemsPerPage = 2;   // set the number of items you want per page
97642  *    
97643  *    var store = Ext.create('Ext.data.Store', {
97644  *        id:'simpsonsStore',
97645  *        autoLoad: false,
97646  *        fields:['name', 'email', 'phone'],
97647  *        pageSize: itemsPerPage, // items per page
97648  *        proxy: {
97649  *            type: 'ajax',
97650  *            url: 'pagingstore.js',  // url that will load data with respect to start and limit params
97651  *            reader: {
97652  *                type: 'json',
97653  *                root: 'items',
97654  *                totalProperty: 'total'
97655  *            }
97656  *        }
97657  *    });
97658  *    
97659  *    // specify segment of data you want to load using params
97660  *    store.load({
97661  *        params:{
97662  *            start:0,    
97663  *            limit: itemsPerPage
97664  *        }
97665  *    });
97666  *    
97667  *    Ext.create('Ext.grid.Panel', {
97668  *        title: 'Simpsons',
97669  *        store: store,
97670  *        columns: [
97671  *            {header: 'Name',  dataIndex: 'name'},
97672  *            {header: 'Email', dataIndex: 'email', flex:1},
97673  *            {header: 'Phone', dataIndex: 'phone'}
97674  *        ],
97675  *        width: 400,
97676  *        height: 125,
97677  *        dockedItems: [{
97678  *            xtype: 'pagingtoolbar',
97679  *            store: store,   // same store GridPanel is using
97680  *            dock: 'bottom',
97681  *            displayInfo: true
97682  *        }],
97683  *        renderTo: Ext.getBody()
97684  *    });
97685  * </code></pre>
97686  *
97687  * <p>To use paging, pass the paging requirements to the server when the store is first loaded.</p>
97688  * <pre><code>
97689 store.load({
97690     params: {
97691         // specify params for the first page load if using paging
97692         start: 0,          
97693         limit: myPageSize,
97694         // other params
97695         foo:   'bar'
97696     }
97697 });
97698  * </code></pre>
97699  * 
97700  * <p>If using {@link Ext.data.Store#autoLoad store's autoLoad} configuration:</p>
97701  * <pre><code>
97702 var myStore = new Ext.data.Store({
97703     {@link Ext.data.Store#autoLoad autoLoad}: {start: 0, limit: 25},
97704     ...
97705 });
97706  * </code></pre>
97707  * 
97708  * <p>The packet sent back from the server would have this form:</p>
97709  * <pre><code>
97710 {
97711     "success": true,
97712     "results": 2000, 
97713     "rows": [ // <b>*Note:</b> this must be an Array 
97714         { "id":  1, "name": "Bill", "occupation": "Gardener" },
97715         { "id":  2, "name":  "Ben", "occupation": "Horticulturalist" },
97716         ...
97717         { "id": 25, "name":  "Sue", "occupation": "Botanist" }
97718     ]
97719 }
97720  * </code></pre>
97721  * <p><u>Paging with Local Data</u></p>
97722  * <p>Paging can also be accomplished with local data using extensions:</p>
97723  * <div class="mdetail-params"><ul>
97724  * <li><a href="http://sencha.com/forum/showthread.php?t=71532">Ext.ux.data.PagingStore</a></li>
97725  * <li>Paging Memory Proxy (examples/ux/PagingMemoryProxy.js)</li>
97726  * </ul></div>
97727  * @constructor Create a new PagingToolbar
97728  * @param {Object} config The config object
97729  * @xtype pagingtoolbar
97730  */
97731 Ext.define('Ext.toolbar.Paging', {
97732     extend: 'Ext.toolbar.Toolbar',
97733     alias: 'widget.pagingtoolbar',
97734     alternateClassName: 'Ext.PagingToolbar',
97735     requires: ['Ext.toolbar.TextItem', 'Ext.form.field.Number'],
97736     /**
97737      * @cfg {Ext.data.Store} store
97738      * The {@link Ext.data.Store} the paging toolbar should use as its data source (required).
97739      */
97740     /**
97741      * @cfg {Boolean} displayInfo
97742      * <tt>true</tt> to display the displayMsg (defaults to <tt>false</tt>)
97743      */
97744     displayInfo: false,
97745     /**
97746      * @cfg {Boolean} prependButtons
97747      * <tt>true</tt> to insert any configured <tt>items</tt> <i>before</i> the paging buttons.
97748      * Defaults to <tt>false</tt>.
97749      */
97750     prependButtons: false,
97751     /**
97752      * @cfg {String} displayMsg
97753      * The paging status message to display (defaults to <tt>'Displaying {0} - {1} of {2}'</tt>).
97754      * Note that this string is formatted using the braced numbers <tt>{0}-{2}</tt> as tokens
97755      * that are replaced by the values for start, end and total respectively. These tokens should
97756      * be preserved when overriding this string if showing those values is desired.
97757      */
97758     displayMsg : 'Displaying {0} - {1} of {2}',
97759     /**
97760      * @cfg {String} emptyMsg
97761      * The message to display when no records are found (defaults to 'No data to display')
97762      */
97763     emptyMsg : 'No data to display',
97764     /**
97765      * @cfg {String} beforePageText
97766      * The text displayed before the input item (defaults to <tt>'Page'</tt>).
97767      */
97768     beforePageText : 'Page',
97769     /**
97770      * @cfg {String} afterPageText
97771      * Customizable piece of the default paging text (defaults to <tt>'of {0}'</tt>). Note that
97772      * this string is formatted using <tt>{0}</tt> as a token that is replaced by the number of
97773      * total pages. This token should be preserved when overriding this string if showing the
97774      * total page count is desired.
97775      */
97776     afterPageText : 'of {0}',
97777     /**
97778      * @cfg {String} firstText
97779      * The quicktip text displayed for the first page button (defaults to <tt>'First Page'</tt>).
97780      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
97781      */
97782     firstText : 'First Page',
97783     /**
97784      * @cfg {String} prevText
97785      * The quicktip text displayed for the previous page button (defaults to <tt>'Previous Page'</tt>).
97786      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
97787      */
97788     prevText : 'Previous Page',
97789     /**
97790      * @cfg {String} nextText
97791      * The quicktip text displayed for the next page button (defaults to <tt>'Next Page'</tt>).
97792      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
97793      */
97794     nextText : 'Next Page',
97795     /**
97796      * @cfg {String} lastText
97797      * The quicktip text displayed for the last page button (defaults to <tt>'Last Page'</tt>).
97798      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
97799      */
97800     lastText : 'Last Page',
97801     /**
97802      * @cfg {String} refreshText
97803      * The quicktip text displayed for the Refresh button (defaults to <tt>'Refresh'</tt>).
97804      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
97805      */
97806     refreshText : 'Refresh',
97807     /**
97808      * @cfg {Number} inputItemWidth
97809      * The width in pixels of the input field used to display and change the current page number (defaults to 30).
97810      */
97811     inputItemWidth : 30,
97812     
97813     /**
97814      * Gets the standard paging items in the toolbar
97815      * @private
97816      */
97817     getPagingItems: function() {
97818         var me = this;
97819         
97820         return [{
97821             itemId: 'first',
97822             tooltip: me.firstText,
97823             overflowText: me.firstText,
97824             iconCls: Ext.baseCSSPrefix + 'tbar-page-first',
97825             disabled: true,
97826             handler: me.moveFirst,
97827             scope: me
97828         },{
97829             itemId: 'prev',
97830             tooltip: me.prevText,
97831             overflowText: me.prevText,
97832             iconCls: Ext.baseCSSPrefix + 'tbar-page-prev',
97833             disabled: true,
97834             handler: me.movePrevious,
97835             scope: me
97836         },
97837         '-',
97838         me.beforePageText,
97839         {
97840             xtype: 'numberfield',
97841             itemId: 'inputItem',
97842             name: 'inputItem',
97843             cls: Ext.baseCSSPrefix + 'tbar-page-number',
97844             allowDecimals: false,
97845             minValue: 1,
97846             hideTrigger: true,
97847             enableKeyEvents: true,
97848             selectOnFocus: true,
97849             submitValue: false,
97850             width: me.inputItemWidth,
97851             margins: '-1 2 3 2',
97852             listeners: {
97853                 scope: me,
97854                 keydown: me.onPagingKeyDown,
97855                 blur: me.onPagingBlur
97856             }
97857         },{
97858             xtype: 'tbtext',
97859             itemId: 'afterTextItem',
97860             text: Ext.String.format(me.afterPageText, 1)
97861         },
97862         '-',
97863         {
97864             itemId: 'next',
97865             tooltip: me.nextText,
97866             overflowText: me.nextText,
97867             iconCls: Ext.baseCSSPrefix + 'tbar-page-next',
97868             disabled: true,
97869             handler: me.moveNext,
97870             scope: me
97871         },{
97872             itemId: 'last',
97873             tooltip: me.lastText,
97874             overflowText: me.lastText,
97875             iconCls: Ext.baseCSSPrefix + 'tbar-page-last',
97876             disabled: true,
97877             handler: me.moveLast,
97878             scope: me
97879         },
97880         '-',
97881         {
97882             itemId: 'refresh',
97883             tooltip: me.refreshText,
97884             overflowText: me.refreshText,
97885             iconCls: Ext.baseCSSPrefix + 'tbar-loading',
97886             handler: me.doRefresh,
97887             scope: me
97888         }];
97889     },
97890
97891     initComponent : function(){
97892         var me = this,
97893             pagingItems = me.getPagingItems(),
97894             userItems   = me.items || me.buttons || [];
97895             
97896         if (me.prependButtons) {
97897             me.items = userItems.concat(pagingItems);
97898         } else {
97899             me.items = pagingItems.concat(userItems);
97900         }
97901         delete me.buttons;
97902         
97903         if (me.displayInfo) {
97904             me.items.push('->');
97905             me.items.push({xtype: 'tbtext', itemId: 'displayItem'});
97906         }
97907         
97908         me.callParent();
97909         
97910         me.addEvents(
97911             /**
97912              * @event change
97913              * Fires after the active page has been changed.
97914              * @param {Ext.toolbar.Paging} this
97915              * @param {Object} pageData An object that has these properties:<ul>
97916              * <li><code>total</code> : Number <div class="sub-desc">The total number of records in the dataset as
97917              * returned by the server</div></li>
97918              * <li><code>currentPage</code> : Number <div class="sub-desc">The current page number</div></li>
97919              * <li><code>pageCount</code> : Number <div class="sub-desc">The total number of pages (calculated from
97920              * the total number of records in the dataset as returned by the server and the current {@link #pageSize})</div></li>
97921              * <li><code>toRecord</code> : Number <div class="sub-desc">The starting record index for the current page</div></li>
97922              * <li><code>fromRecord</code> : Number <div class="sub-desc">The ending record index for the current page</div></li>
97923              * </ul>
97924              */
97925             'change',
97926             /**
97927              * @event beforechange
97928              * Fires just before the active page is changed.
97929              * Return false to prevent the active page from being changed.
97930              * @param {Ext.toolbar.Paging} this
97931              * @param {Number} page The page number that will be loaded on change 
97932              */
97933             'beforechange'
97934         );
97935         me.on('afterlayout', me.onLoad, me, {single: true});
97936
97937         me.bindStore(me.store, true);
97938     },
97939     // private
97940     updateInfo : function(){
97941         var me = this,
97942             displayItem = me.child('#displayItem'),
97943             store = me.store,
97944             pageData = me.getPageData(),
97945             count, msg;
97946
97947         if (displayItem) {
97948             count = store.getCount();
97949             if (count === 0) {
97950                 msg = me.emptyMsg;
97951             } else {
97952                 msg = Ext.String.format(
97953                     me.displayMsg,
97954                     pageData.fromRecord,
97955                     pageData.toRecord,
97956                     pageData.total
97957                 );
97958             }
97959             displayItem.setText(msg);
97960             me.doComponentLayout();
97961         }
97962     },
97963
97964     // private
97965     onLoad : function(){
97966         var me = this,
97967             pageData,
97968             currPage,
97969             pageCount,
97970             afterText;
97971             
97972         if (!me.rendered) {
97973             return;
97974         }
97975
97976         pageData = me.getPageData();
97977         currPage = pageData.currentPage;
97978         pageCount = pageData.pageCount;
97979         afterText = Ext.String.format(me.afterPageText, isNaN(pageCount) ? 1 : pageCount);
97980
97981         me.child('#afterTextItem').setText(afterText);
97982         me.child('#inputItem').setValue(currPage);
97983         me.child('#first').setDisabled(currPage === 1);
97984         me.child('#prev').setDisabled(currPage === 1);
97985         me.child('#next').setDisabled(currPage === pageCount);
97986         me.child('#last').setDisabled(currPage === pageCount);
97987         me.child('#refresh').enable();
97988         me.updateInfo();
97989         me.fireEvent('change', me, pageData);
97990     },
97991
97992     // private
97993     getPageData : function(){
97994         var store = this.store,
97995             totalCount = store.getTotalCount();
97996             
97997         return {
97998             total : totalCount,
97999             currentPage : store.currentPage,
98000             pageCount: Math.ceil(totalCount / store.pageSize),
98001             //pageCount :  store.getPageCount(),
98002             fromRecord: ((store.currentPage - 1) * store.pageSize) + 1,
98003             toRecord: Math.min(store.currentPage * store.pageSize, totalCount)
98004             
98005         };
98006     },
98007
98008     // private
98009     onLoadError : function(){
98010         if (!this.rendered) {
98011             return;
98012         }
98013         this.child('#refresh').enable();
98014     },
98015
98016     // private
98017     readPageFromInput : function(pageData){
98018         var v = this.child('#inputItem').getValue(),
98019             pageNum = parseInt(v, 10);
98020             
98021         if (!v || isNaN(pageNum)) {
98022             this.child('#inputItem').setValue(pageData.currentPage);
98023             return false;
98024         }
98025         return pageNum;
98026     },
98027
98028     onPagingFocus : function(){
98029         this.child('#inputItem').select();
98030     },
98031
98032     //private
98033     onPagingBlur : function(e){
98034         var curPage = this.getPageData().currentPage;
98035         this.child('#inputItem').setValue(curPage);
98036     },
98037
98038     // private
98039     onPagingKeyDown : function(field, e){
98040         var k = e.getKey(),
98041             pageData = this.getPageData(),
98042             increment = e.shiftKey ? 10 : 1,
98043             pageNum,
98044             me = this;
98045
98046         if (k == e.RETURN) {
98047             e.stopEvent();
98048             pageNum = me.readPageFromInput(pageData);
98049             if (pageNum !== false) {
98050                 pageNum = Math.min(Math.max(1, pageNum), pageData.total);
98051                 if(me.fireEvent('beforechange', me, pageNum) !== false){
98052                     me.store.loadPage(pageNum);
98053                 }
98054             }
98055         } else if (k == e.HOME || k == e.END) {
98056             e.stopEvent();
98057             pageNum = k == e.HOME ? 1 : pageData.pageCount;
98058             field.setValue(pageNum);
98059         } else if (k == e.UP || k == e.PAGEUP || k == e.DOWN || k == e.PAGEDOWN) {
98060             e.stopEvent();
98061             pageNum = me.readPageFromInput(pageData);
98062             if (pageNum) {
98063                 if (k == e.DOWN || k == e.PAGEDOWN) {
98064                     increment *= -1;
98065                 }
98066                 pageNum += increment;
98067                 if (pageNum >= 1 && pageNum <= pageData.pages) {
98068                     field.setValue(pageNum);
98069                 }
98070             }
98071         }
98072     },
98073
98074     // private
98075     beforeLoad : function(){
98076         if(this.rendered && this.refresh){
98077             this.refresh.disable();
98078         }
98079     },
98080
98081     // private
98082     doLoad : function(start){
98083         if(this.fireEvent('beforechange', this, o) !== false){
98084             this.store.load();
98085         }
98086     },
98087
98088     /**
98089      * Move to the first page, has the same effect as clicking the 'first' button.
98090      */
98091     moveFirst : function(){
98092         var me = this;
98093         if(me.fireEvent('beforechange', me, 1) !== false){
98094             me.store.loadPage(1);
98095         }
98096     },
98097
98098     /**
98099      * Move to the previous page, has the same effect as clicking the 'previous' button.
98100      */
98101     movePrevious : function(){
98102         var me = this,
98103             prev = me.store.currentPage - 1;
98104         
98105         if(me.fireEvent('beforechange', me, prev) !== false){
98106             me.store.previousPage();
98107         }
98108     },
98109
98110     /**
98111      * Move to the next page, has the same effect as clicking the 'next' button.
98112      */
98113     moveNext : function(){
98114         var me = this;        
98115         if(me.fireEvent('beforechange', me, me.store.currentPage + 1) !== false){
98116             me.store.nextPage();
98117         }
98118     },
98119
98120     /**
98121      * Move to the last page, has the same effect as clicking the 'last' button.
98122      */
98123     moveLast : function(){
98124         var me = this, 
98125             last = this.getPageData().pageCount;
98126         
98127         if(me.fireEvent('beforechange', me, last) !== false){
98128             me.store.loadPage(last);
98129         }
98130     },
98131
98132     /**
98133      * Refresh the current page, has the same effect as clicking the 'refresh' button.
98134      */
98135     doRefresh : function(){
98136         var me = this,
98137             current = me.store.currentPage;
98138         
98139         if(me.fireEvent('beforechange', me, current) !== false){
98140             me.store.loadPage(current);
98141         }
98142     },
98143
98144     /**
98145      * Binds the paging toolbar to the specified {@link Ext.data.Store}
98146      * @param {Store} store The store to bind to this toolbar
98147      * @param {Boolean} initial (Optional) true to not remove listeners
98148      */
98149     bindStore : function(store, initial){
98150         var me = this;
98151         
98152         if (!initial && me.store) {
98153             if(store !== me.store && me.store.autoDestroy){
98154                 me.store.destroy();
98155             }else{
98156                 me.store.un('beforeload', me.beforeLoad, me);
98157                 me.store.un('load', me.onLoad, me);
98158                 me.store.un('exception', me.onLoadError, me);
98159             }
98160             if(!store){
98161                 me.store = null;
98162             }
98163         }
98164         if (store) {
98165             store = Ext.data.StoreManager.lookup(store);
98166             store.on({
98167                 scope: me,
98168                 beforeload: me.beforeLoad,
98169                 load: me.onLoad,
98170                 exception: me.onLoadError
98171             });
98172         }
98173         me.store = store;
98174     },
98175
98176     /**
98177      * Unbinds the paging toolbar from the specified {@link Ext.data.Store} <b>(deprecated)</b>
98178      * @param {Ext.data.Store} store The data store to unbind
98179      */
98180     unbind : function(store){
98181         this.bindStore(null);
98182     },
98183
98184     /**
98185      * Binds the paging toolbar to the specified {@link Ext.data.Store} <b>(deprecated)</b>
98186      * @param {Ext.data.Store} store The data store to bind
98187      */
98188     bind : function(store){
98189         this.bindStore(store);
98190     },
98191
98192     // private
98193     onDestroy : function(){
98194         this.bindStore(null);
98195         this.callParent();
98196     }
98197 });
98198
98199 /**
98200  * @class Ext.view.BoundList
98201  * @extends Ext.view.View
98202  * An internal used DataView for ComboBox, MultiSelect and ItemSelector.
98203  */
98204 Ext.define('Ext.view.BoundList', {
98205     extend: 'Ext.view.View',
98206     alias: 'widget.boundlist',
98207     alternateClassName: 'Ext.BoundList',
98208     requires: ['Ext.layout.component.BoundList', 'Ext.toolbar.Paging'],
98209
98210     /**
98211      * @cfg {Number} pageSize If greater than <tt>0</tt>, a {@link Ext.toolbar.Paging} is displayed at the
98212      * bottom of the list and store queries will execute with page start and
98213      * {@link Ext.toolbar.Paging#pageSize limit} parameters.
98214      */
98215     pageSize: 0,
98216
98217     /**
98218      * @property pagingToolbar
98219      * @type {Ext.toolbar.Paging}
98220      * A reference to the PagingToolbar instance in this view. Only populated if {@link #pageSize} is greater
98221      * than zero and the BoundList has been rendered.
98222      */
98223
98224     // private overrides
98225     autoScroll: true,
98226     baseCls: Ext.baseCSSPrefix + 'boundlist',
98227     listItemCls: '',
98228     shadow: false,
98229     trackOver: true,
98230     refreshed: 0,
98231
98232     ariaRole: 'listbox',
98233
98234     componentLayout: 'boundlist',
98235
98236     renderTpl: ['<div class="list-ct"></div>'],
98237
98238     initComponent: function() {
98239         var me = this,
98240             baseCls = me.baseCls,
98241             itemCls = baseCls + '-item';
98242         me.itemCls = itemCls;
98243         me.selectedItemCls = baseCls + '-selected';
98244         me.overItemCls = baseCls + '-item-over';
98245         me.itemSelector = "." + itemCls;
98246
98247         if (me.floating) {
98248             me.addCls(baseCls + '-floating');
98249         }
98250
98251         // should be setting aria-posinset based on entire set of data
98252         // not filtered set
98253         me.tpl = Ext.create('Ext.XTemplate', 
98254             '<ul><tpl for=".">',
98255                 '<li role="option" class="' + itemCls + '">' + me.getInnerTpl(me.displayField) + '</li>',
98256             '</tpl></ul>'
98257         );
98258
98259         if (me.pageSize) {
98260             me.pagingToolbar = me.createPagingToolbar();
98261         }
98262
98263         me.callParent();
98264
98265         Ext.applyIf(me.renderSelectors, {
98266             listEl: '.list-ct'
98267         });
98268     },
98269
98270     createPagingToolbar: function() {
98271         return Ext.widget('pagingtoolbar', {
98272             pageSize: this.pageSize,
98273             store: this.store,
98274             border: false
98275         });
98276     },
98277
98278     onRender: function() {
98279         var me = this,
98280             toolbar = me.pagingToolbar;
98281         me.callParent(arguments);
98282         if (toolbar) {
98283             toolbar.render(me.el);
98284         }
98285     },
98286
98287     bindStore : function(store, initial) {
98288         var me = this,
98289             toolbar = me.pagingToolbar;
98290         me.callParent(arguments);
98291         if (toolbar) {
98292             toolbar.bindStore(store, initial);
98293         }
98294     },
98295
98296     getTargetEl: function() {
98297         return this.listEl || this.el;
98298     },
98299
98300     getInnerTpl: function(displayField) {
98301         return '{' + displayField + '}';
98302     },
98303
98304     refresh: function() {
98305         var me = this;
98306         me.callParent();
98307         if (me.isVisible()) {
98308             me.refreshed++;
98309             me.doComponentLayout();
98310             me.refreshed--;
98311         }
98312     },
98313     
98314     initAria: function() {
98315         this.callParent();
98316         
98317         var selModel = this.getSelectionModel(),
98318             mode     = selModel.getSelectionMode(),
98319             actionEl = this.getActionEl();
98320         
98321         // TODO: subscribe to mode changes or allow the selModel to manipulate this attribute.
98322         if (mode !== 'SINGLE') {
98323             actionEl.dom.setAttribute('aria-multiselectable', true);
98324         }
98325     },
98326
98327     onDestroy: function() {
98328         Ext.destroyMembers(this, 'pagingToolbar', 'listEl');
98329         this.callParent();
98330     }
98331 });
98332
98333 /**
98334  * @class Ext.view.BoundListKeyNav
98335  * @extends Ext.util.KeyNav
98336  * A specialized {@link Ext.util.KeyNav} implementation for navigating a {@link Ext.view.BoundList} using
98337  * the keyboard. The up, down, pageup, pagedown, home, and end keys move the active highlight
98338  * through the list. The enter key invokes the selection model's select action using the highlighted item.
98339  */
98340 Ext.define('Ext.view.BoundListKeyNav', {
98341     extend: 'Ext.util.KeyNav',
98342     requires: 'Ext.view.BoundList',
98343
98344     /**
98345      * @cfg {Ext.view.BoundList} boundList
98346      * @required
98347      * The {@link Ext.view.BoundList} instance for which key navigation will be managed. This is required.
98348      */
98349
98350     constructor: function(el, config) {
98351         var me = this;
98352         me.boundList = config.boundList;
98353         me.callParent([el, Ext.apply({}, config, me.defaultHandlers)]);
98354     },
98355
98356     defaultHandlers: {
98357         up: function() {
98358             var me = this,
98359                 boundList = me.boundList,
98360                 allItems = boundList.all,
98361                 oldItem = boundList.highlightedItem,
98362                 oldItemIdx = oldItem ? boundList.indexOf(oldItem) : -1,
98363                 newItemIdx = oldItemIdx > 0 ? oldItemIdx - 1 : allItems.getCount() - 1; //wraps around
98364             me.highlightAt(newItemIdx);
98365         },
98366
98367         down: function() {
98368             var me = this,
98369                 boundList = me.boundList,
98370                 allItems = boundList.all,
98371                 oldItem = boundList.highlightedItem,
98372                 oldItemIdx = oldItem ? boundList.indexOf(oldItem) : -1,
98373                 newItemIdx = oldItemIdx < allItems.getCount() - 1 ? oldItemIdx + 1 : 0; //wraps around
98374             me.highlightAt(newItemIdx);
98375         },
98376
98377         pageup: function() {
98378             //TODO
98379         },
98380
98381         pagedown: function() {
98382             //TODO
98383         },
98384
98385         home: function() {
98386             this.highlightAt(0);
98387         },
98388
98389         end: function() {
98390             var me = this;
98391             me.highlightAt(me.boundList.all.getCount() - 1);
98392         },
98393
98394         enter: function(e) {
98395             this.selectHighlighted(e);
98396         }
98397     },
98398
98399     /**
98400      * Highlights the item at the given index.
98401      * @param {Number} index
98402      */
98403     highlightAt: function(index) {
98404         var boundList = this.boundList,
98405             item = boundList.all.item(index);
98406         if (item) {
98407             item = item.dom;
98408             boundList.highlightItem(item);
98409             boundList.getTargetEl().scrollChildIntoView(item, false);
98410         }
98411     },
98412
98413     /**
98414      * Triggers selection of the currently highlighted item according to the behavior of
98415      * the configured SelectionModel.
98416      */
98417     selectHighlighted: function(e) {
98418         var me = this,
98419             boundList = me.boundList,
98420             highlighted = boundList.highlightedItem,
98421             selModel = boundList.getSelectionModel();
98422         if (highlighted) {
98423             selModel.selectWithEvent(boundList.getRecord(highlighted), e);
98424         }
98425     }
98426
98427 });
98428 /**
98429  * @class Ext.form.field.ComboBox
98430  * @extends Ext.form.field.Picker
98431  *
98432  * A combobox control with support for autocomplete, remote loading, and many other features.
98433  *
98434  * A ComboBox is like a combination of a traditional HTML text `&lt;input&gt;` field and a `&lt;select&gt;`
98435  * field; the user is able to type freely into the field, and/or pick values from a dropdown selection
98436  * list. The user can input any value by default, even if it does not appear in the selection list;
98437  * to prevent free-form values and restrict them to items in the list, set {@link #forceSelection} to `true`.
98438  *
98439  * The selection list's options are populated from any {@link Ext.data.Store}, including remote
98440  * stores. The data items in the store are mapped to each option's displayed text and backing value via
98441  * the {@link #valueField} and {@link #displayField} configurations, respectively.
98442  *
98443  * If your store is not remote, i.e. it depends only on local data and is loaded up front, you should be
98444  * sure to set the {@link #queryMode} to `'local'`, as this will improve responsiveness for the user.
98445  *
98446  * {@img Ext.form.ComboBox/Ext.form.ComboBox.png Ext.form.ComboBox component}
98447  *
98448  * ## Example usage:
98449  *
98450  *     // The data store containing the list of states
98451  *     var states = Ext.create('Ext.data.Store', {
98452  *         fields: ['abbr', 'name'],
98453  *         data : [
98454  *             {"abbr":"AL", "name":"Alabama"},
98455  *             {"abbr":"AK", "name":"Alaska"},
98456  *             {"abbr":"AZ", "name":"Arizona"}
98457  *             //...
98458  *         ]
98459  *     });
98460  *
98461  *     // Create the combo box, attached to the states data store
98462  *     Ext.create('Ext.form.ComboBox', {
98463  *         fieldLabel: 'Choose State',
98464  *         store: states,
98465  *         queryMode: 'local',
98466  *         displayField: 'name',
98467  *         valueField: 'abbr',
98468  *         renderTo: Ext.getBody()
98469  *     });
98470  *
98471  * ## Events
98472  *
98473  * To do something when something in ComboBox is selected, configure the select event:
98474  *
98475  *     var cb = Ext.create('Ext.form.ComboBox', {
98476  *         // all of your config options
98477  *         listeners:{
98478  *              scope: yourScope,
98479  *              'select': yourFunction
98480  *         }
98481  *     });
98482  *
98483  *     // Alternatively, you can assign events after the object is created:
98484  *     var cb = new Ext.form.field.ComboBox(yourOptions);
98485  *     cb.on('select', yourFunction, yourScope);
98486  *
98487  * ## Multiple Selection
98488  *
98489  * ComboBox also allows selection of multiple items from the list; to enable multi-selection set the
98490  * {@link #multiSelect} config to `true`.
98491  *
98492  * @constructor
98493  * Create a new ComboBox.
98494  * @param {Object} config Configuration options
98495  * @xtype combo
98496  * @docauthor Jason Johnston <jason@sencha.com>
98497  */
98498 Ext.define('Ext.form.field.ComboBox', {
98499     extend:'Ext.form.field.Picker',
98500     requires: ['Ext.util.DelayedTask', 'Ext.EventObject', 'Ext.view.BoundList', 'Ext.view.BoundListKeyNav', 'Ext.data.StoreManager'],
98501     alternateClassName: 'Ext.form.ComboBox',
98502     alias: ['widget.combobox', 'widget.combo'],
98503
98504     /**
98505      * @cfg {String} triggerCls
98506      * An additional CSS class used to style the trigger button. The trigger will always get the
98507      * {@link #triggerBaseCls} by default and <tt>triggerCls</tt> will be <b>appended</b> if specified.
98508      * Defaults to 'x-form-arrow-trigger' for ComboBox.
98509      */
98510     triggerCls: Ext.baseCSSPrefix + 'form-arrow-trigger',
98511
98512     /**
98513      * @cfg {Ext.data.Store/Array} store The data source to which this combo is bound (defaults to <tt>undefined</tt>).
98514      * Acceptable values for this property are:
98515      * <div class="mdetail-params"><ul>
98516      * <li><b>any {@link Ext.data.Store Store} subclass</b></li>
98517      * <li><b>an Array</b> : Arrays will be converted to a {@link Ext.data.Store} internally,
98518      * automatically generating {@link Ext.data.Field#name field names} to work with all data components.
98519      * <div class="mdetail-params"><ul>
98520      * <li><b>1-dimensional array</b> : (e.g., <tt>['Foo','Bar']</tt>)<div class="sub-desc">
98521      * A 1-dimensional array will automatically be expanded (each array item will be used for both the combo
98522      * {@link #valueField} and {@link #displayField})</div></li>
98523      * <li><b>2-dimensional array</b> : (e.g., <tt>[['f','Foo'],['b','Bar']]</tt>)<div class="sub-desc">
98524      * For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo
98525      * {@link #valueField}, while the value at index 1 is assumed to be the combo {@link #displayField}.
98526      * </div></li></ul></div></li></ul></div>
98527      * <p>See also <tt>{@link #queryMode}</tt>.</p>
98528      */
98529
98530     /**
98531      * @cfg {Boolean} multiSelect
98532      * If set to <tt>true</tt>, allows the combo field to hold more than one value at a time, and allows selecting
98533      * multiple items from the dropdown list. The combo's text field will show all selected values separated by
98534      * the {@link #delimiter}. (Defaults to <tt>false</tt>.)
98535      */
98536     multiSelect: false,
98537
98538     /**
98539      * @cfg {String} delimiter
98540      * The character(s) used to separate the {@link #displayField display values} of multiple selected items
98541      * when <tt>{@link #multiSelect} = true</tt>. Defaults to <tt>', '</tt>.
98542      */
98543     delimiter: ', ',
98544
98545     /**
98546      * @cfg {String} displayField The underlying {@link Ext.data.Field#name data field name} to bind to this
98547      * ComboBox (defaults to 'text').
98548      * <p>See also <tt>{@link #valueField}</tt>.</p>
98549      */
98550     displayField: 'text',
98551
98552     /**
98553      * @cfg {String} valueField
98554      * @required
98555      * The underlying {@link Ext.data.Field#name data value name} to bind to this ComboBox (defaults to match
98556      * the value of the {@link #displayField} config).
98557      * <p><b>Note</b>: use of a <tt>valueField</tt> requires the user to make a selection in order for a value to be
98558      * mapped. See also <tt>{@link #displayField}</tt>.</p>
98559      */
98560
98561     /**
98562      * @cfg {String} triggerAction The action to execute when the trigger is clicked.
98563      * <div class="mdetail-params"><ul>
98564      * <li><b><tt>'all'</tt></b> : <b>Default</b>
98565      * <p class="sub-desc">{@link #doQuery run the query} specified by the <tt>{@link #allQuery}</tt> config option</p></li>
98566      * <li><b><tt>'query'</tt></b> :
98567      * <p class="sub-desc">{@link #doQuery run the query} using the {@link Ext.form.field.Base#getRawValue raw value}.</p></li>
98568      * </ul></div>
98569      * <p>See also <code>{@link #queryParam}</code>.</p>
98570      */
98571     triggerAction: 'all',
98572
98573     /**
98574      * @cfg {String} allQuery The text query to send to the server to return all records for the list
98575      * with no filtering (defaults to '')
98576      */
98577     allQuery: '',
98578
98579     /**
98580      * @cfg {String} queryParam Name of the query ({@link Ext.data.Store#baseParam baseParam} name for the store)
98581      * as it will be passed on the querystring (defaults to <tt>'query'</tt>)
98582      */
98583     queryParam: 'query',
98584
98585     /**
98586      * @cfg {String} queryMode
98587      * The mode for queries. Acceptable values are:
98588      * <div class="mdetail-params"><ul>
98589      * <li><b><tt>'remote'</tt></b> : <b>Default</b>
98590      * <p class="sub-desc">Automatically loads the <tt>{@link #store}</tt> the <b>first</b> time the trigger
98591      * is clicked. If you do not want the store to be automatically loaded the first time the trigger is
98592      * clicked, set to <tt>'local'</tt> and manually load the store.  To force a requery of the store
98593      * <b>every</b> time the trigger is clicked see <tt>{@link #lastQuery}</tt>.</p></li>
98594      * <li><b><tt>'local'</tt></b> :
98595      * <p class="sub-desc">ComboBox loads local data</p>
98596      * <pre><code>
98597 var combo = new Ext.form.field.ComboBox({
98598     renderTo: document.body,
98599     queryMode: 'local',
98600     store: new Ext.data.ArrayStore({
98601         id: 0,
98602         fields: [
98603             'myId',  // numeric value is the key
98604             'displayText'
98605         ],
98606         data: [[1, 'item1'], [2, 'item2']]  // data is local
98607     }),
98608     valueField: 'myId',
98609     displayField: 'displayText',
98610     triggerAction: 'all'
98611 });
98612      * </code></pre></li>
98613      * </ul></div>
98614      */
98615     queryMode: 'remote',
98616
98617     queryCaching: true,
98618
98619     /**
98620      * @cfg {Number} pageSize If greater than <tt>0</tt>, a {@link Ext.toolbar.Paging} is displayed in the
98621      * footer of the dropdown list and the {@link #doQuery filter queries} will execute with page start and
98622      * {@link Ext.toolbar.Paging#pageSize limit} parameters. Only applies when <tt>{@link #queryMode} = 'remote'</tt>
98623      * (defaults to <tt>0</tt>).
98624      */
98625     pageSize: 0,
98626
98627     /**
98628      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and
98629      * sending the query to filter the dropdown list (defaults to <tt>500</tt> if <tt>{@link #queryMode} = 'remote'</tt>
98630      * or <tt>10</tt> if <tt>{@link #queryMode} = 'local'</tt>)
98631      */
98632
98633     /**
98634      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and
98635      * {@link #typeAhead} activate (defaults to <tt>4</tt> if <tt>{@link #queryMode} = 'remote'</tt> or <tt>0</tt> if
98636      * <tt>{@link #queryMode} = 'local'</tt>, does not apply if <tt>{@link Ext.form.field.Trigger#editable editable} = false</tt>).
98637      */
98638
98639     /**
98640      * @cfg {Boolean} autoSelect <tt>true</tt> to select the first result gathered by the data store (defaults
98641      * to <tt>true</tt>).  A false value would require a manual selection from the dropdown list to set the components value
98642      * unless the value of ({@link #typeAhead}) were true.
98643      */
98644     autoSelect: true,
98645
98646     /**
98647      * @cfg {Boolean} typeAhead <tt>true</tt> to populate and autoselect the remainder of the text being
98648      * typed after a configurable delay ({@link #typeAheadDelay}) if it matches a known value (defaults
98649      * to <tt>false</tt>)
98650      */
98651     typeAhead: false,
98652
98653     /**
98654      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
98655      * if <tt>{@link #typeAhead} = true</tt> (defaults to <tt>250</tt>)
98656      */
98657     typeAheadDelay: 250,
98658
98659     /**
98660      * @cfg {Boolean} selectOnTab
98661      * Whether the Tab key should select the currently highlighted item. Defaults to <tt>true</tt>.
98662      */
98663     selectOnTab: true,
98664
98665     /**
98666      * @cfg {Boolean} forceSelection <tt>true</tt> to restrict the selected value to one of the values in the list,
98667      * <tt>false</tt> to allow the user to set arbitrary text into the field (defaults to <tt>false</tt>)
98668      */
98669     forceSelection: false,
98670
98671     /**
98672      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
98673      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined). If this
98674      * default text is used, it means there is no value set and no validation will occur on this field.
98675      */
98676
98677     /**
98678      * The value of the match string used to filter the store. Delete this property to force a requery.
98679      * Example use:
98680      * <pre><code>
98681 var combo = new Ext.form.field.ComboBox({
98682     ...
98683     queryMode: 'remote',
98684     listeners: {
98685         // delete the previous query in the beforequery event or set
98686         // combo.lastQuery = null (this will reload the store the next time it expands)
98687         beforequery: function(qe){
98688             delete qe.combo.lastQuery;
98689         }
98690     }
98691 });
98692      * </code></pre>
98693      * To make sure the filter in the store is not cleared the first time the ComboBox trigger is used
98694      * configure the combo with <tt>lastQuery=''</tt>. Example use:
98695      * <pre><code>
98696 var combo = new Ext.form.field.ComboBox({
98697     ...
98698     queryMode: 'local',
98699     triggerAction: 'all',
98700     lastQuery: ''
98701 });
98702      * </code></pre>
98703      * @property lastQuery
98704      * @type String
98705      */
98706
98707     /**
98708      * @cfg {Object} defaultListConfig
98709      * Set of options that will be used as defaults for the user-configured {@link #listConfig} object.
98710      */
98711     defaultListConfig: {
98712         emptyText: '',
98713         loadingText: 'Loading...',
98714         loadingHeight: 70,
98715         minWidth: 70,
98716         maxHeight: 300,
98717         shadow: 'sides'
98718     },
98719
98720     /**
98721      * @cfg {Mixed} transform
98722      * The id, DOM node or {@link Ext.core.Element} of an existing HTML <tt>&lt;select&gt;</tt> element to
98723      * convert into a ComboBox. The target select's options will be used to build the options in the ComboBox
98724      * dropdown; a configured {@link #store} will take precedence over this.
98725      */
98726
98727     /**
98728      * @cfg {Object} listConfig
98729      * <p>An optional set of configuration properties that will be passed to the {@link Ext.view.BoundList}'s
98730      * constructor. Any configuration that is valid for BoundList can be included. Some of the more useful
98731      * ones are:</p>
98732      * <ul>
98733      *     <li>{@link Ext.view.BoundList#cls} - defaults to empty</li>
98734      *     <li>{@link Ext.view.BoundList#emptyText} - defaults to empty string</li>
98735      *     <li>{@link Ext.view.BoundList#getInnerTpl} - defaults to the template defined in BoundList</li>
98736      *     <li>{@link Ext.view.BoundList#itemSelector} - defaults to the value defined in BoundList</li>
98737      *     <li>{@link Ext.view.BoundList#loadingText} - defaults to <tt>'Loading...'</tt></li>
98738      *     <li>{@link Ext.view.BoundList#minWidth} - defaults to <tt>70</tt></li>
98739      *     <li>{@link Ext.view.BoundList#maxWidth} - defaults to <tt>undefined</tt></li>
98740      *     <li>{@link Ext.view.BoundList#maxHeight} - defaults to <tt>300</tt></li>
98741      *     <li>{@link Ext.view.BoundList#resizable} - defaults to <tt>false</tt></li>
98742      *     <li>{@link Ext.view.BoundList#shadow} - defaults to <tt>'sides'</tt></li>
98743      *     <li>{@link Ext.view.BoundList#width} - defaults to <tt>undefined</tt> (automatically set to the width
98744      *         of the ComboBox field if {@link #matchFieldWidth} is true)</li>
98745      * </ul>
98746      */
98747
98748     //private
98749     ignoreSelection: 0,
98750
98751     initComponent: function() {
98752         var me = this,
98753             isDefined = Ext.isDefined,
98754             store = me.store,
98755             transform = me.transform,
98756             transformSelect, isLocalMode;
98757
98758         if (!store && !transform) {
98759             Ext.Error.raise('Either a valid store, or a HTML select to transform, must be configured on the combo.');
98760         }
98761         if (me.typeAhead && me.multiSelect) {
98762             Ext.Error.raise('typeAhead and multiSelect are mutually exclusive options -- please remove one of them.');
98763         }
98764         if (me.typeAhead && !me.editable) {
98765             Ext.Error.raise('If typeAhead is enabled the combo must be editable: true -- please change one of those settings.');
98766         }
98767         if (me.selectOnFocus && !me.editable) {
98768             Ext.Error.raise('If selectOnFocus is enabled the combo must be editable: true -- please change one of those settings.');
98769         }
98770
98771         this.addEvents(
98772             // TODO need beforeselect?
98773
98774             /**
98775              * @event beforequery
98776              * Fires before all queries are processed. Return false to cancel the query or set the queryEvent's
98777              * cancel property to true.
98778              * @param {Object} queryEvent An object that has these properties:<ul>
98779              * <li><code>combo</code> : Ext.form.field.ComboBox <div class="sub-desc">This combo box</div></li>
98780              * <li><code>query</code> : String <div class="sub-desc">The query string</div></li>
98781              * <li><code>forceAll</code> : Boolean <div class="sub-desc">True to force "all" query</div></li>
98782              * <li><code>cancel</code> : Boolean <div class="sub-desc">Set to true to cancel the query</div></li>
98783              * </ul>
98784              */
98785             'beforequery',
98786
98787             /*
98788              * @event select
98789              * Fires when at least one list item is selected.
98790              * @param {Ext.form.field.ComboBox} combo This combo box
98791              * @param {Array} records The selected records
98792              */
98793             'select'
98794         );
98795
98796         // Build store from 'transform' HTML select element's options
98797         if (!store && transform) {
98798             transformSelect = Ext.getDom(transform);
98799             if (transformSelect) {
98800                 store = Ext.Array.map(Ext.Array.from(transformSelect.options), function(option) {
98801                     return [option.value, option.text];
98802                 });
98803                 if (!me.name) {
98804                     me.name = transformSelect.name;
98805                 }
98806                 if (!('value' in me)) {
98807                     me.value = transformSelect.value;
98808                 }
98809             }
98810         }
98811
98812         me.bindStore(store, true);
98813         store = me.store;
98814         if (store.autoCreated) {
98815             me.queryMode = 'local';
98816             me.valueField = me.displayField = 'field1';
98817             if (!store.expanded) {
98818                 me.displayField = 'field2';
98819             }
98820         }
98821
98822
98823         if (!isDefined(me.valueField)) {
98824             me.valueField = me.displayField;
98825         }
98826
98827         isLocalMode = me.queryMode === 'local';
98828         if (!isDefined(me.queryDelay)) {
98829             me.queryDelay = isLocalMode ? 10 : 500;
98830         }
98831         if (!isDefined(me.minChars)) {
98832             me.minChars = isLocalMode ? 0 : 4;
98833         }
98834
98835         if (!me.displayTpl) {
98836             me.displayTpl = Ext.create('Ext.XTemplate',
98837                 '<tpl for=".">' +
98838                     '{[typeof values === "string" ? values : values.' + me.displayField + ']}' +
98839                     '<tpl if="xindex < xcount">' + me.delimiter + '</tpl>' +
98840                 '</tpl>'
98841             );
98842         } else if (Ext.isString(me.displayTpl)) {
98843             me.displayTpl = Ext.create('Ext.XTemplate', me.displayTpl);
98844         }
98845
98846         me.callParent();
98847
98848         me.doQueryTask = Ext.create('Ext.util.DelayedTask', me.doRawQuery, me);
98849
98850         // store has already been loaded, setValue
98851         if (me.store.getCount() > 0) {
98852             me.setValue(me.value);
98853         }
98854
98855         // render in place of 'transform' select
98856         if (transformSelect) {
98857             me.render(transformSelect.parentNode, transformSelect);
98858             Ext.removeNode(transformSelect);
98859             delete me.renderTo;
98860         }
98861     },
98862
98863     beforeBlur: function() {
98864         var me = this;
98865         me.doQueryTask.cancel();
98866         if (me.forceSelection) {
98867             me.assertValue();
98868         } else {
98869             me.collapse();
98870         }
98871     },
98872
98873     // private
98874     assertValue: function() {
98875         var me = this,
98876             value = me.getRawValue(),
98877             rec;
98878
98879         if (me.multiSelect) {
98880             // For multiselect, check that the current displayed value matches the current
98881             // selection, if it does not then revert to the most recent selection.
98882             if (value !== me.getDisplayValue()) {
98883                 me.setValue(me.lastSelection);
98884             }
98885         } else {
98886             // For single-select, match the displayed value to a record and select it,
98887             // if it does not match a record then revert to the most recent selection.
98888             rec = me.findRecordByDisplay(value);
98889             if (rec) {
98890                 me.select(rec);
98891             } else {
98892                 me.setValue(me.lastSelection);
98893             }
98894         }
98895         me.collapse();
98896     },
98897
98898     onTypeAhead: function() {
98899         var me = this,
98900             displayField = me.displayField,
98901             record = me.store.findRecord(displayField, me.getRawValue()),
98902             boundList = me.getPicker(),
98903             newValue, len, selStart;
98904
98905         if (record) {
98906             newValue = record.get(displayField);
98907             len = newValue.length;
98908             selStart = me.getRawValue().length;
98909
98910             boundList.highlightItem(boundList.getNode(record));
98911
98912             if (selStart !== 0 && selStart !== len) {
98913                 me.setRawValue(newValue);
98914                 me.selectText(selStart, newValue.length);
98915             }
98916         }
98917     },
98918
98919     // invoked when a different store is bound to this combo
98920     // than the original
98921     resetToDefault: function() {
98922
98923     },
98924
98925     bindStore: function(store, initial) {
98926         var me = this,
98927             oldStore = me.store;
98928
98929         // this code directly accesses this.picker, bc invoking getPicker
98930         // would create it when we may be preping to destroy it
98931         if (oldStore && !initial) {
98932             if (oldStore !== store && oldStore.autoDestroy) {
98933                 oldStore.destroy();
98934             } else {
98935                 oldStore.un({
98936                     scope: me,
98937                     load: me.onLoad,
98938                     exception: me.collapse
98939                 });
98940             }
98941             if (!store) {
98942                 me.store = null;
98943                 if (me.picker) {
98944                     me.picker.bindStore(null);
98945                 }
98946             }
98947         }
98948         if (store) {
98949             if (!initial) {
98950                 me.resetToDefault();
98951             }
98952
98953             me.store = Ext.data.StoreManager.lookup(store);
98954             me.store.on({
98955                 scope: me,
98956                 load: me.onLoad,
98957                 exception: me.collapse
98958             });
98959
98960             if (me.picker) {
98961                 me.picker.bindStore(store);
98962             }
98963         }
98964     },
98965
98966     onLoad: function() {
98967         var me = this,
98968             value = me.value;
98969
98970         me.syncSelection();
98971         if (me.picker && !me.picker.getSelectionModel().hasSelection()) {
98972             me.doAutoSelect();
98973         }
98974     },
98975
98976     /**
98977      * @private
98978      * Execute the query with the raw contents within the textfield.
98979      */
98980     doRawQuery: function() {
98981         this.doQuery(this.getRawValue());
98982     },
98983
98984     /**
98985      * Executes a query to filter the dropdown list. Fires the {@link #beforequery} event prior to performing the
98986      * query allowing the query action to be canceled if needed.
98987      * @param {String} queryString The SQL query to execute
98988      * @param {Boolean} forceAll <tt>true</tt> to force the query to execute even if there are currently fewer
98989      * characters in the field than the minimum specified by the <tt>{@link #minChars}</tt> config option.  It
98990      * also clears any filter previously saved in the current store (defaults to <tt>false</tt>)
98991      * @return {Boolean} true if the query was permitted to run, false if it was cancelled by a {@link #beforequery} handler.
98992      */
98993     doQuery: function(queryString, forceAll) {
98994         queryString = queryString || '';
98995
98996         // store in object and pass by reference in 'beforequery'
98997         // so that client code can modify values.
98998         var me = this,
98999             qe = {
99000                 query: queryString,
99001                 forceAll: forceAll,
99002                 combo: me,
99003                 cancel: false
99004             },
99005             store = me.store,
99006             isLocalMode = me.queryMode === 'local';
99007
99008         if (me.fireEvent('beforequery', qe) === false || qe.cancel) {
99009             return false;
99010         }
99011
99012         // get back out possibly modified values
99013         queryString = qe.query;
99014         forceAll = qe.forceAll;
99015
99016         // query permitted to run
99017         if (forceAll || (queryString.length >= me.minChars)) {
99018             // expand before starting query so LoadMask can position itself correctly
99019             me.expand();
99020
99021             // make sure they aren't querying the same thing
99022             if (!me.queryCaching || me.lastQuery !== queryString) {
99023                 me.lastQuery = queryString;
99024                 store.clearFilter(!forceAll);
99025                 if (isLocalMode) {
99026                     if (!forceAll) {
99027                         store.filter(me.displayField, queryString);
99028                     }
99029                 } else {
99030                     store.load({
99031                         params: me.getParams(queryString)
99032                     });
99033                 }
99034             }
99035
99036             // Clear current selection if it does not match the current value in the field
99037             if (me.getRawValue() !== me.getDisplayValue()) {
99038                 me.ignoreSelection++;
99039                 me.picker.getSelectionModel().deselectAll();
99040                 me.ignoreSelection--;
99041             }
99042
99043             if (isLocalMode) {
99044                 me.doAutoSelect();
99045             }
99046             if (me.typeAhead) {
99047                 me.doTypeAhead();
99048             }
99049         }
99050         return true;
99051     },
99052
99053     // private
99054     getParams: function(queryString) {
99055         var p = {},
99056             pageSize = this.pageSize;
99057         p[this.queryParam] = queryString;
99058         if (pageSize) {
99059             p.start = 0;
99060             p.limit = pageSize;
99061         }
99062         return p;
99063     },
99064
99065     /**
99066      * @private
99067      * If the autoSelect config is true, and the picker is open, highlights the first item.
99068      */
99069     doAutoSelect: function() {
99070         var me = this,
99071             picker = me.picker,
99072             lastSelected, itemNode;
99073         if (picker && me.autoSelect && me.store.getCount() > 0) {
99074             // Highlight the last selected item and scroll it into view
99075             lastSelected = picker.getSelectionModel().lastSelected;
99076             itemNode = picker.getNode(lastSelected || 0);
99077             if (itemNode) {
99078                 picker.highlightItem(itemNode);
99079                 picker.listEl.scrollChildIntoView(itemNode, false);
99080             }
99081         }
99082     },
99083
99084     doTypeAhead: function() {
99085         if (!this.typeAheadTask) {
99086             this.typeAheadTask = Ext.create('Ext.util.DelayedTask', this.onTypeAhead, this);
99087         }
99088         if (this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE) {
99089             this.typeAheadTask.delay(this.typeAheadDelay);
99090         }
99091     },
99092
99093     onTriggerClick: function() {
99094         var me = this;
99095         if (!me.readOnly && !me.disabled) {
99096             if (me.isExpanded) {
99097                 me.collapse();
99098             } else {
99099                 me.onFocus({});
99100                 if (me.triggerAction === 'all') {
99101                     me.doQuery(me.allQuery, true);
99102                 } else {
99103                     me.doQuery(me.getRawValue());
99104                 }
99105             }
99106             me.inputEl.focus();
99107         }
99108     },
99109
99110
99111     // store the last key and doQuery if relevant
99112     onKeyUp: function(e, t) {
99113         var me = this,
99114             key = e.getKey();
99115
99116         if (!me.readOnly && !me.disabled && me.editable) {
99117             me.lastKey = key;
99118             // we put this in a task so that we can cancel it if a user is
99119             // in and out before the queryDelay elapses
99120
99121             // perform query w/ any normal key or backspace or delete
99122             if (!e.isSpecialKey() || key == e.BACKSPACE || key == e.DELETE) {
99123                 me.doQueryTask.delay(me.queryDelay);
99124             }
99125         }
99126     },
99127
99128     initEvents: function() {
99129         var me = this;
99130         me.callParent();
99131
99132         // setup keyboard handling
99133         me.mon(me.inputEl, 'keyup', me.onKeyUp, me);
99134     },
99135
99136     createPicker: function() {
99137         var me = this,
99138             picker,
99139             menuCls = Ext.baseCSSPrefix + 'menu',
99140             opts = Ext.apply({
99141                 selModel: {
99142                     mode: me.multiSelect ? 'SIMPLE' : 'SINGLE'
99143                 },
99144                 floating: true,
99145                 hidden: true,
99146                 ownerCt: me.ownerCt,
99147                 cls: me.el.up('.' + menuCls) ? menuCls : '',
99148                 store: me.store,
99149                 displayField: me.displayField,
99150                 focusOnToFront: false,
99151                 pageSize: me.pageSize
99152             }, me.listConfig, me.defaultListConfig);
99153
99154         picker = me.picker = Ext.create('Ext.view.BoundList', opts);
99155
99156         me.mon(picker, {
99157             itemclick: me.onItemClick,
99158             refresh: me.onListRefresh,
99159             scope: me
99160         });
99161
99162         me.mon(picker.getSelectionModel(), {
99163             selectionChange: me.onListSelectionChange,
99164             scope: me
99165         });
99166
99167         return picker;
99168     },
99169
99170     onListRefresh: function() {
99171         this.alignPicker();
99172         this.syncSelection();
99173     },
99174     
99175     onItemClick: function(picker, record){
99176         /*
99177          * If we're doing single selection, the selection change events won't fire when
99178          * clicking on the selected element. Detect it here.
99179          */
99180         var me = this,
99181             lastSelection = me.lastSelection,
99182             valueField = me.valueField,
99183             selected;
99184         
99185         if (!me.multiSelect && lastSelection) {
99186             selected = lastSelection[0];
99187             if (record.get(valueField) === selected.get(valueField)) {
99188                 me.collapse();
99189             }
99190         }   
99191     },
99192
99193     onListSelectionChange: function(list, selectedRecords) {
99194         var me = this;
99195         // Only react to selection if it is not called from setValue, and if our list is
99196         // expanded (ignores changes to the selection model triggered elsewhere)
99197         if (!me.ignoreSelection && me.isExpanded) {
99198             if (!me.multiSelect) {
99199                 Ext.defer(me.collapse, 1, me);
99200             }
99201             me.setValue(selectedRecords, false);
99202             if (selectedRecords.length > 0) {
99203                 me.fireEvent('select', me, selectedRecords);
99204             }
99205             me.inputEl.focus();
99206         }
99207     },
99208
99209     /**
99210      * @private
99211      * Enables the key nav for the BoundList when it is expanded.
99212      */
99213     onExpand: function() {
99214         var me = this,
99215             keyNav = me.listKeyNav,
99216             selectOnTab = me.selectOnTab,
99217             picker = me.getPicker();
99218
99219         // Handle BoundList navigation from the input field. Insert a tab listener specially to enable selectOnTab.
99220         if (keyNav) {
99221             keyNav.enable();
99222         } else {
99223             keyNav = me.listKeyNav = Ext.create('Ext.view.BoundListKeyNav', this.inputEl, {
99224                 boundList: picker,
99225                 forceKeyDown: true,
99226                 tab: function(e) {
99227                     if (selectOnTab) {
99228                         this.selectHighlighted(e);
99229                         me.triggerBlur();
99230                     }
99231                     // Tab key event is allowed to propagate to field
99232                     return true;
99233                 }
99234             });
99235         }
99236
99237         // While list is expanded, stop tab monitoring from Ext.form.field.Trigger so it doesn't short-circuit selectOnTab
99238         if (selectOnTab) {
99239             me.ignoreMonitorTab = true;
99240         }
99241
99242         Ext.defer(keyNav.enable, 1, keyNav); //wait a bit so it doesn't react to the down arrow opening the picker
99243         me.inputEl.focus();
99244     },
99245
99246     /**
99247      * @private
99248      * Disables the key nav for the BoundList when it is collapsed.
99249      */
99250     onCollapse: function() {
99251         var me = this,
99252             keyNav = me.listKeyNav;
99253         if (keyNav) {
99254             keyNav.disable();
99255             me.ignoreMonitorTab = false;
99256         }
99257     },
99258
99259     /**
99260      * Selects an item by a {@link Ext.data.Model Model}, or by a key value.
99261      * @param r
99262      */
99263     select: function(r) {
99264         this.setValue(r, true);
99265     },
99266
99267     /**
99268      * Find the record by searching for a specific field/value combination
99269      * Returns an Ext.data.Record or false
99270      * @private
99271      */
99272     findRecord: function(field, value) {
99273         var ds = this.store,
99274             idx = ds.findExact(field, value);
99275         return idx !== -1 ? ds.getAt(idx) : false;
99276     },
99277     findRecordByValue: function(value) {
99278         return this.findRecord(this.valueField, value);
99279     },
99280     findRecordByDisplay: function(value) {
99281         return this.findRecord(this.displayField, value);
99282     },
99283
99284     /**
99285      * Sets the specified value(s) into the field. For each value, if a record is found in the {@link #store} that
99286      * matches based on the {@link #valueField}, then that record's {@link #displayField} will be displayed in the
99287      * field.  If no match is found, and the {@link #valueNotFoundText} config option is defined, then that will be
99288      * displayed as the default field text. Otherwise a blank value will be shown, although the value will still be set.
99289      * @param {String|Array} value The value(s) to be set. Can be either a single String or {@link Ext.data.Model},
99290      * or an Array of Strings or Models.
99291      * @return {Ext.form.field.Field} this
99292      */
99293     setValue: function(value, doSelect) {
99294         var me = this,
99295             valueNotFoundText = me.valueNotFoundText,
99296             inputEl = me.inputEl,
99297             i, len, record,
99298             models = [],
99299             displayTplData = [],
99300             processedValue = [];
99301
99302         if (me.store.loading) {
99303             // Called while the Store is loading. Ensure it is processed by the onLoad method.
99304             me.value = value;
99305             return me;
99306         }
99307
99308         // This method processes multi-values, so ensure value is an array.
99309         value = Ext.Array.from(value);
99310
99311         // Loop through values
99312         for (i = 0, len = value.length; i < len; i++) {
99313             record = value[i];
99314             if (!record || !record.isModel) {
99315                 record = me.findRecordByValue(record);
99316             }
99317             // record found, select it.
99318             if (record) {
99319                 models.push(record);
99320                 displayTplData.push(record.data);
99321                 processedValue.push(record.get(me.valueField));
99322             }
99323             // record was not found, this could happen because
99324             // store is not loaded or they set a value not in the store
99325             else {
99326                 // if valueNotFoundText is defined, display it, otherwise display nothing for this value
99327                 if (Ext.isDefined(valueNotFoundText)) {
99328                     displayTplData.push(valueNotFoundText);
99329                 }
99330                 processedValue.push(value[i]);
99331             }
99332         }
99333
99334         // Set the value of this field. If we are multiselecting, then that is an array.
99335         me.value = me.multiSelect ? processedValue : processedValue[0];
99336         if (!Ext.isDefined(me.value)) {
99337             me.value = null;
99338         }
99339         me.displayTplData = displayTplData; //store for getDisplayValue method
99340         me.lastSelection = me.valueModels = models;
99341
99342         if (inputEl && me.emptyText && !Ext.isEmpty(value)) {
99343             inputEl.removeCls(me.emptyCls);
99344         }
99345
99346         // Calculate raw value from the collection of Model data
99347         me.setRawValue(me.getDisplayValue());
99348         me.checkChange();
99349
99350         if (doSelect !== false) {
99351             me.syncSelection();
99352         }
99353         me.applyEmptyText();
99354
99355         return me;
99356     },
99357
99358     /**
99359      * @private Generate the string value to be displayed in the text field for the currently stored value
99360      */
99361     getDisplayValue: function() {
99362         return this.displayTpl.apply(this.displayTplData);
99363     },
99364
99365     getValue: function() {
99366         // If the user has not changed the raw field value since a value was selected from the list,
99367         // then return the structured value from the selection. If the raw field value is different
99368         // than what would be displayed due to selection, return that raw value.
99369         var me = this,
99370             picker = me.picker,
99371             rawValue = me.getRawValue(), //current value of text field
99372             value = me.value; //stored value from last selection or setValue() call
99373
99374         if (me.getDisplayValue() !== rawValue) {
99375             value = rawValue;
99376             me.value = me.displayTplData = me.valueModels = null;
99377             if (picker) {
99378                 me.ignoreSelection++;
99379                 picker.getSelectionModel().deselectAll();
99380                 me.ignoreSelection--;
99381             }
99382         }
99383
99384         return value;
99385     },
99386
99387     getSubmitValue: function() {
99388         return this.getValue();
99389     },
99390
99391     isEqual: function(v1, v2) {
99392         var fromArray = Ext.Array.from,
99393             i, len;
99394
99395         v1 = fromArray(v1);
99396         v2 = fromArray(v2);
99397         len = v1.length;
99398
99399         if (len !== v2.length) {
99400             return false;
99401         }
99402
99403         for(i = 0; i < len; i++) {
99404             if (v2[i] !== v1[i]) {
99405                 return false;
99406             }
99407         }
99408
99409         return true;
99410     },
99411
99412     /**
99413      * Clears any value currently set in the ComboBox.
99414      */
99415     clearValue: function() {
99416         this.setValue([]);
99417     },
99418
99419     /**
99420      * @private Synchronizes the selection in the picker to match the current value of the combobox.
99421      */
99422     syncSelection: function() {
99423         var me = this,
99424             ExtArray = Ext.Array,
99425             picker = me.picker,
99426             selection, selModel;
99427         if (picker) {
99428             // From the value, find the Models that are in the store's current data
99429             selection = [];
99430             ExtArray.forEach(me.valueModels || [], function(value) {
99431                 if (value && value.isModel && me.store.indexOf(value) >= 0) {
99432                     selection.push(value);
99433                 }
99434             });
99435
99436             // Update the selection to match
99437             me.ignoreSelection++;
99438             selModel = picker.getSelectionModel();
99439             selModel.deselectAll();
99440             if (selection.length) {
99441                 selModel.select(selection);
99442             }
99443             me.ignoreSelection--;
99444         }
99445     }
99446 });
99447
99448 /**
99449  * @private
99450  * @class Ext.picker.Month
99451  * @extends Ext.Component
99452  * <p>A month picker component. This class is used by the {@link Ext.picker.Date DatePicker} class
99453  * to allow browsing and selection of year/months combinations.</p>
99454  * @constructor
99455  * Create a new MonthPicker
99456  * @param {Object} config The config object
99457  * @xtype monthpicker
99458  * @private
99459  */
99460 Ext.define('Ext.picker.Month', {
99461     extend: 'Ext.Component',
99462     requires: ['Ext.XTemplate', 'Ext.util.ClickRepeater', 'Ext.Date', 'Ext.button.Button'],
99463     alias: 'widget.monthpicker',
99464     alternateClassName: 'Ext.MonthPicker',
99465
99466     renderTpl: [
99467         '<div class="{baseCls}-body">',
99468           '<div class="{baseCls}-months">',
99469               '<tpl for="months">',
99470                   '<div class="{parent.baseCls}-item {parent.baseCls}-month"><a href="#" hidefocus="on">{.}</a></div>',
99471               '</tpl>',
99472           '</div>',
99473           '<div class="{baseCls}-years">',
99474               '<div class="{baseCls}-yearnav">',
99475                   '<button class="{baseCls}-yearnav-prev"></button>',
99476                   '<button class="{baseCls}-yearnav-next"></button>',
99477               '</div>',
99478               '<tpl for="years">',
99479                   '<div class="{parent.baseCls}-item {parent.baseCls}-year"><a href="#" hidefocus="on">{.}</a></div>',
99480               '</tpl>',
99481           '</div>',
99482         '</div>',
99483         '<div class="' + Ext.baseCSSPrefix + 'clear"></div>',
99484         '<tpl if="showButtons">',
99485           '<div class="{baseCls}-buttons"></div>',
99486         '</tpl>'
99487     ],
99488
99489     /**
99490      * @cfg {String} okText The text to display on the ok button. Defaults to <tt>'OK'</tt>
99491      */
99492     okText: 'OK',
99493
99494     /**
99495      * @cfg {String} cancelText The text to display on the cancel button. Defaults to <tt>'Cancel'</tt>
99496      */
99497     cancelText: 'Cancel',
99498
99499     /**
99500      * @cfg {String} baseCls The base CSS class to apply to the picker element. Defaults to <tt>'x-monthpicker'</tt>
99501      */
99502     baseCls: Ext.baseCSSPrefix + 'monthpicker',
99503
99504     /**
99505      * @cfg {Boolean} showButtons True to show ok and cancel buttons below the picker. Defaults to <tt>true</tt>.
99506      */
99507     showButtons: true,
99508
99509     /**
99510      * @cfg {String} selectedCls The class to be added to selected items in the picker. Defaults to
99511      * <tt>'x-monthpicker-selected'</tt>
99512      */
99513
99514     /**
99515      * @cfg {Date/Array} value The default value to set. See {#setValue setValue}
99516      */
99517
99518     width: 175,
99519
99520     height: 195,
99521
99522
99523     // private
99524     totalYears: 10,
99525     yearOffset: 5, // 10 years in total, 2 per row
99526     monthOffset: 6, // 12 months, 2 per row
99527
99528     // private, inherit docs
99529     initComponent: function(){
99530         var me = this;
99531
99532         me.selectedCls = me.baseCls + '-selected';
99533         me.addEvents(
99534             /**
99535              * @event cancelclick
99536              * Fires when the cancel button is pressed.
99537              * @param {Ext.picker.Month} this
99538              */
99539             'cancelclick',
99540
99541             /**
99542              * @event monthclick
99543              * Fires when a month is clicked.
99544              * @param {Ext.picker.Month} this
99545              * @param {Array} value The current value
99546              */
99547             'monthclick',
99548
99549             /**
99550              * @event monthdblclick
99551              * Fires when a month is clicked.
99552              * @param {Ext.picker.Month} this
99553              * @param {Array} value The current value
99554              */
99555             'monthdblclick',
99556
99557             /**
99558              * @event okclick
99559              * Fires when the ok button is pressed.
99560              * @param {Ext.picker.Month} this
99561              * @param {Array} value The current value
99562              */
99563             'okclick',
99564
99565             /**
99566              * @event select
99567              * Fires when a month/year is selected.
99568              * @param {Ext.picker.Month} this
99569              * @param {Array} value The current value
99570              */
99571             'select',
99572
99573             /**
99574              * @event yearclick
99575              * Fires when a year is clicked.
99576              * @param {Ext.picker.Month} this
99577              * @param {Array} value The current value
99578              */
99579             'yearclick',
99580
99581             /**
99582              * @event yeardblclick
99583              * Fires when a year is clicked.
99584              * @param {Ext.picker.Month} this
99585              * @param {Array} value The current value
99586              */
99587             'yeardblclick'
99588         );
99589
99590         me.setValue(me.value);
99591         me.activeYear = me.getYear(new Date().getFullYear() - 4, -4);
99592         this.callParent();
99593     },
99594
99595     // private, inherit docs
99596     onRender: function(ct, position){
99597         var me = this,
99598             i = 0,
99599             months = [],
99600             shortName = Ext.Date.getShortMonthName,
99601             monthLen = me.monthOffset;
99602
99603         for (; i < monthLen; ++i) {
99604             months.push(shortName(i), shortName(i + monthLen));
99605         }
99606
99607         Ext.apply(me.renderData, {
99608             months: months,
99609             years: me.getYears(),
99610             showButtons: me.showButtons
99611         });
99612
99613         Ext.apply(me.renderSelectors, {
99614             bodyEl: '.' + me.baseCls + '-body',
99615             prevEl: '.' + me.baseCls + '-yearnav-prev',
99616             nextEl: '.' + me.baseCls + '-yearnav-next',
99617             buttonsEl: '.' + me.baseCls + '-buttons'
99618         });
99619         this.callParent([ct, position]);
99620     },
99621
99622     // private, inherit docs
99623     afterRender: function(){
99624         var me = this,
99625             body = me.bodyEl,
99626             buttonsEl = me.buttonsEl;
99627
99628         me.callParent();
99629
99630         me.mon(body, 'click', me.onBodyClick, me);
99631         me.mon(body, 'dblclick', me.onBodyClick, me);
99632
99633         // keep a reference to the year/month elements since we'll be re-using them
99634         me.years = body.select('.' + me.baseCls + '-year a');
99635         me.months = body.select('.' + me.baseCls + '-month a');
99636
99637         if (me.showButtons) {
99638             me.okBtn = Ext.create('Ext.button.Button', {
99639                 text: me.okText,
99640                 renderTo: buttonsEl,
99641                 handler: me.onOkClick,
99642                 scope: me
99643             });
99644             me.cancelBtn = Ext.create('Ext.button.Button', {
99645                 text: me.cancelText,
99646                 renderTo: buttonsEl,
99647                 handler: me.onCancelClick,
99648                 scope: me
99649             });
99650         }
99651
99652         me.backRepeater = Ext.create('Ext.util.ClickRepeater', me.prevEl, {
99653             handler: Ext.Function.bind(me.adjustYear, me, [-me.totalYears])
99654         });
99655
99656         me.prevEl.addClsOnOver(me.baseCls + '-yearnav-prev-over');
99657         me.nextRepeater = Ext.create('Ext.util.ClickRepeater', me.nextEl, {
99658             handler: Ext.Function.bind(me.adjustYear, me, [me.totalYears])
99659         });
99660         me.nextEl.addClsOnOver(me.baseCls + '-yearnav-next-over');
99661         me.updateBody();
99662     },
99663
99664     /**
99665      * Set the value for the picker.
99666      * @param {Date/Array} value The value to set. It can be a Date object, where the month/year will be extracted, or
99667      * it can be an array, with the month as the first index and the year as the second.
99668      * @return {Ext.picker.Month} this
99669      */
99670     setValue: function(value){
99671         var me = this,
99672             active = me.activeYear,
99673             offset = me.monthOffset,
99674             year,
99675             index;
99676
99677         if (!value) {
99678             me.value = [null, null];
99679         } else if (Ext.isDate(value)) {
99680             me.value = [value.getMonth(), value.getFullYear()];
99681         } else {
99682             me.value = [value[0], value[1]];
99683         }
99684
99685         if (me.rendered) {
99686             year = me.value[1];
99687             if (year !== null) {
99688                 if ((year < active || year > active + me.yearOffset)) {
99689                     me.activeYear = year - me.yearOffset + 1;
99690                 }
99691             }
99692             me.updateBody();
99693         }
99694
99695         return me;
99696     },
99697
99698     /**
99699      * Gets the selected value. It is returned as an array [month, year]. It may
99700      * be a partial value, for example [null, 2010]. The month is returned as
99701      * 0 based.
99702      * @return {Array} The selected value
99703      */
99704     getValue: function(){
99705         return this.value;
99706     },
99707
99708     /**
99709      * Checks whether the picker has a selection
99710      * @return {Boolean} Returns true if both a month and year have been selected
99711      */
99712     hasSelection: function(){
99713         var value = this.value;
99714         return value[0] !== null && value[1] !== null;
99715     },
99716
99717     /**
99718      * Get an array of years to be pushed in the template. It is not in strict
99719      * numerical order because we want to show them in columns.
99720      * @private
99721      * @return {Array} An array of years
99722      */
99723     getYears: function(){
99724         var me = this,
99725             offset = me.yearOffset,
99726             start = me.activeYear, // put the "active" year on the left
99727             end = start + offset,
99728             i = start,
99729             years = [];
99730
99731         for (; i < end; ++i) {
99732             years.push(i, i + offset);
99733         }
99734
99735         return years;
99736     },
99737
99738     /**
99739      * Update the years in the body based on any change
99740      * @private
99741      */
99742     updateBody: function(){
99743         var me = this,
99744             years = me.years,
99745             months = me.months,
99746             yearNumbers = me.getYears(),
99747             cls = me.selectedCls,
99748             value = me.getYear(null),
99749             month = me.value[0],
99750             monthOffset = me.monthOffset,
99751             year;
99752
99753         if (me.rendered) {
99754             years.removeCls(cls);
99755             months.removeCls(cls);
99756             years.each(function(el, all, index){
99757                 year = yearNumbers[index];
99758                 el.dom.innerHTML = year;
99759                 if (year == value) {
99760                     el.dom.className = cls;
99761                 }
99762             });
99763             if (month !== null) {
99764                 if (month < monthOffset) {
99765                     month = month * 2;
99766                 } else {
99767                     month = (month - monthOffset) * 2 + 1;
99768                 }
99769                 months.item(month).addCls(cls);
99770             }
99771         }
99772     },
99773
99774     /**
99775      * Gets the current year value, or the default.
99776      * @private
99777      * @param {Number} defaultValue The default value to use if the year is not defined.
99778      * @param {Number} offset A number to offset the value by
99779      * @return {Number} The year value
99780      */
99781     getYear: function(defaultValue, offset) {
99782         var year = this.value[1];
99783         offset = offset || 0;
99784         return year === null ? defaultValue : year + offset;
99785     },
99786
99787     /**
99788      * React to clicks on the body
99789      * @private
99790      */
99791     onBodyClick: function(e, t) {
99792         var me = this,
99793             isDouble = e.type == 'dblclick';
99794
99795         if (e.getTarget('.' + me.baseCls + '-month')) {
99796             e.stopEvent();
99797             me.onMonthClick(t, isDouble);
99798         } else if (e.getTarget('.' + me.baseCls + '-year')) {
99799             e.stopEvent();
99800             me.onYearClick(t, isDouble);
99801         }
99802     },
99803
99804     /**
99805      * Modify the year display by passing an offset.
99806      * @param {Number} offset The offset to move by. If not specified, it defaults to 10.
99807      */
99808     adjustYear: function(offset){
99809         if (typeof offset != 'number') {
99810             offset = this.totalYears;
99811         }
99812         this.activeYear += offset;
99813         this.updateBody();
99814     },
99815
99816     /**
99817      * React to the ok button being pressed
99818      * @private
99819      */
99820     onOkClick: function(){
99821         this.fireEvent('okclick', this, this.value);
99822     },
99823
99824     /**
99825      * React to the cancel button being pressed
99826      * @private
99827      */
99828     onCancelClick: function(){
99829         this.fireEvent('cancelclick', this);
99830     },
99831
99832     /**
99833      * React to a month being clicked
99834      * @private
99835      * @param {HTMLElement} target The element that was clicked
99836      * @param {Boolean} isDouble True if the event was a doubleclick
99837      */
99838     onMonthClick: function(target, isDouble){
99839         var me = this;
99840         me.value[0] = me.resolveOffset(me.months.indexOf(target), me.monthOffset);
99841         me.updateBody();
99842         me.fireEvent('month' + (isDouble ? 'dbl' : '') + 'click', me, me.value);
99843         me.fireEvent('select', me, me.value);
99844     },
99845
99846     /**
99847      * React to a year being clicked
99848      * @private
99849      * @param {HTMLElement} target The element that was clicked
99850      * @param {Boolean} isDouble True if the event was a doubleclick
99851      */
99852     onYearClick: function(target, isDouble){
99853         var me = this;
99854         me.value[1] = me.activeYear + me.resolveOffset(me.years.indexOf(target), me.yearOffset);
99855         me.updateBody();
99856         me.fireEvent('year' + (isDouble ? 'dbl' : '') + 'click', me, me.value);
99857         me.fireEvent('select', me, me.value);
99858
99859     },
99860
99861     /**
99862      * Returns an offsetted number based on the position in the collection. Since our collections aren't
99863      * numerically ordered, this function helps to normalize those differences.
99864      * @private
99865      * @param {Object} index
99866      * @param {Object} offset
99867      * @return {Number} The correctly offsetted number
99868      */
99869     resolveOffset: function(index, offset){
99870         if (index % 2 === 0) {
99871             return (index / 2);
99872         } else {
99873             return offset + Math.floor(index / 2);
99874         }
99875     },
99876
99877     // private, inherit docs
99878     beforeDestroy: function(){
99879         var me = this;
99880         me.years = me.months = null;
99881         Ext.destroyMembers('backRepeater', 'nextRepeater', 'okBtn', 'cancelBtn');
99882         this.callParent();
99883     }
99884 });
99885
99886 /**
99887  * @class Ext.picker.Date
99888  * @extends Ext.Component
99889  * <p>A date picker. This class is used by the {@link Ext.form.field.Date} field to allow browsing and
99890  * selection of valid dates in a popup next to the field, but may also be used with other components.</p>
99891  * <p>Typically you will need to implement a handler function to be notified when the user chooses a color from the
99892  * picker; you can register the handler using the {@link #select} event, or by implementing the {@link #handler}
99893  * method.</p>
99894  * <p>By default the user will be allowed to pick any date; this can be changed by using the {@link #minDate},
99895  * {@link #maxDate}, {@link #disabledDays}, {@link #disabledDatesRE}, and/or {@link #disabledDates} configs.</p>
99896  * <p>All the string values documented below may be overridden by including an Ext locale file in your page.</p>
99897  * <p>Example usage:</p>
99898  * <pre><code>new Ext.panel.Panel({
99899     title: 'Choose a future date:',
99900     width: 200,
99901     bodyPadding: 10,
99902     renderTo: Ext.getBody(),
99903     items: [{
99904         xtype: 'datepicker',
99905         minDate: new Date(),
99906         handler: function(picker, date) {
99907             // do something with the selected date
99908         }
99909     }]
99910 });</code></pre>
99911  * {@img Ext.picker.Date/Ext.picker.Date.png Ext.picker.Date component}
99912  *
99913  * @constructor
99914  * Create a new DatePicker
99915  * @param {Object} config The config object
99916  *
99917  * @xtype datepicker
99918  */
99919 Ext.define('Ext.picker.Date', {
99920     extend: 'Ext.Component',
99921     requires: [
99922         'Ext.XTemplate',
99923         'Ext.button.Button',
99924         'Ext.button.Split',
99925         'Ext.util.ClickRepeater',
99926         'Ext.util.KeyNav',
99927         'Ext.EventObject',
99928         'Ext.fx.Manager',
99929         'Ext.picker.Month'
99930     ],
99931     alias: 'widget.datepicker',
99932     alternateClassName: 'Ext.DatePicker',
99933
99934     renderTpl: [
99935         '<div class="{cls}" id="{id}" role="grid" title="{ariaTitle} {value:this.longDay}">',
99936             '<div role="presentation" class="{baseCls}-header">',
99937                 '<div class="{baseCls}-prev"><a href="#" role="button" title="{prevText}"></a></div>',
99938                 '<div class="{baseCls}-month"></div>',
99939                 '<div class="{baseCls}-next"><a href="#" role="button" title="{nextText}"></a></div>',
99940             '</div>',
99941             '<table class="{baseCls}-inner" cellspacing="0" role="presentation">',
99942                 '<thead role="presentation"><tr role="presentation">',
99943                     '<tpl for="dayNames">',
99944                         '<th role="columnheader" title="{.}"><span>{.:this.firstInitial}</span></th>',
99945                     '</tpl>',
99946                 '</tr></thead>',
99947                 '<tbody role="presentation"><tr role="presentation">',
99948                     '<tpl for="days">',
99949                         '{#:this.isEndOfWeek}',
99950                         '<td role="gridcell" id="{[Ext.id()]}">',
99951                             '<a role="presentation" href="#" hidefocus="on" class="{parent.baseCls}-date" tabIndex="1">',
99952                                 '<em role="presentation"><span role="presentation"></span></em>',
99953                             '</a>',
99954                         '</td>',
99955                     '</tpl>',
99956                 '</tr></tbody>',
99957             '</table>',
99958             '<tpl if="showToday">',
99959                 '<div role="presentation" class="{baseCls}-footer"></div>',
99960             '</tpl>',
99961         '</div>',
99962         {
99963             firstInitial: function(value) {
99964                 return value.substr(0,1);
99965             },
99966             isEndOfWeek: function(value) {
99967                 // convert from 1 based index to 0 based
99968                 // by decrementing value once.
99969                 value--;
99970                 var end = value % 7 === 0 && value !== 0;
99971                 return end ? '</tr><tr role="row">' : '';
99972             },
99973             longDay: function(value){
99974                 return Ext.Date.format(value, this.longDayFormat);
99975             }
99976         }
99977     ],
99978
99979     ariaTitle: 'Date Picker',
99980     /**
99981      * @cfg {String} todayText
99982      * The text to display on the button that selects the current date (defaults to <code>'Today'</code>)
99983      */
99984     todayText : 'Today',
99985     /**
99986      * @cfg {Function} handler
99987      * Optional. A function that will handle the select event of this picker.
99988      * The handler is passed the following parameters:<div class="mdetail-params"><ul>
99989      * <li><code>picker</code> : Ext.picker.Date <div class="sub-desc">This Date picker.</div></li>
99990      * <li><code>date</code> : Date <div class="sub-desc">The selected date.</div></li>
99991      * </ul></div>
99992      */
99993     /**
99994      * @cfg {Object} scope
99995      * The scope (<code><b>this</b></code> reference) in which the <code>{@link #handler}</code>
99996      * function will be called.  Defaults to this DatePicker instance.
99997      */
99998     /**
99999      * @cfg {String} todayTip
100000      * A string used to format the message for displaying in a tooltip over the button that
100001      * selects the current date. Defaults to <code>'{0} (Spacebar)'</code> where
100002      * the <code>{0}</code> token is replaced by today's date.
100003      */
100004     todayTip : '{0} (Spacebar)',
100005     /**
100006      * @cfg {String} minText
100007      * The error text to display if the minDate validation fails (defaults to <code>'This date is before the minimum date'</code>)
100008      */
100009     minText : 'This date is before the minimum date',
100010     /**
100011      * @cfg {String} maxText
100012      * The error text to display if the maxDate validation fails (defaults to <code>'This date is after the maximum date'</code>)
100013      */
100014     maxText : 'This date is after the maximum date',
100015     /**
100016      * @cfg {String} format
100017      * The default date format string which can be overriden for localization support.  The format must be
100018      * valid according to {@link Ext.Date#parse} (defaults to {@link Ext.Date#defaultFormat}).
100019      */
100020     /**
100021      * @cfg {String} disabledDaysText
100022      * The tooltip to display when the date falls on a disabled day (defaults to <code>'Disabled'</code>)
100023      */
100024     disabledDaysText : 'Disabled',
100025     /**
100026      * @cfg {String} disabledDatesText
100027      * The tooltip text to display when the date falls on a disabled date (defaults to <code>'Disabled'</code>)
100028      */
100029     disabledDatesText : 'Disabled',
100030     /**
100031      * @cfg {Array} monthNames
100032      * An array of textual month names which can be overriden for localization support (defaults to Ext.Date.monthNames)
100033      */
100034     /**
100035      * @cfg {Array} dayNames
100036      * An array of textual day names which can be overriden for localization support (defaults to Ext.Date.dayNames)
100037      */
100038     /**
100039      * @cfg {String} nextText
100040      * The next month navigation button tooltip (defaults to <code>'Next Month (Control+Right)'</code>)
100041      */
100042     nextText : 'Next Month (Control+Right)',
100043     /**
100044      * @cfg {String} prevText
100045      * The previous month navigation button tooltip (defaults to <code>'Previous Month (Control+Left)'</code>)
100046      */
100047     prevText : 'Previous Month (Control+Left)',
100048     /**
100049      * @cfg {String} monthYearText
100050      * The header month selector tooltip (defaults to <code>'Choose a month (Control+Up/Down to move years)'</code>)
100051      */
100052     monthYearText : 'Choose a month (Control+Up/Down to move years)',
100053     /**
100054      * @cfg {Number} startDay
100055      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
100056      */
100057     startDay : 0,
100058     /**
100059      * @cfg {Boolean} showToday
100060      * False to hide the footer area containing the Today button and disable the keyboard handler for spacebar
100061      * that selects the current date (defaults to <code>true</code>).
100062      */
100063     showToday : true,
100064     /**
100065      * @cfg {Date} minDate
100066      * Minimum allowable date (JavaScript date object, defaults to null)
100067      */
100068     /**
100069      * @cfg {Date} maxDate
100070      * Maximum allowable date (JavaScript date object, defaults to null)
100071      */
100072     /**
100073      * @cfg {Array} disabledDays
100074      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
100075      */
100076     /**
100077      * @cfg {RegExp} disabledDatesRE
100078      * JavaScript regular expression used to disable a pattern of dates (defaults to null).  The {@link #disabledDates}
100079      * config will generate this regex internally, but if you specify disabledDatesRE it will take precedence over the
100080      * disabledDates value.
100081      */
100082     /**
100083      * @cfg {Array} disabledDates
100084      * An array of 'dates' to disable, as strings. These strings will be used to build a dynamic regular
100085      * expression so they are very powerful. Some examples:
100086      * <ul>
100087      * <li>['03/08/2003', '09/16/2003'] would disable those exact dates</li>
100088      * <li>['03/08', '09/16'] would disable those days for every year</li>
100089      * <li>['^03/08'] would only match the beginning (useful if you are using short years)</li>
100090      * <li>['03/../2006'] would disable every day in March 2006</li>
100091      * <li>['^03'] would disable every day in every March</li>
100092      * </ul>
100093      * Note that the format of the dates included in the array should exactly match the {@link #format} config.
100094      * In order to support regular expressions, if you are using a date format that has '.' in it, you will have to
100095      * escape the dot when restricting dates. For example: ['03\\.08\\.03'].
100096      */
100097
100098     /**
100099      * @cfg {Boolean} disableAnim True to disable animations when showing the month picker. Defaults to <tt>false</tt>.
100100      */
100101     disableAnim: true,
100102
100103     /**
100104      * @cfg {String} baseCls
100105      * The base CSS class to apply to this components element (defaults to <tt>'x-datepicker'</tt>).
100106      */
100107     baseCls: Ext.baseCSSPrefix + 'datepicker',
100108
100109     /**
100110      * @cfg {String} selectedCls
100111      * The class to apply to the selected cell. Defaults to <tt>'x-datepicker-selected'</tt>
100112      */
100113
100114     /**
100115      * @cfg {String} disabledCellCls
100116      * The class to apply to disabled cells. Defaults to <tt>'x-datepicker-disabled'</tt>
100117      */
100118
100119     /**
100120      * @cfg {String} longDayFormat
100121      * The format for displaying a date in a longer format. Defaults to <tt>'F d, Y'</tt>
100122      */
100123     longDayFormat: 'F d, Y',
100124
100125     /**
100126      * @cfg {Object} keyNavConfig Specifies optional custom key event handlers for the {@link Ext.util.KeyNav}
100127      * attached to this date picker. Must conform to the config format recognized by the {@link Ext.util.KeyNav}
100128      * constructor. Handlers specified in this object will replace default handlers of the same name.
100129      */
100130
100131     /**
100132      * @cfg {Boolean} focusOnShow
100133      * True to automatically focus the picker on show. Defaults to <tt>false</tt>.
100134      */
100135     focusOnShow: false,
100136
100137     // private
100138     // Set by other components to stop the picker focus being updated when the value changes.
100139     focusOnSelect: true,
100140
100141     width: 178,
100142
100143     // default value used to initialise each date in the DatePicker
100144     // (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
100145     initHour: 12, // 24-hour format
100146
100147     numDays: 42,
100148
100149     // private, inherit docs
100150     initComponent : function() {
100151         var me = this,
100152             clearTime = Ext.Date.clearTime;
100153
100154         me.selectedCls = me.baseCls + '-selected';
100155         me.disabledCellCls = me.baseCls + '-disabled';
100156         me.prevCls = me.baseCls + '-prevday';
100157         me.activeCls = me.baseCls + '-active';
100158         me.nextCls = me.baseCls + '-prevday';
100159         me.todayCls = me.baseCls + '-today';
100160         me.dayNames = me.dayNames.slice(me.startDay).concat(me.dayNames.slice(0, me.startDay));
100161         this.callParent();
100162
100163         me.value = me.value ?
100164                  clearTime(me.value, true) : clearTime(new Date());
100165
100166         me.addEvents(
100167             /**
100168              * @event select
100169              * Fires when a date is selected
100170              * @param {DatePicker} this DatePicker
100171              * @param {Date} date The selected date
100172              */
100173             'select'
100174         );
100175
100176         me.initDisabledDays();
100177     },
100178
100179     // private, inherit docs
100180     onRender : function(container, position){
100181         /*
100182          * days array for looping through 6 full weeks (6 weeks * 7 days)
100183          * Note that we explicitly force the size here so the template creates
100184          * all the appropriate cells.
100185          */
100186
100187         var me = this,
100188             days = new Array(me.numDays),
100189             today = Ext.Date.format(new Date(), me.format);
100190
100191         Ext.applyIf(me, {
100192             renderData: {},
100193             renderSelectors: {}
100194         });
100195
100196         Ext.apply(me.renderData, {
100197             dayNames: me.dayNames,
100198             ariaTitle: me.ariaTitle,
100199             value: me.value,
100200             showToday: me.showToday,
100201             prevText: me.prevText,
100202             nextText: me.nextText,
100203             days: days
100204         });
100205         me.getTpl('renderTpl').longDayFormat = me.longDayFormat;
100206
100207         Ext.apply(me.renderSelectors, {
100208             eventEl: 'table.' + me.baseCls + '-inner',
100209             prevEl: '.' + me.baseCls + '-prev a',
100210             nextEl: '.' + me.baseCls + '-next a',
100211             middleBtnEl: '.' + me.baseCls + '-month',
100212             footerEl: '.' + me.baseCls + '-footer'
100213         });
100214
100215         this.callParent(arguments);
100216         me.el.unselectable();
100217
100218         me.cells = me.eventEl.select('tbody td');
100219         me.textNodes = me.eventEl.query('tbody td span');
100220
100221         me.monthBtn = Ext.create('Ext.button.Split', {
100222             text: '',
100223             tooltip: me.monthYearText,
100224             renderTo: me.middleBtnEl
100225         });
100226         //~ me.middleBtnEl.down('button').addCls(Ext.baseCSSPrefix + 'btn-arrow');
100227
100228
100229         me.todayBtn = Ext.create('Ext.button.Button', {
100230             renderTo: me.footerEl,
100231             text: Ext.String.format(me.todayText, today),
100232             tooltip: Ext.String.format(me.todayTip, today),
100233             handler: me.selectToday,
100234             scope: me
100235         });
100236     },
100237
100238     // private, inherit docs
100239     initEvents: function(){
100240         var me = this,
100241             eDate = Ext.Date,
100242             day = eDate.DAY;
100243
100244         this.callParent();
100245
100246         me.prevRepeater = Ext.create('Ext.util.ClickRepeater', me.prevEl, {
100247             handler: me.showPrevMonth,
100248             scope: me,
100249             preventDefault: true,
100250             stopDefault: true
100251         });
100252
100253         me.nextRepeater = Ext.create('Ext.util.ClickRepeater', me.nextEl, {
100254             handler: me.showNextMonth,
100255             scope: me,
100256             preventDefault:true,
100257             stopDefault:true
100258         });
100259
100260         me.keyNav = Ext.create('Ext.util.KeyNav', me.eventEl, Ext.apply({
100261             scope: me,
100262             'left' : function(e){
100263                 if(e.ctrlKey){
100264                     me.showPrevMonth();
100265                 }else{
100266                     me.update(eDate.add(me.activeDate, day, -1));
100267                 }
100268             },
100269
100270             'right' : function(e){
100271                 if(e.ctrlKey){
100272                     me.showNextMonth();
100273                 }else{
100274                     me.update(eDate.add(me.activeDate, day, 1));
100275                 }
100276             },
100277
100278             'up' : function(e){
100279                 if(e.ctrlKey){
100280                     me.showNextYear();
100281                 }else{
100282                     me.update(eDate.add(me.activeDate, day, -7));
100283                 }
100284             },
100285
100286             'down' : function(e){
100287                 if(e.ctrlKey){
100288                     me.showPrevYear();
100289                 }else{
100290                     me.update(eDate.add(me.activeDate, day, 7));
100291                 }
100292             },
100293             'pageUp' : me.showNextMonth,
100294             'pageDown' : me.showPrevMonth,
100295             'enter' : function(e){
100296                 e.stopPropagation();
100297                 return true;
100298             }
100299         }, me.keyNavConfig));
100300
100301         if(me.showToday){
100302             me.todayKeyListener = me.eventEl.addKeyListener(Ext.EventObject.SPACE, me.selectToday,  me);
100303         }
100304         me.mon(me.eventEl, 'mousewheel', me.handleMouseWheel, me);
100305         me.mon(me.eventEl, 'click', me.handleDateClick,  me, {delegate: 'a.' + me.baseCls + '-date'});
100306         me.mon(me.monthBtn, 'click', me.showMonthPicker, me);
100307         me.mon(me.monthBtn, 'arrowclick', me.showMonthPicker, me);
100308         me.update(me.value);
100309     },
100310
100311     /**
100312      * Setup the disabled dates regex based on config options
100313      * @private
100314      */
100315     initDisabledDays : function(){
100316         var me = this,
100317             dd = me.disabledDates,
100318             re = '(?:',
100319             len;
100320
100321         if(!me.disabledDatesRE && dd){
100322                 len = dd.length - 1;
100323
100324             Ext.each(dd, function(d, i){
100325                 re += Ext.isDate(d) ? '^' + Ext.String.escapeRegex(Ext.Date.dateFormat(d, me.format)) + '$' : dd[i];
100326                 if(i != len){
100327                     re += '|';
100328                 }
100329             }, me);
100330             me.disabledDatesRE = new RegExp(re + ')');
100331         }
100332     },
100333
100334     /**
100335      * Replaces any existing disabled dates with new values and refreshes the DatePicker.
100336      * @param {Array/RegExp} disabledDates An array of date strings (see the {@link #disabledDates} config
100337      * for details on supported values), or a JavaScript regular expression used to disable a pattern of dates.
100338      * @return {Ext.picker.Date} this
100339      */
100340     setDisabledDates : function(dd){
100341         var me = this;
100342
100343         if(Ext.isArray(dd)){
100344             me.disabledDates = dd;
100345             me.disabledDatesRE = null;
100346         }else{
100347             me.disabledDatesRE = dd;
100348         }
100349         me.initDisabledDays();
100350         me.update(me.value, true);
100351         return me;
100352     },
100353
100354     /**
100355      * Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
100356      * @param {Array} disabledDays An array of disabled day indexes. See the {@link #disabledDays} config
100357      * for details on supported values.
100358      * @return {Ext.picker.Date} this
100359      */
100360     setDisabledDays : function(dd){
100361         this.disabledDays = dd;
100362         return this.update(this.value, true);
100363     },
100364
100365     /**
100366      * Replaces any existing {@link #minDate} with the new value and refreshes the DatePicker.
100367      * @param {Date} value The minimum date that can be selected
100368      * @return {Ext.picker.Date} this
100369      */
100370     setMinDate : function(dt){
100371         this.minDate = dt;
100372         return this.update(this.value, true);
100373     },
100374
100375     /**
100376      * Replaces any existing {@link #maxDate} with the new value and refreshes the DatePicker.
100377      * @param {Date} value The maximum date that can be selected
100378      * @return {Ext.picker.Date} this
100379      */
100380     setMaxDate : function(dt){
100381         this.maxDate = dt;
100382         return this.update(this.value, true);
100383     },
100384
100385     /**
100386      * Sets the value of the date field
100387      * @param {Date} value The date to set
100388      * @return {Ext.picker.Date} this
100389      */
100390     setValue : function(value){
100391         this.value = Ext.Date.clearTime(value, true);
100392         return this.update(this.value);
100393     },
100394
100395     /**
100396      * Gets the current selected value of the date field
100397      * @return {Date} The selected date
100398      */
100399     getValue : function(){
100400         return this.value;
100401     },
100402
100403     // private
100404     focus : function(){
100405         this.update(this.activeDate);
100406     },
100407
100408     // private, inherit docs
100409     onEnable: function(){
100410         this.callParent();
100411         this.setDisabledStatus(false);
100412         this.update(this.activeDate);
100413
100414     },
100415
100416     // private, inherit docs
100417     onDisable : function(){
100418         this.callParent();
100419         this.setDisabledStatus(true);
100420     },
100421
100422     /**
100423      * Set the disabled state of various internal components
100424      * @private
100425      * @param {Boolean} disabled
100426      */
100427     setDisabledStatus : function(disabled){
100428         var me = this;
100429
100430         me.keyNav.setDisabled(disabled);
100431         me.prevRepeater.setDisabled(disabled);
100432         me.nextRepeater.setDisabled(disabled);
100433         if (me.showToday) {
100434             me.todayKeyListener.setDisabled(disabled);
100435             me.todayBtn.setDisabled(disabled);
100436         }
100437     },
100438
100439     /**
100440      * Get the current active date.
100441      * @private
100442      * @return {Date} The active date
100443      */
100444     getActive: function(){
100445         return this.activeDate || me.value;
100446     },
100447
100448     /**
100449      * Run any animation required to hide/show the month picker.
100450      * @private
100451      * @param {Boolean} isHide True if it's a hide operation
100452      */
100453     runAnimation: function(isHide){
100454         var options = {
100455                 target: this.monthPicker,
100456                 duration: 200
100457             };
100458
100459         Ext.fx.Manager.run();
100460         if (isHide) {
100461             //TODO: slideout
100462         } else {
100463             //TODO: slidein
100464         }
100465         Ext.create('Ext.fx.Anim', options);
100466     },
100467
100468     /**
100469      * Hides the month picker, if it's visible.
100470      * @return {Ext.picker.Date} this
100471      */
100472     hideMonthPicker : function(){
100473         var me = this,
100474             picker = me.monthPicker;
100475
100476         if (picker) {
100477             if (me.disableAnim) {
100478                 picker.hide();
100479             } else {
100480                 this.runAnimation(true);
100481             }
100482         }
100483         return me;
100484     },
100485
100486     /**
100487      * Show the month picker
100488      * @return {Ext.picker.Date} this
100489      */
100490     showMonthPicker : function(){
100491
100492         var me = this,
100493             picker,
100494             size,
100495             top,
100496             left;
100497
100498
100499         if (me.rendered && !me.disabled) {
100500             size = me.getSize();
100501             picker = me.createMonthPicker();
100502             picker.show();
100503             picker.setSize(size);
100504             picker.setValue(me.getActive());
100505
100506             if (me.disableAnim) {
100507                 picker.setPosition(-1, -1);
100508             } else {
100509                 me.runAnimation(false);
100510             }
100511         }
100512         return me;
100513     },
100514
100515     /**
100516      * Create the month picker instance
100517      * @private
100518      * @return {Ext.picker.Month} picker
100519      */
100520     createMonthPicker: function(){
100521         var me = this,
100522             picker = me.monthPicker;
100523
100524         if (!picker) {
100525             me.monthPicker = picker = Ext.create('Ext.picker.Month', {
100526                 renderTo: me.el,
100527                 floating: true,
100528                 shadow: false,
100529                 listeners: {
100530                     scope: me,
100531                     cancelclick: me.onCancelClick,
100532                     okclick: me.onOkClick,
100533                     yeardblclick: me.onOkClick,
100534                     monthdblclick: me.onOkClick
100535                 }
100536             });
100537
100538             me.on('beforehide', me.hideMonthPicker, me);
100539         }
100540         return picker;
100541     },
100542
100543     /**
100544      * Respond to an ok click on the month picker
100545      * @private
100546      */
100547     onOkClick: function(picker, value){
100548         var me = this,
100549             month = value[0],
100550             year = value[1],
100551             date = new Date(year, month, me.getActive().getDate());
100552
100553         if (date.getMonth() !== month) {
100554             // 'fix' the JS rolling date conversion if needed
100555             date = new Date(year, month, 1).getLastDateOfMonth();
100556         }
100557         me.update(date);
100558         me.hideMonthPicker();
100559     },
100560
100561     /**
100562      * Respond to a cancel click on the month picker
100563      * @private
100564      */
100565     onCancelClick: function(){
100566         this.hideMonthPicker();
100567     },
100568
100569     /**
100570      * Show the previous month.
100571      * @return {Ext.picker.Date} this
100572      */
100573     showPrevMonth : function(e){
100574         return this.update(Ext.Date.add(this.activeDate, Ext.Date.MONTH, -1));
100575     },
100576
100577     /**
100578      * Show the next month.
100579      * @return {Ext.picker.Date} this
100580      */
100581     showNextMonth : function(e){
100582         return this.update(Ext.Date.add(this.activeDate, Ext.Date.MONTH, 1));
100583     },
100584
100585     /**
100586      * Show the previous year.
100587      * @return {Ext.picker.Date} this
100588      */
100589     showPrevYear : function(){
100590         this.update(Ext.Date.add(this.activeDate, Ext.Date.YEAR, -1));
100591     },
100592
100593     /**
100594      * Show the next year.
100595      * @return {Ext.picker.Date} this
100596      */
100597     showNextYear : function(){
100598         this.update(Ext.Date.add(this.activeDate, Ext.Date.YEAR, 1));
100599     },
100600
100601     /**
100602      * Respond to the mouse wheel event
100603      * @private
100604      * @param {Ext.EventObject} e
100605      */
100606     handleMouseWheel : function(e){
100607         e.stopEvent();
100608         if(!this.disabled){
100609             var delta = e.getWheelDelta();
100610             if(delta > 0){
100611                 this.showPrevMonth();
100612             } else if(delta < 0){
100613                 this.showNextMonth();
100614             }
100615         }
100616     },
100617
100618     /**
100619      * Respond to a date being clicked in the picker
100620      * @private
100621      * @param {Ext.EventObject} e
100622      * @param {HTMLElement} t
100623      */
100624     handleDateClick : function(e, t){
100625         var me = this,
100626             handler = me.handler;
100627
100628         e.stopEvent();
100629         if(!me.disabled && t.dateValue && !Ext.fly(t.parentNode).hasCls(me.disabledCellCls)){
100630             me.cancelFocus = me.focusOnSelect === false;
100631             me.setValue(new Date(t.dateValue));
100632             delete me.cancelFocus;
100633             me.fireEvent('select', me, me.value);
100634             if (handler) {
100635                 handler.call(me.scope || me, me, me.value);
100636             }
100637             // event handling is turned off on hide
100638             // when we are using the picker in a field
100639             // therefore onSelect comes AFTER the select
100640             // event.
100641             me.onSelect();
100642         }
100643     },
100644
100645     /**
100646      * Perform any post-select actions
100647      * @private
100648      */
100649     onSelect: function() {
100650         if (this.hideOnSelect) {
100651              this.hide();
100652          }
100653     },
100654
100655     /**
100656      * Sets the current value to today.
100657      * @return {Ext.picker.Date} this
100658      */
100659     selectToday : function(){
100660         var me = this,
100661             btn = me.todayBtn,
100662             handler = me.handler;
100663
100664         if(btn && !btn.disabled){
100665             me.setValue(Ext.Date.clearTime(new Date()));
100666             me.fireEvent('select', me, me.value);
100667             if (handler) {
100668                 handler.call(me.scope || me, me, me.value);
100669             }
100670             me.onSelect();
100671         }
100672         return me;
100673     },
100674
100675     /**
100676      * Update the selected cell
100677      * @private
100678      * @param {Date} date The new date
100679      * @param {Date} active The active date
100680      */
100681     selectedUpdate: function(date, active){
100682         var me = this,
100683             t = date.getTime(),
100684             cells = me.cells,
100685             cls = me.selectedCls;
100686
100687         cells.removeCls(cls);
100688         cells.each(function(c){
100689             if (c.dom.firstChild.dateValue == t) {
100690                 me.el.dom.setAttribute('aria-activedescendent', c.dom.id);
100691                 c.addCls(cls);
100692                 if(me.isVisible() && !me.cancelFocus){
100693                     Ext.fly(c.dom.firstChild).focus(50);
100694                 }
100695                 return false;
100696             }
100697         }, this);
100698     },
100699
100700     /**
100701      * Update the contents of the picker for a new month
100702      * @private
100703      * @param {Date} date The new date
100704      * @param {Date} active The active date
100705      */
100706     fullUpdate: function(date, active){
100707         var me = this,
100708             cells = me.cells.elements,
100709             textNodes = me.textNodes,
100710             disabledCls = me.disabledCellCls,
100711             eDate = Ext.Date,
100712             i = 0,
100713             extraDays = 0,
100714             visible = me.isVisible(),
100715             sel = +eDate.clearTime(date, true),
100716             today = +eDate.clearTime(new Date()),
100717             min = me.minDate ? eDate.clearTime(me.minDate, true) : Number.NEGATIVE_INFINITY,
100718             max = me.maxDate ? eDate.clearTime(me.maxDate, true) : Number.POSITIVE_INFINITY,
100719             ddMatch = me.disabledDatesRE,
100720             ddText = me.disabledDatesText,
100721             ddays = me.disabledDays ? me.disabledDays.join('') : false,
100722             ddaysText = me.disabledDaysText,
100723             format = me.format,
100724             days = eDate.getDaysInMonth(date),
100725             firstOfMonth = eDate.getFirstDateOfMonth(date),
100726             startingPos = firstOfMonth.getDay() - me.startDay,
100727             previousMonth = eDate.add(date, eDate.MONTH, -1),
100728             longDayFormat = me.longDayFormat,
100729             prevStart,
100730             current,
100731             disableToday,
100732             tempDate,
100733             setCellClass,
100734             html,
100735             cls,
100736             formatValue,
100737             value;
100738
100739         if (startingPos < 0) {
100740             startingPos += 7;
100741         }
100742
100743         days += startingPos;
100744         prevStart = eDate.getDaysInMonth(previousMonth) - startingPos;
100745         current = new Date(previousMonth.getFullYear(), previousMonth.getMonth(), prevStart, me.initHour);
100746
100747         if (me.showToday) {
100748             tempDate = eDate.clearTime(new Date());
100749             disableToday = (tempDate < min || tempDate > max ||
100750                 (ddMatch && format && ddMatch.test(eDate.dateFormat(tempDate, format))) ||
100751                 (ddays && ddays.indexOf(tempDate.getDay()) != -1));
100752
100753             if (!me.disabled) {
100754                 me.todayBtn.setDisabled(disableToday);
100755                 me.todayKeyListener.setDisabled(disableToday);
100756             }
100757         }
100758
100759         setCellClass = function(cell){
100760             value = +eDate.clearTime(current, true);
100761             cell.title = eDate.format(current, longDayFormat);
100762             // store dateValue number as an expando
100763             cell.firstChild.dateValue = value;
100764             if(value == today){
100765                 cell.className += ' ' + me.todayCls;
100766                 cell.title = me.todayText;
100767             }
100768             if(value == sel){
100769                 cell.className += ' ' + me.selectedCls;
100770                 me.el.dom.setAttribute('aria-activedescendant', cell.id);
100771                 if (visible && me.floating) {
100772                     Ext.fly(cell.firstChild).focus(50);
100773                 }
100774             }
100775             // disabling
100776             if(value < min) {
100777                 cell.className = disabledCls;
100778                 cell.title = me.minText;
100779                 return;
100780             }
100781             if(value > max) {
100782                 cell.className = disabledCls;
100783                 cell.title = me.maxText;
100784                 return;
100785             }
100786             if(ddays){
100787                 if(ddays.indexOf(current.getDay()) != -1){
100788                     cell.title = ddaysText;
100789                     cell.className = disabledCls;
100790                 }
100791             }
100792             if(ddMatch && format){
100793                 formatValue = eDate.dateFormat(current, format);
100794                 if(ddMatch.test(formatValue)){
100795                     cell.title = ddText.replace('%0', formatValue);
100796                     cell.className = disabledCls;
100797                 }
100798             }
100799         };
100800
100801         for(; i < me.numDays; ++i) {
100802             if (i < startingPos) {
100803                 html = (++prevStart);
100804                 cls = me.prevCls;
100805             } else if (i >= days) {
100806                 html = (++extraDays);
100807                 cls = me.nextCls;
100808             } else {
100809                 html = i - startingPos + 1;
100810                 cls = me.activeCls;
100811             }
100812             textNodes[i].innerHTML = html;
100813             cells[i].className = cls;
100814             current.setDate(current.getDate() + 1);
100815             setCellClass(cells[i]);
100816         }
100817
100818         me.monthBtn.setText(me.monthNames[date.getMonth()] + ' ' + date.getFullYear());
100819     },
100820
100821     /**
100822      * Update the contents of the picker
100823      * @private
100824      * @param {Date} date The new date
100825      * @param {Boolean} forceRefresh True to force a full refresh
100826      */
100827     update : function(date, forceRefresh){
100828         var me = this,
100829             active = me.activeDate;
100830
100831         if (me.rendered) {
100832             me.activeDate = date;
100833             if(!forceRefresh && active && me.el && active.getMonth() == date.getMonth() && active.getFullYear() == date.getFullYear()){
100834                 me.selectedUpdate(date, active);
100835             } else {
100836                 me.fullUpdate(date, active);
100837             }
100838         }
100839         return me;
100840     },
100841
100842     // private, inherit docs
100843     beforeDestroy : function() {
100844         var me = this;
100845
100846         if (me.rendered) {
100847             Ext.destroy(
100848                 me.todayKeyListener,
100849                 me.keyNav,
100850                 me.monthPicker,
100851                 me.monthBtn,
100852                 me.nextRepeater,
100853                 me.prevRepeater,
100854                 me.todayBtn
100855             );
100856             delete me.textNodes;
100857             delete me.cells.elements;
100858         }
100859     },
100860
100861     // private, inherit docs
100862     onShow: function() {
100863         this.callParent(arguments);
100864         if (this.focusOnShow) {
100865             this.focus();
100866         }
100867     }
100868 },
100869
100870 // After dependencies have loaded:
100871 function() {
100872     var proto = this.prototype;
100873
100874     proto.monthNames = Ext.Date.monthNames;
100875
100876     proto.dayNames = Ext.Date.dayNames;
100877
100878     proto.format = Ext.Date.defaultFormat;
100879 });
100880
100881 /**
100882  * @class Ext.form.field.Date
100883  * @extends Ext.form.field.Picker
100884
100885 Provides a date input field with a {@link Ext.picker.Date date picker} dropdown and automatic date
100886 validation.
100887
100888 This field recognizes and uses the JavaScript Date object as its main {@link #value} type. In addition,
100889 it recognizes string values which are parsed according to the {@link #format} and/or {@link #altFormats}
100890 configs. These may be reconfigured to use date formats appropriate for the user's locale.
100891
100892 The field may be limited to a certain range of dates by using the {@link #minValue}, {@link #maxValue},
100893 {@link #disabledDays}, and {@link #disabledDates} config parameters. These configurations will be used both
100894 in the field's validation, and in the date picker dropdown by preventing invalid dates from being selected.
100895 {@img Ext.form.Date/Ext.form.Date.png Ext.form.Date component}
100896 #Example usage:#
100897
100898     Ext.create('Ext.form.Panel', {
100899         width: 300,
100900         bodyPadding: 10,
100901         title: 'Dates',
100902         items: [{
100903             xtype: 'datefield',
100904             anchor: '100%',
100905             fieldLabel: 'From',
100906             name: 'from_date',
100907             maxValue: new Date()  // limited to the current date or prior
100908         }, {
100909             xtype: 'datefield',
100910             anchor: '100%',
100911             fieldLabel: 'To',
100912             name: 'to_date',
100913             value: new Date()  // defaults to today
100914         }],
100915             renderTo: Ext.getBody()
100916     });
100917
100918 #Date Formats Examples#
100919
100920 This example shows a couple of different date format parsing scenarios. Both use custom date format
100921 configurations; the first one matches the configured `format` while the second matches the `altFormats`.
100922
100923     Ext.create('Ext.form.Panel', {
100924         renderTo: Ext.getBody(),
100925         width: 300,
100926         bodyPadding: 10,
100927         title: 'Dates',
100928         items: [{
100929             xtype: 'datefield',
100930             anchor: '100%',
100931             fieldLabel: 'Date',
100932             name: 'date',
100933             // The value matches the format; will be parsed and displayed using that format.
100934             format: 'm d Y',
100935             value: '2 4 1978'
100936         }, {
100937             xtype: 'datefield',
100938             anchor: '100%',
100939             fieldLabel: 'Date',
100940             name: 'date',
100941             // The value does not match the format, but does match an altFormat; will be parsed
100942             // using the altFormat and displayed using the format.
100943             format: 'm d Y',
100944             altFormats: 'm,d,Y|m.d.Y',
100945             value: '2.4.1978'
100946         }]
100947     });
100948
100949  * @constructor
100950  * Create a new Date field
100951  * @param {Object} config
100952  * 
100953  * @xtype datefield
100954  * @markdown
100955  * @docauthor Jason Johnston <jason@sencha.com>
100956  */
100957 Ext.define('Ext.form.field.Date', {
100958     extend:'Ext.form.field.Picker',
100959     alias: 'widget.datefield',
100960     requires: ['Ext.picker.Date'],
100961     alternateClassName: ['Ext.form.DateField', 'Ext.form.Date'],
100962
100963     /**
100964      * @cfg {String} format
100965      * The default date format string which can be overriden for localization support.  The format must be
100966      * valid according to {@link Ext.Date#parse} (defaults to <tt>'m/d/Y'</tt>).
100967      */
100968     format : "m/d/Y",
100969     /**
100970      * @cfg {String} altFormats
100971      * Multiple date formats separated by "<tt>|</tt>" to try when parsing a user input value and it
100972      * does not match the defined format (defaults to
100973      * <tt>'m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j'</tt>).
100974      */
100975     altFormats : "m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j",
100976     /**
100977      * @cfg {String} disabledDaysText
100978      * The tooltip to display when the date falls on a disabled day (defaults to <tt>'Disabled'</tt>)
100979      */
100980     disabledDaysText : "Disabled",
100981     /**
100982      * @cfg {String} disabledDatesText
100983      * The tooltip text to display when the date falls on a disabled date (defaults to <tt>'Disabled'</tt>)
100984      */
100985     disabledDatesText : "Disabled",
100986     /**
100987      * @cfg {String} minText
100988      * The error text to display when the date in the cell is before <tt>{@link #minValue}</tt> (defaults to
100989      * <tt>'The date in this field must be after {minValue}'</tt>).
100990      */
100991     minText : "The date in this field must be equal to or after {0}",
100992     /**
100993      * @cfg {String} maxText
100994      * The error text to display when the date in the cell is after <tt>{@link #maxValue}</tt> (defaults to
100995      * <tt>'The date in this field must be before {maxValue}'</tt>).
100996      */
100997     maxText : "The date in this field must be equal to or before {0}",
100998     /**
100999      * @cfg {String} invalidText
101000      * The error text to display when the date in the field is invalid (defaults to
101001      * <tt>'{value} is not a valid date - it must be in the format {format}'</tt>).
101002      */
101003     invalidText : "{0} is not a valid date - it must be in the format {1}",
101004     /**
101005      * @cfg {String} triggerCls
101006      * An additional CSS class used to style the trigger button.  The trigger will always get the
101007      * class <tt>'x-form-trigger'</tt> and <tt>triggerCls</tt> will be <b>appended</b> if specified
101008      * (defaults to <tt>'x-form-date-trigger'</tt> which displays a calendar icon).
101009      */
101010     triggerCls : Ext.baseCSSPrefix + 'form-date-trigger',
101011     /**
101012      * @cfg {Boolean} showToday
101013      * <tt>false</tt> to hide the footer area of the Date picker containing the Today button and disable
101014      * the keyboard handler for spacebar that selects the current date (defaults to <tt>true</tt>).
101015      */
101016     showToday : true,
101017     /**
101018      * @cfg {Date/String} minValue
101019      * The minimum allowed date. Can be either a Javascript date object or a string date in a
101020      * valid format (defaults to undefined).
101021      */
101022     /**
101023      * @cfg {Date/String} maxValue
101024      * The maximum allowed date. Can be either a Javascript date object or a string date in a
101025      * valid format (defaults to undefined).
101026      */
101027     /**
101028      * @cfg {Array} disabledDays
101029      * An array of days to disable, 0 based (defaults to undefined). Some examples:<pre><code>
101030 // disable Sunday and Saturday:
101031 disabledDays:  [0, 6]
101032 // disable weekdays:
101033 disabledDays: [1,2,3,4,5]
101034      * </code></pre>
101035      */
101036     /**
101037      * @cfg {Array} disabledDates
101038      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
101039      * expression so they are very powerful. Some examples:<pre><code>
101040 // disable these exact dates:
101041 disabledDates: ["03/08/2003", "09/16/2003"]
101042 // disable these days for every year:
101043 disabledDates: ["03/08", "09/16"]
101044 // only match the beginning (useful if you are using short years):
101045 disabledDates: ["^03/08"]
101046 // disable every day in March 2006:
101047 disabledDates: ["03/../2006"]
101048 // disable every day in every March:
101049 disabledDates: ["^03"]
101050      * </code></pre>
101051      * Note that the format of the dates included in the array should exactly match the {@link #format} config.
101052      * In order to support regular expressions, if you are using a {@link #format date format} that has "." in
101053      * it, you will have to escape the dot when restricting dates. For example: <tt>["03\\.08\\.03"]</tt>.
101054      */
101055     
101056     /**
101057      * @cfg {String} submitFormat The date format string which will be submitted to the server.  
101058      * The format must be valid according to {@link Ext.Date#parse} (defaults to <tt>{@link #format}</tt>).
101059      */
101060
101061     // in the absence of a time value, a default value of 12 noon will be used
101062     // (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
101063     initTime: '12', // 24 hour format
101064
101065     initTimeFormat: 'H',
101066
101067     matchFieldWidth: false,
101068     /**
101069      * @cfg {Number} startDay
101070      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
101071      */
101072     startDay: 0,
101073     
101074     initComponent : function(){
101075         var me = this,
101076             isString = Ext.isString,
101077             min, max;
101078
101079         min = me.minValue;
101080         max = me.maxValue;
101081         if(isString(min)){
101082             me.minValue = me.parseDate(min);
101083         }
101084         if(isString(max)){
101085             me.maxValue = me.parseDate(max);
101086         }
101087         me.disabledDatesRE = null;
101088         me.initDisabledDays();
101089
101090         me.callParent();
101091     },
101092
101093     initValue: function() {
101094         var me = this,
101095             value = me.value;
101096
101097         // If a String value was supplied, try to convert it to a proper Date
101098         if (Ext.isString(value)) {
101099             me.value = me.rawToValue(value);
101100         }
101101
101102         me.callParent();
101103     },
101104
101105     // private
101106     initDisabledDays : function(){
101107         if(this.disabledDates){
101108             var dd = this.disabledDates,
101109                 len = dd.length - 1,
101110                 re = "(?:";
101111
101112             Ext.each(dd, function(d, i){
101113                 re += Ext.isDate(d) ? '^' + Ext.String.escapeRegex(d.dateFormat(this.format)) + '$' : dd[i];
101114                 if (i !== len) {
101115                     re += '|';
101116                 }
101117             }, this);
101118             this.disabledDatesRE = new RegExp(re + ')');
101119         }
101120     },
101121
101122     /**
101123      * Replaces any existing disabled dates with new values and refreshes the Date picker.
101124      * @param {Array} disabledDates An array of date strings (see the <tt>{@link #disabledDates}</tt> config
101125      * for details on supported values) used to disable a pattern of dates.
101126      */
101127     setDisabledDates : function(dd){
101128         var me = this,
101129             picker = me.picker;
101130             
101131         me.disabledDates = dd;
101132         me.initDisabledDays();
101133         if (picker) {
101134             picker.setDisabledDates(me.disabledDatesRE);
101135         }
101136     },
101137
101138     /**
101139      * Replaces any existing disabled days (by index, 0-6) with new values and refreshes the Date picker.
101140      * @param {Array} disabledDays An array of disabled day indexes. See the <tt>{@link #disabledDays}</tt>
101141      * config for details on supported values.
101142      */
101143     setDisabledDays : function(dd){
101144         var picker = this.picker;
101145             
101146         this.disabledDays = dd;
101147         if (picker) {
101148             picker.setDisabledDays(dd);
101149         }
101150     },
101151
101152     /**
101153      * Replaces any existing <tt>{@link #minValue}</tt> with the new value and refreshes the Date picker.
101154      * @param {Date} value The minimum date that can be selected
101155      */
101156     setMinValue : function(dt){
101157         var me = this,
101158             picker = me.picker,
101159             minValue = (Ext.isString(dt) ? me.parseDate(dt) : dt);
101160             
101161         me.minValue = minValue;
101162         if (picker) {
101163             picker.minText = Ext.String.format(me.minText, me.formatDate(me.minValue));
101164             picker.setMinDate(minValue);
101165         }
101166     },
101167
101168     /**
101169      * Replaces any existing <tt>{@link #maxValue}</tt> with the new value and refreshes the Date picker.
101170      * @param {Date} value The maximum date that can be selected
101171      */
101172     setMaxValue : function(dt){
101173         var me = this,
101174             picker = me.picker,
101175             maxValue = (Ext.isString(dt) ? me.parseDate(dt) : dt);
101176             
101177         me.maxValue = maxValue;
101178         if (picker) {
101179             picker.maxText = Ext.String.format(me.maxText, me.formatDate(me.maxValue));
101180             picker.setMaxDate(maxValue);
101181         }
101182     },
101183
101184     /**
101185      * Runs all of Date's validations and returns an array of any errors. Note that this first
101186      * runs Text's validations, so the returned array is an amalgamation of all field errors.
101187      * The additional validation checks are testing that the date format is valid, that the chosen
101188      * date is within the min and max date constraints set, that the date chosen is not in the disabledDates
101189      * regex and that the day chosed is not one of the disabledDays.
101190      * @param {Mixed} value The value to get errors for (defaults to the current field value)
101191      * @return {Array} All validation errors for this field
101192      */
101193     getErrors: function(value) {
101194         var me = this,
101195             format = Ext.String.format,
101196             clearTime = Ext.Date.clearTime,
101197             errors = me.callParent(arguments),
101198             disabledDays = me.disabledDays,
101199             disabledDatesRE = me.disabledDatesRE,
101200             minValue = me.minValue,
101201             maxValue = me.maxValue,
101202             len = disabledDays ? disabledDays.length : 0,
101203             i = 0,
101204             svalue,
101205             fvalue,
101206             day,
101207             time;
101208
101209         value = me.formatDate(value || me.processRawValue(me.getRawValue()));
101210
101211         if (value === null || value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
101212              return errors;
101213         }
101214
101215         svalue = value;
101216         value = me.parseDate(value);
101217         if (!value) {
101218             errors.push(format(me.invalidText, svalue, me.format));
101219             return errors;
101220         }
101221
101222         time = value.getTime();
101223         if (minValue && time < clearTime(minValue).getTime()) {
101224             errors.push(format(me.minText, me.formatDate(minValue)));
101225         }
101226
101227         if (maxValue && time > clearTime(maxValue).getTime()) {
101228             errors.push(format(me.maxText, me.formatDate(maxValue)));
101229         }
101230
101231         if (disabledDays) {
101232             day = value.getDay();
101233
101234             for(; i < len; i++) {
101235                 if (day === disabledDays[i]) {
101236                     errors.push(me.disabledDaysText);
101237                     break;
101238                 }
101239             }
101240         }
101241
101242         fvalue = me.formatDate(value);
101243         if (disabledDatesRE && disabledDatesRE.test(fvalue)) {
101244             errors.push(format(me.disabledDatesText, fvalue));
101245         }
101246
101247         return errors;
101248     },
101249
101250     rawToValue: function(rawValue) {
101251         return this.parseDate(rawValue) || rawValue || null;
101252     },
101253
101254     valueToRaw: function(value) {
101255         return this.formatDate(this.parseDate(value));
101256     },
101257
101258     /**
101259      * Sets the value of the date field.  You can pass a date object or any string that can be
101260      * parsed into a valid date, using <tt>{@link #format}</tt> as the date format, according
101261      * to the same rules as {@link Ext.Date#parse} (the default format used is <tt>"m/d/Y"</tt>).
101262      * <br />Usage:
101263      * <pre><code>
101264 //All of these calls set the same date value (May 4, 2006)
101265
101266 //Pass a date object:
101267 var dt = new Date('5/4/2006');
101268 dateField.setValue(dt);
101269
101270 //Pass a date string (default format):
101271 dateField.setValue('05/04/2006');
101272
101273 //Pass a date string (custom format):
101274 dateField.format = 'Y-m-d';
101275 dateField.setValue('2006-05-04');
101276 </code></pre>
101277      * @param {String/Date} date The date or valid date string
101278      * @return {Ext.form.field.Date} this
101279      * @method setValue
101280      */
101281
101282     /**
101283      * Attempts to parse a given string value using a given {@link Ext.Date#parse date format}.
101284      * @param {String} value The value to attempt to parse
101285      * @param {String} format A valid date format (see {@link Ext.Date#parse})
101286      * @return {Date} The parsed Date object, or null if the value could not be successfully parsed.
101287      */
101288     safeParse : function(value, format) {
101289         var me = this,
101290             utilDate = Ext.Date,
101291             parsedDate,
101292             result = null;
101293             
101294         if (utilDate.formatContainsHourInfo(format)) {
101295             // if parse format contains hour information, no DST adjustment is necessary
101296             result = utilDate.parse(value, format);
101297         } else {
101298             // set time to 12 noon, then clear the time
101299             parsedDate = utilDate.parse(value + ' ' + me.initTime, format + ' ' + me.initTimeFormat);
101300             if (parsedDate) {
101301                 result = utilDate.clearTime(parsedDate);
101302             }
101303         }
101304         return result;
101305     },
101306     
101307     // @private
101308     getSubmitValue: function() {
101309         var me = this,
101310             format = me.submitFormat || me.format,
101311             value = me.getValue();
101312             
101313         return value ? Ext.Date.format(value, format) : null;
101314     },
101315
101316     /**
101317      * @private
101318      */
101319     parseDate : function(value) {
101320         if(!value || Ext.isDate(value)){
101321             return value;
101322         }
101323
101324         var me = this,
101325             val = me.safeParse(value, me.format),
101326             altFormats = me.altFormats,
101327             altFormatsArray = me.altFormatsArray,
101328             i = 0,
101329             len;
101330
101331         if (!val && altFormats) {
101332             altFormatsArray = altFormatsArray || altFormats.split('|');
101333             len = altFormatsArray.length;
101334             for (; i < len && !val; ++i) {
101335                 val = me.safeParse(value, altFormatsArray[i]);
101336             }
101337         }
101338         return val;
101339     },
101340
101341     // private
101342     formatDate : function(date){
101343         return Ext.isDate(date) ? Ext.Date.dateFormat(date, this.format) : date;
101344     },
101345
101346     createPicker: function() {
101347         var me = this,
101348             format = Ext.String.format;
101349
101350         return Ext.create('Ext.picker.Date', {
101351             ownerCt: this.ownerCt,
101352             renderTo: document.body,
101353             floating: true,
101354             hidden: true,
101355             focusOnShow: true,
101356             minDate: me.minValue,
101357             maxDate: me.maxValue,
101358             disabledDatesRE: me.disabledDatesRE,
101359             disabledDatesText: me.disabledDatesText,
101360             disabledDays: me.disabledDays,
101361             disabledDaysText: me.disabledDaysText,
101362             format: me.format,
101363             showToday: me.showToday,
101364             startDay: me.startDay,
101365             minText: format(me.minText, me.formatDate(me.minValue)),
101366             maxText: format(me.maxText, me.formatDate(me.maxValue)),
101367             listeners: {
101368                 scope: me,
101369                 select: me.onSelect
101370             },
101371             keyNavConfig: {
101372                 esc: function() {
101373                     me.collapse();
101374                 }
101375             }
101376         });
101377     },
101378
101379     onSelect: function(m, d) {
101380         this.setValue(d);
101381         this.fireEvent('select', this, d);
101382         this.collapse();
101383     },
101384
101385     /**
101386      * @private
101387      * Sets the Date picker's value to match the current field value when expanding.
101388      */
101389     onExpand: function() {
101390         var me = this,
101391             value = me.getValue();
101392         me.picker.setValue(value instanceof Date ? value : new Date());
101393     },
101394
101395     /**
101396      * @private
101397      * Focuses the field when collapsing the Date picker.
101398      */
101399     onCollapse: function() {
101400         this.focus(false, 60);
101401     },
101402
101403     // private
101404     beforeBlur : function(){
101405         var v = this.parseDate(this.getRawValue());
101406         if(v){
101407             this.setValue(v);
101408         }
101409     }
101410
101411     /**
101412      * @cfg {Boolean} grow @hide
101413      */
101414     /**
101415      * @cfg {Number} growMin @hide
101416      */
101417     /**
101418      * @cfg {Number} growMax @hide
101419      */
101420     /**
101421      * @hide
101422      * @method autoSize
101423      */
101424 });
101425
101426 /**
101427  * @class Ext.form.field.Display
101428  * @extends Ext.form.field.Base
101429  * <p>A display-only text field which is not validated and not submitted. This is useful for when you want
101430  * to display a value from a form's {@link Ext.form.Basic#load loaded data} but do not want to allow the
101431  * user to edit or submit that value. The value can be optionally {@link #htmlEncode HTML encoded} if it contains
101432  * HTML markup that you do not want to be rendered.</p>
101433  * <p>If you have more complex content, or need to include components within the displayed content, also
101434  * consider using a {@link Ext.form.FieldContainer} instead.</p>
101435  * {@img Ext.form.Display/Ext.form.Display.png Ext.form.Display component}
101436  * <p>Example:</p>
101437  * <pre><code>
101438     Ext.create('Ext.form.Panel', {
101439         width: 175,
101440         height: 120,
101441         bodyPadding: 10,
101442         title: 'Final Score',
101443         items: [{
101444             xtype: 'displayfield',
101445             fieldLabel: 'Home',
101446             name: 'home_score',
101447             value: '10'
101448         }, {
101449             xtype: 'displayfield',
101450             fieldLabel: 'Visitor',
101451             name: 'visitor_score',
101452             value: '11'
101453         }],
101454         buttons: [{
101455             text: 'Update',
101456         }],
101457         renderTo: Ext.getBody()
101458     });
101459 </code></pre>
101460
101461  * @constructor
101462  * Creates a new DisplayField.
101463  * @param {Object} config Configuration options
101464  *
101465  * @xtype displayfield
101466  */
101467 Ext.define('Ext.form.field.Display', {
101468     extend:'Ext.form.field.Base',
101469     alias: 'widget.displayfield',
101470     requires: ['Ext.util.Format', 'Ext.XTemplate'],
101471     alternateClassName: ['Ext.form.DisplayField', 'Ext.form.Display'],
101472     fieldSubTpl: [
101473         '<div id="{id}" class="{fieldCls}"></div>',
101474         {
101475             compiled: true,
101476             disableFormats: true
101477         }
101478     ],
101479
101480     /**
101481      * @cfg {String} fieldCls The default CSS class for the field (defaults to <tt>"x-form-display-field"</tt>)
101482      */
101483     fieldCls: Ext.baseCSSPrefix + 'form-display-field',
101484
101485     /**
101486      * @cfg {Boolean} htmlEncode <tt>false</tt> to skip HTML-encoding the text when rendering it (defaults to
101487      * <tt>false</tt>). This might be useful if you want to include tags in the field's innerHTML rather than
101488      * rendering them as string literals per the default logic.
101489      */
101490     htmlEncode: false,
101491
101492     validateOnChange: false,
101493
101494     initEvents: Ext.emptyFn,
101495
101496     submitValue: false,
101497
101498     isValid: function() {
101499         return true;
101500     },
101501
101502     validate: function() {
101503         return true;
101504     },
101505
101506     getRawValue: function() {
101507         return this.rawValue;
101508     },
101509
101510     setRawValue: function(value) {
101511         var me = this;
101512         value = Ext.value(value, '');
101513         me.rawValue = value;
101514         if (me.rendered) {
101515             me.inputEl.dom.innerHTML = me.htmlEncode ? Ext.util.Format.htmlEncode(value) : value;
101516         }
101517         return value;
101518     },
101519
101520     // private
101521     getContentTarget: function() {
101522         return this.inputEl;
101523     }
101524
101525     /**
101526      * @cfg {String} inputType
101527      * @hide
101528      */
101529     /**
101530      * @cfg {Boolean} disabled
101531      * @hide
101532      */
101533     /**
101534      * @cfg {Boolean} readOnly
101535      * @hide
101536      */
101537     /**
101538      * @cfg {Boolean} validateOnChange
101539      * @hide
101540      */
101541     /**
101542      * @cfg {Number} checkChangeEvents
101543      * @hide
101544      */
101545     /**
101546      * @cfg {Number} checkChangeBuffer
101547      * @hide
101548      */
101549 });
101550
101551 /**
101552  * @class Ext.form.field.File
101553  * @extends Ext.form.field.Text
101554
101555 A file upload field which has custom styling and allows control over the button text and other
101556 features of {@link Ext.form.field.Text text fields} like {@link Ext.form.field.Text#emptyText empty text}.
101557 It uses a hidden file input element behind the scenes to allow user selection of a file and to
101558 perform the actual upload during {@link Ext.form.Basic#submit form submit}.
101559
101560 Because there is no secure cross-browser way to programmatically set the value of a file input,
101561 the standard Field `setValue` method is not implemented. The `{@link #getValue}` method will return
101562 a value that is browser-dependent; some have just the file name, some have a full path, some use
101563 a fake path.
101564 {@img Ext.form.File/Ext.form.File.png Ext.form.File component}
101565 #Example Usage:#
101566
101567     Ext.create('Ext.form.Panel', {
101568         title: 'Upload a Photo',
101569         width: 400,
101570         bodyPadding: 10,
101571         frame: true,
101572         renderTo: Ext.getBody(),    
101573         items: [{
101574             xtype: 'filefield',
101575             name: 'photo',
101576             fieldLabel: 'Photo',
101577             labelWidth: 50,
101578             msgTarget: 'side',
101579             allowBlank: false,
101580             anchor: '100%',
101581             buttonText: 'Select Photo...'
101582         }],
101583     
101584         buttons: [{
101585             text: 'Upload',
101586             handler: function() {
101587                 var form = this.up('form').getForm();
101588                 if(form.isValid()){
101589                     form.submit({
101590                         url: 'photo-upload.php',
101591                         waitMsg: 'Uploading your photo...',
101592                         success: function(fp, o) {
101593                             Ext.Msg.alert('Success', 'Your photo "' + o.result.file + '" has been uploaded.');
101594                         }
101595                     });
101596                 }
101597             }
101598         }]
101599     });
101600
101601  * @constructor
101602  * Create a new File field
101603  * @param {Object} config Configuration options
101604  * @xtype filefield
101605  * @markdown
101606  * @docauthor Jason Johnston <jason@sencha.com>
101607  */
101608 Ext.define("Ext.form.field.File", {
101609     extend: 'Ext.form.field.Text',
101610     alias: ['widget.filefield', 'widget.fileuploadfield'],
101611     alternateClassName: ['Ext.form.FileUploadField', 'Ext.ux.form.FileUploadField', 'Ext.form.File'],
101612     uses: ['Ext.button.Button', 'Ext.layout.component.field.File'],
101613
101614     /**
101615      * @cfg {String} buttonText The button text to display on the upload button (defaults to
101616      * 'Browse...').  Note that if you supply a value for {@link #buttonConfig}, the buttonConfig.text
101617      * value will be used instead if available.
101618      */
101619     buttonText: 'Browse...',
101620
101621     /**
101622      * @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible
101623      * text field (defaults to false).  If true, all inherited Text members will still be available.
101624      */
101625     buttonOnly: false,
101626
101627     /**
101628      * @cfg {Number} buttonMargin The number of pixels of space reserved between the button and the text field
101629      * (defaults to 3).  Note that this only applies if {@link #buttonOnly} = false.
101630      */
101631     buttonMargin: 3,
101632
101633     /**
101634      * @cfg {Object} buttonConfig A standard {@link Ext.button.Button} config object.
101635      */
101636
101637     /**
101638      * @event change
101639      * Fires when the underlying file input field's value has changed from the user
101640      * selecting a new file from the system file selection dialog.
101641      * @param {Ext.ux.form.FileUploadField} this
101642      * @param {String} value The file value returned by the underlying file input field
101643      */
101644
101645     /**
101646      * @property fileInputEl
101647      * @type {Ext.core.Element}
101648      * A reference to the invisible file input element created for this upload field. Only
101649      * populated after this component is rendered.
101650      */
101651
101652     /**
101653      * @property button
101654      * @type {Ext.button.Button}
101655      * A reference to the trigger Button component created for this upload field. Only
101656      * populated after this component is rendered.
101657      */
101658
101659     /**
101660      * @cfg {String} fieldBodyCls
101661      * An extra CSS class to be applied to the body content element in addition to {@link #fieldBodyCls}.
101662      * Defaults to 'x-form-file-wrap' for file upload field.
101663      */
101664     fieldBodyCls: Ext.baseCSSPrefix + 'form-file-wrap',
101665
101666
101667     // private
101668     readOnly: true,
101669     componentLayout: 'filefield',
101670
101671     // private
101672     onRender: function() {
101673         var me = this,
101674             inputEl;
101675
101676         me.callParent(arguments);
101677
101678         me.createButton();
101679         me.createFileInput();
101680         
101681         // we don't create the file/button til after onRender, the initial disable() is
101682         // called in the onRender of the component.
101683         if (me.disabled) {
101684             me.disableItems();
101685         }
101686
101687         inputEl = me.inputEl;
101688         inputEl.dom.removeAttribute('name'); //name goes on the fileInput, not the text input
101689         if (me.buttonOnly) {
101690             inputEl.setDisplayed(false);
101691         }
101692     },
101693
101694     /**
101695      * @private
101696      * Creates the custom trigger Button component. The fileInput will be inserted into this.
101697      */
101698     createButton: function() {
101699         var me = this;
101700         me.button = Ext.widget('button', Ext.apply({
101701             renderTo: me.bodyEl,
101702             text: me.buttonText,
101703             cls: Ext.baseCSSPrefix + 'form-file-btn',
101704             preventDefault: false,
101705             ownerCt: me,
101706             style: me.buttonOnly ? '' : 'margin-left:' + me.buttonMargin + 'px'
101707         }, me.buttonConfig));
101708     },
101709
101710     /**
101711      * @private
101712      * Creates the file input element. It is inserted into the trigger button component, made
101713      * invisible, and floated on top of the button's other content so that it will receive the
101714      * button's clicks.
101715      */
101716     createFileInput : function() {
101717         var me = this;
101718         me.fileInputEl = me.button.el.createChild({
101719             name: me.getName(),
101720             cls: Ext.baseCSSPrefix + 'form-file-input',
101721             tag: 'input',
101722             type: 'file',
101723             size: 1
101724         }).on('change', me.onFileChange, me);
101725     },
101726
101727     /**
101728      * @private Event handler fired when the user selects a file.
101729      */
101730     onFileChange: function() {
101731         this.lastValue = null; // force change event to get fired even if the user selects a file with the same name
101732         Ext.form.field.File.superclass.setValue.call(this, this.fileInputEl.dom.value);
101733     },
101734
101735     /**
101736      * Overridden to do nothing
101737      * @hide
101738      */
101739     setValue: Ext.emptyFn,
101740
101741     reset : function(){
101742         this.fileInputEl.remove();
101743         this.createFileInput();
101744         this.callParent();
101745     },
101746
101747     onDisable: function(){
101748         this.callParent();
101749         this.disableItems();
101750     },
101751     
101752     disableItems: function(){
101753         var file = this.fileInputEl,
101754             button = this.button;
101755              
101756         if (file) {
101757             file.dom.disabled = true;
101758         }
101759         if (button) {
101760             button.disable();
101761         }    
101762     },
101763
101764     onEnable: function(){
101765         var me = this;
101766         me.callParent();
101767         me.fileInputEl.dom.disabled = false;
101768         me.button.enable();
101769     },
101770
101771     isFileUpload: function() {
101772         return true;
101773     },
101774
101775     extractFileInput: function() {
101776         var fileInput = this.fileInputEl.dom;
101777         this.reset();
101778         return fileInput;
101779     },
101780
101781     onDestroy: function(){
101782         Ext.destroyMembers(this, 'fileInputEl', 'button');
101783         this.callParent();
101784     }
101785
101786
101787 });
101788
101789 /**
101790  * @class Ext.form.field.Hidden
101791  * @extends Ext.form.field.Base
101792  * <p>A basic hidden field for storing hidden values in forms that need to be passed in the form submit.</p>
101793  * <p>This creates an actual input element with type="submit" in the DOM. While its label is
101794  * {@link #hideLabel not rendered} by default, it is still a real component and may be sized according to
101795  * its owner container's layout.</p>
101796  * <p>Because of this, in most cases it is more convenient and less problematic to simply
101797  * {@link Ext.form.action.Action#params pass hidden parameters} directly when
101798  * {@link Ext.form.Basic#submit submitting the form}.</p>
101799  * <p>Example:</p>
101800  * <pre><code>new Ext.form.Panel({
101801     title: 'My Form',
101802     items: [{
101803         xtype: 'textfield',
101804         fieldLabel: 'Text Field',
101805         name: 'text_field',
101806         value: 'value from text field'
101807     }, {
101808         xtype: 'hiddenfield',
101809         name: 'hidden_field_1',
101810         value: 'value from hidden field'
101811     }],
101812
101813     buttons: [{
101814         text: 'Submit',
101815         handler: function() {
101816             this.up('form').getForm().submit({
101817                 params: {
101818                     hidden_field_2: 'value from submit call'
101819                 }
101820             });
101821         }
101822     }]
101823 });</code></pre>
101824  * <p>Submitting the above form will result in three values sent to the server:
101825  * <code>text_field=value+from+text+field&hidden_field_1=value+from+hidden+field&<br>hidden_field_2=value+from+submit+call</code></p>
101826  *
101827  * @constructor
101828  * Create a new Hidden field.
101829  * @param {Object} config Configuration options
101830  * 
101831  * @xtype hiddenfield
101832  */
101833 Ext.define('Ext.form.field.Hidden', {
101834     extend:'Ext.form.field.Base',
101835     alias: ['widget.hiddenfield', 'widget.hidden'],
101836     alternateClassName: 'Ext.form.Hidden',
101837
101838     // private
101839     inputType : 'hidden',
101840     hideLabel: true,
101841     
101842     initComponent: function(){
101843         this.formItemCls += '-hidden';
101844         this.callParent();    
101845     },
101846
101847     // These are all private overrides
101848     initEvents: Ext.emptyFn,
101849     setSize : Ext.emptyFn,
101850     setWidth : Ext.emptyFn,
101851     setHeight : Ext.emptyFn,
101852     setPosition : Ext.emptyFn,
101853     setPagePosition : Ext.emptyFn,
101854     markInvalid : Ext.emptyFn,
101855     clearInvalid : Ext.emptyFn
101856 });
101857
101858 /**
101859  * @class Ext.picker.Color
101860  * @extends Ext.Component
101861  * <p>ColorPicker provides a simple color palette for choosing colors. The picker can be rendered to any container.
101862  * The available default to a standard 40-color palette; this can be customized with the {@link #colors} config.</p>
101863  * <p>Typically you will need to implement a handler function to be notified when the user chooses a color from the
101864  * picker; you can register the handler using the {@link #select} event, or by implementing the {@link #handler}
101865  * method.</p>
101866  * <p>Here's an example of typical usage:</p>
101867  * <pre><code>var cp = new Ext.picker.Color({
101868     value: '993300',  // initial selected color
101869     renderTo: 'my-div'
101870 });
101871
101872 cp.on('select', function(picker, selColor){
101873     // do something with selColor
101874 });
101875 </code></pre>
101876  * {@img Ext.picker.Color/Ext.picker.Color.png Ext.picker.Color component}
101877  *
101878  * @constructor
101879  * Create a new ColorPicker
101880  * @param {Object} config The config object
101881  * 
101882  * @xtype colorpicker
101883  */
101884 Ext.define('Ext.picker.Color', {
101885     extend: 'Ext.Component',
101886     requires: 'Ext.XTemplate',
101887     alias: 'widget.colorpicker',
101888     alternateClassName: 'Ext.ColorPalette',
101889     
101890     /**
101891      * @cfg {String} componentCls
101892      * The CSS class to apply to the containing element (defaults to 'x-color-picker')
101893      */
101894     componentCls : Ext.baseCSSPrefix + 'color-picker',
101895     
101896     /**
101897      * @cfg {String} selectedCls
101898      * The CSS class to apply to the selected element
101899      */
101900     selectedCls: Ext.baseCSSPrefix + 'color-picker-selected',
101901     
101902     /**
101903      * @cfg {String} value
101904      * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol).  Note that
101905      * the hex codes are case-sensitive.
101906      */
101907     value : null,
101908     
101909     /**
101910      * @cfg {String} clickEvent
101911      * The DOM event that will cause a color to be selected. This can be any valid event name (dblclick, contextmenu).
101912      * Defaults to <tt>'click'</tt>.
101913      */
101914     clickEvent :'click',
101915
101916     /**
101917      * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the {@link #select} event
101918      */
101919     allowReselect : false,
101920
101921     /**
101922      * <p>An array of 6-digit color hex code strings (without the # symbol).  This array can contain any number
101923      * of colors, and each hex code should be unique.  The width of the picker is controlled via CSS by adjusting
101924      * the width property of the 'x-color-picker' class (or assigning a custom class), so you can balance the number
101925      * of colors with the width setting until the box is symmetrical.</p>
101926      * <p>You can override individual colors if needed:</p>
101927      * <pre><code>
101928 var cp = new Ext.picker.Color();
101929 cp.colors[0] = 'FF0000';  // change the first box to red
101930 </code></pre>
101931
101932 Or you can provide a custom array of your own for complete control:
101933 <pre><code>
101934 var cp = new Ext.picker.Color();
101935 cp.colors = ['000000', '993300', '333300'];
101936 </code></pre>
101937      * @type Array
101938      */
101939     colors : [
101940         '000000', '993300', '333300', '003300', '003366', '000080', '333399', '333333',
101941         '800000', 'FF6600', '808000', '008000', '008080', '0000FF', '666699', '808080',
101942         'FF0000', 'FF9900', '99CC00', '339966', '33CCCC', '3366FF', '800080', '969696',
101943         'FF00FF', 'FFCC00', 'FFFF00', '00FF00', '00FFFF', '00CCFF', '993366', 'C0C0C0',
101944         'FF99CC', 'FFCC99', 'FFFF99', 'CCFFCC', 'CCFFFF', '99CCFF', 'CC99FF', 'FFFFFF'
101945     ],
101946
101947     /**
101948      * @cfg {Function} handler
101949      * Optional. A function that will handle the select event of this picker.
101950      * The handler is passed the following parameters:<div class="mdetail-params"><ul>
101951      * <li><code>picker</code> : ColorPicker<div class="sub-desc">The {@link #picker Ext.picker.Color}.</div></li>
101952      * <li><code>color</code> : String<div class="sub-desc">The 6-digit color hex code (without the # symbol).</div></li>
101953      * </ul></div>
101954      */
101955     /**
101956      * @cfg {Object} scope
101957      * The scope (<tt><b>this</b></tt> reference) in which the <code>{@link #handler}</code>
101958      * function will be called.  Defaults to this ColorPicker instance.
101959      */
101960     
101961     colorRe: /(?:^|\s)color-(.{6})(?:\s|$)/,
101962     
101963     constructor: function() {
101964         this.renderTpl = Ext.create('Ext.XTemplate', '<tpl for="colors"><a href="#" class="color-{.}" hidefocus="on"><em><span style="background:#{.}" unselectable="on">&#160;</span></em></a></tpl>');
101965         this.callParent(arguments);
101966     },
101967     
101968     // private
101969     initComponent : function(){
101970         var me = this;
101971         
101972         this.callParent(arguments);
101973         me.addEvents(
101974             /**
101975              * @event select
101976              * Fires when a color is selected
101977              * @param {Ext.picker.Color} this
101978              * @param {String} color The 6-digit color hex code (without the # symbol)
101979              */
101980             'select'
101981         );
101982
101983         if (me.handler) {
101984             me.on('select', me.handler, me.scope, true);
101985         }
101986     },
101987
101988
101989     // private
101990     onRender : function(container, position){
101991         var me = this,
101992             clickEvent = me.clickEvent;
101993             
101994         Ext.apply(me.renderData, {
101995             itemCls: me.itemCls,
101996             colors: me.colors    
101997         });
101998         this.callParent(arguments);
101999
102000         me.mon(me.el, clickEvent, me.handleClick, me, {delegate: 'a'});
102001         // always stop following the anchors
102002         if(clickEvent != 'click'){
102003             me.mon(me.el, 'click', Ext.emptyFn, me, {delegate: 'a', stopEvent: true});
102004         }
102005     },
102006
102007     // private
102008     afterRender : function(){
102009         var me = this,
102010             value;
102011             
102012         this.callParent(arguments);
102013         if (me.value) {
102014             value = me.value;
102015             me.value = null;
102016             me.select(value, true);
102017         }
102018     },
102019
102020     // private
102021     handleClick : function(event, target){
102022         var me = this,
102023             color;
102024             
102025         event.stopEvent();
102026         if (!me.disabled) {
102027             color = target.className.match(me.colorRe)[1];
102028             me.select(color.toUpperCase());
102029         }
102030     },
102031
102032     /**
102033      * Selects the specified color in the picker (fires the {@link #select} event)
102034      * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
102035      * @param {Boolean} suppressEvent (optional) True to stop the select event from firing. Defaults to <tt>false</tt>.
102036      */
102037     select : function(color, suppressEvent){
102038         
102039         var me = this,
102040             selectedCls = me.selectedCls,
102041             value = me.value,
102042             el;
102043             
102044         color = color.replace('#', '');
102045         if (!me.rendered) {
102046             me.value = color;
102047             return;
102048         }
102049         
102050         
102051         if (color != value || me.allowReselect) {
102052             el = me.el;
102053
102054             if (me.value) {
102055                 el.down('a.color-' + value).removeCls(selectedCls);
102056             }
102057             el.down('a.color-' + color).addCls(selectedCls);
102058             me.value = color;
102059             if (suppressEvent !== true) {
102060                 me.fireEvent('select', me, color);
102061             }
102062         }
102063     },
102064     
102065     /**
102066      * Get the currently selected color value.
102067      * @return {String} value The selected value. Null if nothing is selected.
102068      */
102069     getValue: function(){
102070         return this.value || null;
102071     }
102072 });
102073
102074 /**
102075  * @private
102076  * @class Ext.layout.component.field.HtmlEditor
102077  * @extends Ext.layout.component.field.Field
102078  * Layout class for {@link Ext.form.field.HtmlEditor} fields. Sizes the toolbar, textarea, and iframe elements.
102079  * @private
102080  */
102081
102082 Ext.define('Ext.layout.component.field.HtmlEditor', {
102083     extend: 'Ext.layout.component.field.Field',
102084     alias: ['layout.htmleditor'],
102085
102086     type: 'htmleditor',
102087
102088     sizeBodyContents: function(width, height) {
102089         var me = this,
102090             owner = me.owner,
102091             bodyEl = owner.bodyEl,
102092             toolbar = owner.getToolbar(),
102093             textarea = owner.textareaEl,
102094             iframe = owner.iframeEl,
102095             editorHeight;
102096
102097         if (Ext.isNumber(width)) {
102098             width -= bodyEl.getFrameWidth('lr');
102099         }
102100         toolbar.setWidth(width);
102101         textarea.setWidth(width);
102102         iframe.setWidth(width);
102103
102104         // If fixed height, subtract toolbar height from the input area height
102105         if (Ext.isNumber(height)) {
102106             editorHeight = height - toolbar.getHeight() - bodyEl.getFrameWidth('tb');
102107             textarea.setHeight(editorHeight);
102108             iframe.setHeight(editorHeight);
102109         }
102110     }
102111 });
102112 /**
102113  * @class Ext.form.field.HtmlEditor
102114  * @extends Ext.Component
102115  *
102116  * Provides a lightweight HTML Editor component. Some toolbar features are not supported by Safari and will be
102117  * automatically hidden when needed. These are noted in the config options where appropriate.
102118  * 
102119  * The editor's toolbar buttons have tooltips defined in the {@link #buttonTips} property, but they are not
102120  * enabled by default unless the global {@link Ext.tip.QuickTipManager} singleton is {@link Ext.tip.QuickTipManager#init initialized}.
102121  * 
102122  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
102123  * any element that has display set to 'none' can cause problems in Safari and Firefox due to their default iframe reloading bugs.
102124  *
102125  * {@img Ext.form.HtmlEditor/Ext.form.HtmlEditor1.png Ext.form.HtmlEditor component}
102126  *
102127  * ## Example usage
102128  *
102129  * {@img Ext.form.HtmlEditor/Ext.form.HtmlEditor2.png Ext.form.HtmlEditor component}
102130  *
102131  *     // Simple example rendered with default options:
102132  *     Ext.tip.QuickTips.init();  // enable tooltips
102133  *     Ext.create('Ext.form.HtmlEditor', {
102134  *         width: 580,
102135  *         height: 250,
102136  *         renderTo: Ext.getBody()        
102137  *     });
102138  * 
102139  * {@img Ext.form.HtmlEditor/Ext.form.HtmlEditor2.png Ext.form.HtmlEditor component}
102140  * 
102141  *     // Passed via xtype into a container and with custom options:
102142  *     Ext.tip.QuickTips.init();  // enable tooltips
102143  *     new Ext.panel.Panel({
102144  *         title: 'HTML Editor',
102145  *         renderTo: Ext.getBody(),
102146  *         width: 550,
102147  *         height: 250,
102148  *         frame: true,
102149  *         layout: 'fit',
102150  *         items: {
102151  *             xtype: 'htmleditor',
102152  *             enableColors: false,
102153  *             enableAlignments: false
102154  *         }
102155  *     });
102156  *
102157  * @constructor
102158  * Create a new HtmlEditor
102159  * @param {Object} config
102160  * @xtype htmleditor
102161  */
102162 Ext.define('Ext.form.field.HtmlEditor', {
102163     extend:'Ext.Component',
102164     mixins: {
102165         labelable: 'Ext.form.Labelable',
102166         field: 'Ext.form.field.Field'
102167     },
102168     alias: 'widget.htmleditor',
102169     alternateClassName: 'Ext.form.HtmlEditor',
102170     requires: [
102171         'Ext.tip.QuickTipManager',
102172         'Ext.picker.Color',
102173         'Ext.toolbar.Item',
102174         'Ext.toolbar.Toolbar',
102175         'Ext.util.Format',
102176         'Ext.layout.component.field.HtmlEditor'
102177     ],
102178
102179     fieldSubTpl: [
102180         '<div class="{toolbarWrapCls}"></div>',
102181         '<textarea id="{id}" name="{name}" tabIndex="-1" class="{textareaCls}" ',
102182             'style="{size}" autocomplete="off"></textarea>',
102183         '<iframe name="{iframeName}" frameBorder="0" style="overflow:auto;{size}" src="{iframeSrc}"></iframe>',
102184         {
102185             compiled: true,
102186             disableFormats: true
102187         }
102188     ],
102189
102190     /**
102191      * @cfg {Boolean} enableFormat Enable the bold, italic and underline buttons (defaults to true)
102192      */
102193     enableFormat : true,
102194     /**
102195      * @cfg {Boolean} enableFontSize Enable the increase/decrease font size buttons (defaults to true)
102196      */
102197     enableFontSize : true,
102198     /**
102199      * @cfg {Boolean} enableColors Enable the fore/highlight color buttons (defaults to true)
102200      */
102201     enableColors : true,
102202     /**
102203      * @cfg {Boolean} enableAlignments Enable the left, center, right alignment buttons (defaults to true)
102204      */
102205     enableAlignments : true,
102206     /**
102207      * @cfg {Boolean} enableLists Enable the bullet and numbered list buttons. Not available in Safari. (defaults to true)
102208      */
102209     enableLists : true,
102210     /**
102211      * @cfg {Boolean} enableSourceEdit Enable the switch to source edit button. Not available in Safari. (defaults to true)
102212      */
102213     enableSourceEdit : true,
102214     /**
102215      * @cfg {Boolean} enableLinks Enable the create link button. Not available in Safari. (defaults to true)
102216      */
102217     enableLinks : true,
102218     /**
102219      * @cfg {Boolean} enableFont Enable font selection. Not available in Safari. (defaults to true)
102220      */
102221     enableFont : true,
102222     /**
102223      * @cfg {String} createLinkText The default text for the create link prompt
102224      */
102225     createLinkText : 'Please enter the URL for the link:',
102226     /**
102227      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
102228      */
102229     defaultLinkValue : 'http:/'+'/',
102230     /**
102231      * @cfg {Array} fontFamilies An array of available font families
102232      */
102233     fontFamilies : [
102234         'Arial',
102235         'Courier New',
102236         'Tahoma',
102237         'Times New Roman',
102238         'Verdana'
102239     ],
102240     defaultFont: 'tahoma',
102241     /**
102242      * @cfg {String} defaultValue A default value to be put into the editor to resolve focus issues (defaults to &#160; (Non-breaking space) in Opera and IE6, &#8203; (Zero-width space) in all other browsers).
102243      */
102244     defaultValue: (Ext.isOpera || Ext.isIE6) ? '&#160;' : '&#8203;',
102245
102246     fieldBodyCls: Ext.baseCSSPrefix + 'html-editor-wrap',
102247
102248     componentLayout: 'htmleditor',
102249
102250     // private properties
102251     initialized : false,
102252     activated : false,
102253     sourceEditMode : false,
102254     iframePad:3,
102255     hideMode:'offsets',
102256
102257     maskOnDisable: true,
102258     
102259     // private
102260     initComponent : function(){
102261         var me = this;
102262
102263         me.addEvents(
102264             /**
102265              * @event initialize
102266              * Fires when the editor is fully initialized (including the iframe)
102267              * @param {Ext.form.field.HtmlEditor} this
102268              */
102269             'initialize',
102270             /**
102271              * @event activate
102272              * Fires when the editor is first receives the focus. Any insertion must wait
102273              * until after this event.
102274              * @param {Ext.form.field.HtmlEditor} this
102275              */
102276             'activate',
102277              /**
102278              * @event beforesync
102279              * Fires before the textarea is updated with content from the editor iframe. Return false
102280              * to cancel the sync.
102281              * @param {Ext.form.field.HtmlEditor} this
102282              * @param {String} html
102283              */
102284             'beforesync',
102285              /**
102286              * @event beforepush
102287              * Fires before the iframe editor is updated with content from the textarea. Return false
102288              * to cancel the push.
102289              * @param {Ext.form.field.HtmlEditor} this
102290              * @param {String} html
102291              */
102292             'beforepush',
102293              /**
102294              * @event sync
102295              * Fires when the textarea is updated with content from the editor iframe.
102296              * @param {Ext.form.field.HtmlEditor} this
102297              * @param {String} html
102298              */
102299             'sync',
102300              /**
102301              * @event push
102302              * Fires when the iframe editor is updated with content from the textarea.
102303              * @param {Ext.form.field.HtmlEditor} this
102304              * @param {String} html
102305              */
102306             'push',
102307              /**
102308              * @event editmodechange
102309              * Fires when the editor switches edit modes
102310              * @param {Ext.form.field.HtmlEditor} this
102311              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
102312              */
102313             'editmodechange'
102314         );
102315
102316         me.callParent(arguments);
102317
102318         // Init mixins
102319         me.initLabelable();
102320         me.initField();
102321     },
102322
102323     /*
102324      * Protected method that will not generally be called directly. It
102325      * is called when the editor creates its toolbar. Override this method if you need to
102326      * add custom toolbar buttons.
102327      * @param {Ext.form.field.HtmlEditor} editor
102328      */
102329     createToolbar : function(editor){
102330         var me = this,
102331             items = [],
102332             tipsEnabled = Ext.tip.QuickTipManager && Ext.tip.QuickTipManager.isEnabled(),
102333             baseCSSPrefix = Ext.baseCSSPrefix,
102334             fontSelectItem, toolbar, undef;
102335
102336         function btn(id, toggle, handler){
102337             return {
102338                 itemId : id,
102339                 cls : baseCSSPrefix + 'btn-icon',
102340                 iconCls: baseCSSPrefix + 'edit-'+id,
102341                 enableToggle:toggle !== false,
102342                 scope: editor,
102343                 handler:handler||editor.relayBtnCmd,
102344                 clickEvent:'mousedown',
102345                 tooltip: tipsEnabled ? editor.buttonTips[id] || undef : undef,
102346                 overflowText: editor.buttonTips[id].title || undef,
102347                 tabIndex:-1
102348             };
102349         }
102350
102351
102352         if (me.enableFont && !Ext.isSafari2) {
102353             fontSelectItem = Ext.widget('component', {
102354                 renderTpl: [
102355                     '<select class="{cls}">',
102356                         '<tpl for="fonts">',
102357                             '<option value="{[values.toLowerCase()]}" style="font-family:{.}"<tpl if="values.toLowerCase()==parent.defaultFont"> selected</tpl>>{.}</option>',
102358                         '</tpl>',
102359                     '</select>'
102360                 ],
102361                 renderData: {
102362                     cls: baseCSSPrefix + 'font-select',
102363                     fonts: me.fontFamilies,
102364                     defaultFont: me.defaultFont
102365                 },
102366                 renderSelectors: {
102367                     selectEl: 'select'
102368                 },
102369                 onDisable: function() {
102370                     var selectEl = this.selectEl;
102371                     if (selectEl) {
102372                         selectEl.dom.disabled = true;
102373                     }
102374                     Ext.Component.superclass.onDisable.apply(this, arguments);
102375                 },
102376                 onEnable: function() {
102377                     var selectEl = this.selectEl;
102378                     if (selectEl) {
102379                         selectEl.dom.disabled = false;
102380                     }
102381                     Ext.Component.superclass.onEnable.apply(this, arguments);
102382                 }
102383             });
102384
102385             items.push(
102386                 fontSelectItem,
102387                 '-'
102388             );
102389         }
102390
102391         if (me.enableFormat) {
102392             items.push(
102393                 btn('bold'),
102394                 btn('italic'),
102395                 btn('underline')
102396             );
102397         }
102398
102399         if (me.enableFontSize) {
102400             items.push(
102401                 '-',
102402                 btn('increasefontsize', false, me.adjustFont),
102403                 btn('decreasefontsize', false, me.adjustFont)
102404             );
102405         }
102406
102407         if (me.enableColors) {
102408             items.push(
102409                 '-', {
102410                     itemId: 'forecolor',
102411                     cls: baseCSSPrefix + 'btn-icon',
102412                     iconCls: baseCSSPrefix + 'edit-forecolor',
102413                     overflowText: editor.buttonTips.forecolor.title,
102414                     tooltip: tipsEnabled ? editor.buttonTips.forecolor || undef : undef,
102415                     tabIndex:-1,
102416                     menu : Ext.widget('menu', {
102417                         plain: true,
102418                         items: [{
102419                             xtype: 'colorpicker',
102420                             allowReselect: true,
102421                             focus: Ext.emptyFn,
102422                             value: '000000',
102423                             plain: true,
102424                             clickEvent: 'mousedown',
102425                             handler: function(cp, color) {
102426                                 me.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
102427                                 me.deferFocus();
102428                                 this.up('menu').hide();
102429                             }
102430                         }]
102431                     })
102432                 }, {
102433                     itemId: 'backcolor',
102434                     cls: baseCSSPrefix + 'btn-icon',
102435                     iconCls: baseCSSPrefix + 'edit-backcolor',
102436                     overflowText: editor.buttonTips.backcolor.title,
102437                     tooltip: tipsEnabled ? editor.buttonTips.backcolor || undef : undef,
102438                     tabIndex:-1,
102439                     menu : Ext.widget('menu', {
102440                         plain: true,
102441                         items: [{
102442                             xtype: 'colorpicker',
102443                             focus: Ext.emptyFn,
102444                             value: 'FFFFFF',
102445                             plain: true,
102446                             allowReselect: true,
102447                             clickEvent: 'mousedown',
102448                             handler: function(cp, color) {
102449                                 if (Ext.isGecko) {
102450                                     me.execCmd('useCSS', false);
102451                                     me.execCmd('hilitecolor', color);
102452                                     me.execCmd('useCSS', true);
102453                                     me.deferFocus();
102454                                 } else {
102455                                     me.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
102456                                     me.deferFocus();
102457                                 }
102458                                 this.up('menu').hide();
102459                             }
102460                         }]
102461                     })
102462                 }
102463             );
102464         }
102465
102466         if (me.enableAlignments) {
102467             items.push(
102468                 '-',
102469                 btn('justifyleft'),
102470                 btn('justifycenter'),
102471                 btn('justifyright')
102472             );
102473         }
102474
102475         if (!Ext.isSafari2) {
102476             if (me.enableLinks) {
102477                 items.push(
102478                     '-',
102479                     btn('createlink', false, me.createLink)
102480                 );
102481             }
102482
102483             if (me.enableLists) {
102484                 items.push(
102485                     '-',
102486                     btn('insertorderedlist'),
102487                     btn('insertunorderedlist')
102488                 );
102489             }
102490             if (me.enableSourceEdit) {
102491                 items.push(
102492                     '-',
102493                     btn('sourceedit', true, function(btn){
102494                         me.toggleSourceEdit(!me.sourceEditMode);
102495                     })
102496                 );
102497             }
102498         }
102499
102500         // build the toolbar
102501         toolbar = Ext.widget('toolbar', {
102502             renderTo: me.toolbarWrap,
102503             enableOverflow: true,
102504             items: items
102505         });
102506
102507         if (fontSelectItem) {
102508             me.fontSelect = fontSelectItem.selectEl;
102509
102510             me.mon(me.fontSelect, 'change', function(){
102511                 me.relayCmd('fontname', me.fontSelect.dom.value);
102512                 me.deferFocus();
102513             });
102514         }
102515
102516         // stop form submits
102517         me.mon(toolbar.el, 'click', function(e){
102518             e.preventDefault();
102519         });
102520
102521         me.toolbar = toolbar;
102522     },
102523
102524     onDisable: function() {
102525         this.bodyEl.mask();
102526         this.callParent(arguments);
102527     },
102528
102529     onEnable: function() {
102530         this.bodyEl.unmask();
102531         this.callParent(arguments);
102532     },
102533
102534     /**
102535      * Sets the read only state of this field.
102536      * @param {Boolean} readOnly Whether the field should be read only.
102537      */
102538     setReadOnly: function(readOnly) {
102539         var me = this,
102540             textareaEl = me.textareaEl,
102541             iframeEl = me.iframeEl,
102542             body;
102543
102544         me.readOnly = readOnly;
102545
102546         if (textareaEl) {
102547             textareaEl.dom.readOnly = readOnly;
102548         }
102549
102550         if (me.initialized) {
102551             body = me.getEditorBody();
102552             if (Ext.isIE) {
102553                 // Hide the iframe while setting contentEditable so it doesn't grab focus
102554                 iframeEl.setDisplayed(false);
102555                 body.contentEditable = !readOnly;
102556                 iframeEl.setDisplayed(true);
102557             } else {
102558                 me.setDesignMode(!readOnly);
102559             }
102560             if (body) {
102561                 body.style.cursor = readOnly ? 'default' : 'text';
102562             }
102563             me.disableItems(readOnly);
102564         }
102565     },
102566
102567     /**
102568      * Protected method that will not generally be called directly. It
102569      * is called when the editor initializes the iframe with HTML contents. Override this method if you
102570      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
102571      *
102572      * Note: IE8-Standards has unwanted scroller behavior, so the default meta tag forces IE7 compatibility.
102573      * Also note that forcing IE7 mode works when the page is loaded normally, but if you are using IE's Web
102574      * Developer Tools to manually set the document mode, that will take precedence and override what this
102575      * code sets by default. This can be confusing when developing, but is not a user-facing issue.
102576      */
102577     getDocMarkup: function() {
102578         var me = this,
102579             h = me.iframeEl.getHeight() - me.iframePad * 2;
102580         return Ext.String.format('<html><head><style type="text/css">body{border:0;margin:0;padding:{0}px;height:{1}px;cursor:text}</style></head><body></body></html>', me.iframePad, h);
102581     },
102582
102583     // private
102584     getEditorBody: function() {
102585         var doc = this.getDoc();
102586         return doc.body || doc.documentElement;
102587     },
102588
102589     // private
102590     getDoc: function() {
102591         return (!Ext.isIE && this.iframeEl.dom.contentDocument) || this.getWin().document;
102592     },
102593
102594     // private
102595     getWin: function() {
102596         return Ext.isIE ? this.iframeEl.dom.contentWindow : window.frames[this.iframeEl.dom.name];
102597     },
102598
102599     // private
102600     onRender: function() {
102601         var me = this,
102602             renderSelectors = me.renderSelectors;
102603
102604         Ext.applyIf(renderSelectors, me.getLabelableSelectors());
102605
102606         Ext.applyIf(renderSelectors, {
102607             toolbarWrap: 'div.' + Ext.baseCSSPrefix + 'html-editor-tb',
102608             iframeEl: 'iframe',
102609             textareaEl: 'textarea'
102610         });
102611
102612         me.callParent(arguments);
102613
102614         me.textareaEl.dom.value = me.value || '';
102615
102616         // Start polling for when the iframe document is ready to be manipulated
102617         me.monitorTask = Ext.TaskManager.start({
102618             run: me.checkDesignMode,
102619             scope: me,
102620             interval:100
102621         });
102622
102623         me.createToolbar(me);
102624         me.disableItems(true);
102625     },
102626
102627     initRenderTpl: function() {
102628         var me = this;
102629         if (!me.hasOwnProperty('renderTpl')) {
102630             me.renderTpl = me.getTpl('labelableRenderTpl');
102631         }
102632         return me.callParent();
102633     },
102634
102635     initRenderData: function() {
102636         return Ext.applyIf(this.callParent(), this.getLabelableRenderData());
102637     },
102638
102639     getSubTplData: function() {
102640         var cssPrefix = Ext.baseCSSPrefix;
102641         return {
102642             toolbarWrapCls: cssPrefix + 'html-editor-tb',
102643             textareaCls: cssPrefix + 'hidden',
102644             iframeName: Ext.id(),
102645             iframeSrc: Ext.SSL_SECURE_URL,
102646             size: 'height:100px;'
102647         };
102648     },
102649
102650     getSubTplMarkup: function() {
102651         return this.getTpl('fieldSubTpl').apply(this.getSubTplData());
102652     },
102653
102654     getBodyNaturalWidth: function() {
102655         return 565;
102656     },
102657
102658     initFrameDoc: function() {
102659         var me = this,
102660             doc, task;
102661
102662         Ext.TaskManager.stop(me.monitorTask);
102663
102664         doc = me.getDoc();
102665         me.win = me.getWin();
102666
102667         doc.open();
102668         doc.write(me.getDocMarkup());
102669         doc.close();
102670
102671         task = { // must defer to wait for browser to be ready
102672             run: function() {
102673                 var doc = me.getDoc();
102674                 if (doc.body || doc.readyState === 'complete') {
102675                     Ext.TaskManager.stop(task);
102676                     me.setDesignMode(true);
102677                     Ext.defer(me.initEditor, 10, me);
102678                 }
102679             },
102680             interval : 10,
102681             duration:10000,
102682             scope: me
102683         };
102684         Ext.TaskManager.start(task);
102685     },
102686
102687     checkDesignMode: function() {
102688         var me = this,
102689             doc = me.getDoc();
102690         if (doc && (!doc.editorInitialized || me.getDesignMode() !== 'on')) {
102691             me.initFrameDoc();
102692         }
102693     },
102694
102695     /* private
102696      * set current design mode. To enable, mode can be true or 'on', off otherwise
102697      */
102698     setDesignMode: function(mode) {
102699         var me = this,
102700             doc = me.getDoc();
102701         if (doc) {
102702             if (me.readOnly) {
102703                 mode = false;
102704             }
102705             doc.designMode = (/on|true/i).test(String(mode).toLowerCase()) ?'on':'off';
102706         }
102707     },
102708
102709     // private
102710     getDesignMode: function() {
102711         var doc = this.getDoc();
102712         return !doc ? '' : String(doc.designMode).toLowerCase();
102713     },
102714
102715     disableItems: function(disabled) {
102716         this.getToolbar().items.each(function(item){
102717             if(item.getItemId() !== 'sourceedit'){
102718                 item.setDisabled(disabled);
102719             }
102720         });
102721     },
102722
102723     /**
102724      * Toggles the editor between standard and source edit mode.
102725      * @param {Boolean} sourceEditMode (optional) True for source edit, false for standard
102726      */
102727     toggleSourceEdit: function(sourceEditMode) {
102728         var me = this,
102729             iframe = me.iframeEl,
102730             textarea = me.textareaEl,
102731             hiddenCls = Ext.baseCSSPrefix + 'hidden',
102732             btn = me.getToolbar().getComponent('sourceedit');
102733
102734         if (!Ext.isBoolean(sourceEditMode)) {
102735             sourceEditMode = !me.sourceEditMode;
102736         }
102737         me.sourceEditMode = sourceEditMode;
102738
102739         if (btn.pressed !== sourceEditMode) {
102740             btn.toggle(sourceEditMode);
102741         }
102742         if (sourceEditMode) {
102743             me.disableItems(true);
102744             me.syncValue();
102745             iframe.addCls(hiddenCls);
102746             textarea.removeCls(hiddenCls);
102747             textarea.dom.removeAttribute('tabIndex');
102748             textarea.focus();
102749         }
102750         else {
102751             if (me.initialized) {
102752                 me.disableItems(me.readOnly);
102753             }
102754             me.pushValue();
102755             iframe.removeCls(hiddenCls);
102756             textarea.addCls(hiddenCls);
102757             textarea.dom.setAttribute('tabIndex', -1);
102758             me.deferFocus();
102759         }
102760         me.fireEvent('editmodechange', me, sourceEditMode);
102761         me.doComponentLayout();
102762     },
102763
102764     // private used internally
102765     createLink : function() {
102766         var url = prompt(this.createLinkText, this.defaultLinkValue);
102767         if (url && url !== 'http:/'+'/') {
102768             this.relayCmd('createlink', url);
102769         }
102770     },
102771
102772     clearInvalid: Ext.emptyFn,
102773
102774     // docs inherit from Field
102775     setValue: function(value) {
102776         var me = this,
102777             textarea = me.textareaEl;
102778         me.mixins.field.setValue.call(me, value);
102779         if (value === null || value === undefined) {
102780             value = '';
102781         }
102782         if (textarea) {
102783             textarea.dom.value = value;
102784         }
102785         me.pushValue();
102786         return this;
102787     },
102788
102789     /**
102790      * Protected method that will not generally be called directly. If you need/want
102791      * custom HTML cleanup, this is the method you should override.
102792      * @param {String} html The HTML to be cleaned
102793      * @return {String} The cleaned HTML
102794      */
102795     cleanHtml: function(html) {
102796         html = String(html);
102797         if (Ext.isWebKit) { // strip safari nonsense
102798             html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
102799         }
102800
102801         /*
102802          * Neat little hack. Strips out all the non-digit characters from the default
102803          * value and compares it to the character code of the first character in the string
102804          * because it can cause encoding issues when posted to the server.
102805          */
102806         if (html.charCodeAt(0) === this.defaultValue.replace(/\D/g, '')) {
102807             html = html.substring(1);
102808         }
102809         return html;
102810     },
102811
102812     /**
102813      * @protected method that will not generally be called directly. Syncs the contents
102814      * of the editor iframe with the textarea.
102815      */
102816     syncValue : function(){
102817         var me = this,
102818             body, html, bodyStyle, match;
102819         if (me.initialized) {
102820             body = me.getEditorBody();
102821             html = body.innerHTML;
102822             if (Ext.isWebKit) {
102823                 bodyStyle = body.getAttribute('style'); // Safari puts text-align styles on the body element!
102824                 match = bodyStyle.match(/text-align:(.*?);/i);
102825                 if (match && match[1]) {
102826                     html = '<div style="' + match[0] + '">' + html + '</div>';
102827                 }
102828             }
102829             html = me.cleanHtml(html);
102830             if (me.fireEvent('beforesync', me, html) !== false) {
102831                 me.textareaEl.dom.value = html;
102832                 me.fireEvent('sync', me, html);
102833             }
102834         }
102835     },
102836
102837     //docs inherit from Field
102838     getValue : function() {
102839         var me = this,
102840             value;
102841         if (!me.sourceEditMode) {
102842             me.syncValue();
102843         }
102844         value = me.rendered ? me.textareaEl.dom.value : me.value;
102845         me.value = value;
102846         return value;
102847     },
102848
102849     /**
102850      * @protected method that will not generally be called directly. Pushes the value of the textarea
102851      * into the iframe editor.
102852      */
102853     pushValue: function() {
102854         var me = this,
102855             v;
102856         if(me.initialized){
102857             v = me.textareaEl.dom.value || '';
102858             if (!me.activated && v.length < 1) {
102859                 v = me.defaultValue;
102860             }
102861             if (me.fireEvent('beforepush', me, v) !== false) {
102862                 me.getEditorBody().innerHTML = v;
102863                 if (Ext.isGecko) {
102864                     // Gecko hack, see: https://bugzilla.mozilla.org/show_bug.cgi?id=232791#c8
102865                     me.setDesignMode(false);  //toggle off first
102866                     me.setDesignMode(true);
102867                 }
102868                 me.fireEvent('push', me, v);
102869             }
102870         }
102871     },
102872
102873     // private
102874     deferFocus : function(){
102875          this.focus(false, true);
102876     },
102877
102878     getFocusEl: function() {
102879         var me = this,
102880             win = me.win;
102881         return win && !me.sourceEditMode ? win : me.textareaEl;
102882     },
102883
102884     // private
102885     initEditor : function(){
102886         //Destroying the component during/before initEditor can cause issues.
102887         try {
102888             var me = this,
102889                 dbody = me.getEditorBody(),
102890                 ss = me.textareaEl.getStyles('font-size', 'font-family', 'background-image', 'background-repeat', 'background-color', 'color'),
102891                 doc,
102892                 fn;
102893
102894             ss['background-attachment'] = 'fixed'; // w3c
102895             dbody.bgProperties = 'fixed'; // ie
102896
102897             Ext.core.DomHelper.applyStyles(dbody, ss);
102898
102899             doc = me.getDoc();
102900
102901             if (doc) {
102902                 try {
102903                     Ext.EventManager.removeAll(doc);
102904                 } catch(e) {}
102905             }
102906
102907             /*
102908              * We need to use createDelegate here, because when using buffer, the delayed task is added
102909              * as a property to the function. When the listener is removed, the task is deleted from the function.
102910              * Since onEditorEvent is shared on the prototype, if we have multiple html editors, the first time one of the editors
102911              * is destroyed, it causes the fn to be deleted from the prototype, which causes errors. Essentially, we're just anonymizing the function.
102912              */
102913             fn = Ext.Function.bind(me.onEditorEvent, me);
102914             Ext.EventManager.on(doc, {
102915                 mousedown: fn,
102916                 dblclick: fn,
102917                 click: fn,
102918                 keyup: fn,
102919                 buffer:100
102920             });
102921
102922             // These events need to be relayed from the inner document (where they stop
102923             // bubbling) up to the outer document. This has to be done at the DOM level so
102924             // the event reaches listeners on elements like the document body. The effected
102925             // mechanisms that depend on this bubbling behavior are listed to the right
102926             // of the event.
102927             fn = me.onRelayedEvent;
102928             Ext.EventManager.on(doc, {
102929                 mousedown: fn, // menu dismisal (MenuManager) and Window onMouseDown (toFront)
102930                 mousemove: fn, // window resize drag detection
102931                 mouseup: fn,   // window resize termination
102932                 click: fn,     // not sure, but just to be safe
102933                 dblclick: fn,  // not sure again
102934                 scope: me
102935             });
102936
102937             if (Ext.isGecko) {
102938                 Ext.EventManager.on(doc, 'keypress', me.applyCommand, me);
102939             }
102940             if (me.fixKeys) {
102941                 Ext.EventManager.on(doc, 'keydown', me.fixKeys, me);
102942             }
102943
102944             // We need to be sure we remove all our events from the iframe on unload or we're going to LEAK!
102945             Ext.EventManager.on(window, 'unload', me.beforeDestroy, me);
102946             doc.editorInitialized = true;
102947
102948             me.initialized = true;
102949             me.pushValue();
102950             me.setReadOnly(me.readOnly);
102951             me.fireEvent('initialize', me);
102952         } catch(ex) {
102953             // ignore (why?)
102954         }
102955     },
102956
102957     // private
102958     beforeDestroy : function(){
102959         var me = this,
102960             monitorTask = me.monitorTask,
102961             doc, prop;
102962
102963         if (monitorTask) {
102964             Ext.TaskManager.stop(monitorTask);
102965         }
102966         if (me.rendered) {
102967             try {
102968                 doc = me.getDoc();
102969                 if (doc) {
102970                     Ext.EventManager.removeAll(doc);
102971                     for (prop in doc) {
102972                         if (doc.hasOwnProperty(prop)) {
102973                             delete doc[prop];
102974                         }
102975                     }
102976                 }
102977             } catch(e) {
102978                 // ignore (why?)
102979             }
102980             Ext.destroyMembers('tb', 'toolbarWrap', 'iframeEl', 'textareaEl');
102981         }
102982         me.callParent();
102983     },
102984
102985     // private
102986     onRelayedEvent: function (event) {
102987         // relay event from the iframe's document to the document that owns the iframe...
102988
102989         var iframeEl = this.iframeEl,
102990             iframeXY = iframeEl.getXY(),
102991             eventXY = event.getXY();
102992
102993         // the event from the inner document has XY relative to that document's origin,
102994         // so adjust it to use the origin of the iframe in the outer document:
102995         event.xy = [iframeXY[0] + eventXY[0], iframeXY[1] + eventXY[1]];
102996
102997         event.injectEvent(iframeEl); // blame the iframe for the event...
102998
102999         event.xy = eventXY; // restore the original XY (just for safety)
103000     },
103001
103002     // private
103003     onFirstFocus : function(){
103004         var me = this,
103005             selection, range;
103006         me.activated = true;
103007         me.disableItems(me.readOnly);
103008         if (Ext.isGecko) { // prevent silly gecko errors
103009             me.win.focus();
103010             selection = me.win.getSelection();
103011             if (!selection.focusNode || selection.focusNode.nodeType !== 3) {
103012                 range = selection.getRangeAt(0);
103013                 range.selectNodeContents(me.getEditorBody());
103014                 range.collapse(true);
103015                 me.deferFocus();
103016             }
103017             try {
103018                 me.execCmd('useCSS', true);
103019                 me.execCmd('styleWithCSS', false);
103020             } catch(e) {
103021                 // ignore (why?)
103022             }
103023         }
103024         me.fireEvent('activate', me);
103025     },
103026
103027     // private
103028     adjustFont: function(btn) {
103029         var adjust = btn.getItemId() === 'increasefontsize' ? 1 : -1,
103030             size = this.getDoc().queryCommandValue('FontSize') || '2',
103031             isPxSize = Ext.isString(size) && size.indexOf('px') !== -1,
103032             isSafari;
103033         size = parseInt(size, 10);
103034         if (isPxSize) {
103035             // Safari 3 values
103036             // 1 = 10px, 2 = 13px, 3 = 16px, 4 = 18px, 5 = 24px, 6 = 32px
103037             if (size <= 10) {
103038                 size = 1 + adjust;
103039             }
103040             else if (size <= 13) {
103041                 size = 2 + adjust;
103042             }
103043             else if (size <= 16) {
103044                 size = 3 + adjust;
103045             }
103046             else if (size <= 18) {
103047                 size = 4 + adjust;
103048             }
103049             else if (size <= 24) {
103050                 size = 5 + adjust;
103051             }
103052             else {
103053                 size = 6 + adjust;
103054             }
103055             size = Ext.Number.constrain(size, 1, 6);
103056         } else {
103057             isSafari = Ext.isSafari;
103058             if (isSafari) { // safari
103059                 adjust *= 2;
103060             }
103061             size = Math.max(1, size + adjust) + (isSafari ? 'px' : 0);
103062         }
103063         this.execCmd('FontSize', size);
103064     },
103065
103066     // private
103067     onEditorEvent: function(e) {
103068         this.updateToolbar();
103069     },
103070
103071     /**
103072      * Protected method that will not generally be called directly. It triggers
103073      * a toolbar update by reading the markup state of the current selection in the editor.
103074      */
103075     updateToolbar: function() {
103076         var me = this,
103077             btns, doc, name, fontSelect;
103078
103079         if (me.readOnly) {
103080             return;
103081         }
103082
103083         if (!me.activated) {
103084             me.onFirstFocus();
103085             return;
103086         }
103087
103088         btns = me.getToolbar().items.map;
103089         doc = me.getDoc();
103090
103091         if (me.enableFont && !Ext.isSafari2) {
103092             name = (doc.queryCommandValue('FontName') || me.defaultFont).toLowerCase();
103093             fontSelect = me.fontSelect.dom;
103094             if (name !== fontSelect.value) {
103095                 fontSelect.value = name;
103096             }
103097         }
103098
103099         function updateButtons() {
103100             Ext.Array.forEach(Ext.Array.toArray(arguments), function(name) {
103101                 btns[name].toggle(doc.queryCommandState(name));
103102             });
103103         }
103104         if(me.enableFormat){
103105             updateButtons('bold', 'italic', 'underline');
103106         }
103107         if(me.enableAlignments){
103108             updateButtons('justifyleft', 'justifycenter', 'justifyright');
103109         }
103110         if(!Ext.isSafari2 && me.enableLists){
103111             updateButtons('insertorderedlist', 'insertunorderedlist');
103112         }
103113
103114         Ext.menu.Manager.hideAll();
103115
103116         me.syncValue();
103117     },
103118
103119     // private
103120     relayBtnCmd: function(btn) {
103121         this.relayCmd(btn.getItemId());
103122     },
103123
103124     /**
103125      * Executes a Midas editor command on the editor document and performs necessary focus and
103126      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
103127      * @param {String} cmd The Midas command
103128      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
103129      */
103130     relayCmd: function(cmd, value) {
103131         Ext.defer(function() {
103132             var me = this;
103133             me.focus();
103134             me.execCmd(cmd, value);
103135             me.updateToolbar();
103136         }, 10, this);
103137     },
103138
103139     /**
103140      * Executes a Midas editor command directly on the editor document.
103141      * For visual commands, you should use {@link #relayCmd} instead.
103142      * <b>This should only be called after the editor is initialized.</b>
103143      * @param {String} cmd The Midas command
103144      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
103145      */
103146     execCmd : function(cmd, value){
103147         var me = this,
103148             doc = me.getDoc(),
103149             undef;
103150         doc.execCommand(cmd, false, value === undef ? null : value);
103151         me.syncValue();
103152     },
103153
103154     // private
103155     applyCommand : function(e){
103156         if (e.ctrlKey) {
103157             var me = this,
103158                 c = e.getCharCode(), cmd;
103159             if (c > 0) {
103160                 c = String.fromCharCode(c);
103161                 switch (c) {
103162                     case 'b':
103163                         cmd = 'bold';
103164                     break;
103165                     case 'i':
103166                         cmd = 'italic';
103167                     break;
103168                     case 'u':
103169                         cmd = 'underline';
103170                     break;
103171                 }
103172                 if (cmd) {
103173                     me.win.focus();
103174                     me.execCmd(cmd);
103175                     me.deferFocus();
103176                     e.preventDefault();
103177                 }
103178             }
103179         }
103180     },
103181
103182     /**
103183      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
103184      * to insert text.
103185      * @param {String} text
103186      */
103187     insertAtCursor : function(text){
103188         var me = this,
103189             range;
103190
103191         if (me.activated) {
103192             me.win.focus();
103193             if (Ext.isIE) {
103194                 range = me.getDoc().selection.createRange();
103195                 if (range) {
103196                     range.pasteHTML(text);
103197                     me.syncValue();
103198                     me.deferFocus();
103199                 }
103200             }else{
103201                 me.execCmd('InsertHTML', text);
103202                 me.deferFocus();
103203             }
103204         }
103205     },
103206
103207     // private
103208     fixKeys: function() { // load time branching for fastest keydown performance
103209         if (Ext.isIE) {
103210             return function(e){
103211                 var me = this,
103212                     k = e.getKey(),
103213                     doc = me.getDoc(),
103214                     range, target;
103215                 if (k === e.TAB) {
103216                     e.stopEvent();
103217                     range = doc.selection.createRange();
103218                     if(range){
103219                         range.collapse(true);
103220                         range.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;');
103221                         me.deferFocus();
103222                     }
103223                 }
103224                 else if (k === e.ENTER) {
103225                     range = doc.selection.createRange();
103226                     if (range) {
103227                         target = range.parentElement();
103228                         if(!target || target.tagName.toLowerCase() !== 'li'){
103229                             e.stopEvent();
103230                             range.pasteHTML('<br />');
103231                             range.collapse(false);
103232                             range.select();
103233                         }
103234                     }
103235                 }
103236             };
103237         }
103238
103239         if (Ext.isOpera) {
103240             return function(e){
103241                 var me = this;
103242                 if (e.getKey() === e.TAB) {
103243                     e.stopEvent();
103244                     me.win.focus();
103245                     me.execCmd('InsertHTML','&nbsp;&nbsp;&nbsp;&nbsp;');
103246                     me.deferFocus();
103247                 }
103248             };
103249         }
103250
103251         if (Ext.isWebKit) {
103252             return function(e){
103253                 var me = this,
103254                     k = e.getKey();
103255                 if (k === e.TAB) {
103256                     e.stopEvent();
103257                     me.execCmd('InsertText','\t');
103258                     me.deferFocus();
103259                 }
103260                 else if (k === e.ENTER) {
103261                     e.stopEvent();
103262                     me.execCmd('InsertHtml','<br /><br />');
103263                     me.deferFocus();
103264                 }
103265             };
103266         }
103267
103268         return null; // not needed, so null
103269     }(),
103270
103271     /**
103272      * Returns the editor's toolbar. <b>This is only available after the editor has been rendered.</b>
103273      * @return {Ext.toolbar.Toolbar}
103274      */
103275     getToolbar : function(){
103276         return this.toolbar;
103277     },
103278
103279     /**
103280      * Object collection of toolbar tooltips for the buttons in the editor. The key
103281      * is the command id associated with that button and the value is a valid QuickTips object.
103282      * For example:
103283 <pre><code>
103284 {
103285     bold : {
103286         title: 'Bold (Ctrl+B)',
103287         text: 'Make the selected text bold.',
103288         cls: 'x-html-editor-tip'
103289     },
103290     italic : {
103291         title: 'Italic (Ctrl+I)',
103292         text: 'Make the selected text italic.',
103293         cls: 'x-html-editor-tip'
103294     },
103295     ...
103296 </code></pre>
103297     * @type Object
103298      */
103299     buttonTips : {
103300         bold : {
103301             title: 'Bold (Ctrl+B)',
103302             text: 'Make the selected text bold.',
103303             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103304         },
103305         italic : {
103306             title: 'Italic (Ctrl+I)',
103307             text: 'Make the selected text italic.',
103308             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103309         },
103310         underline : {
103311             title: 'Underline (Ctrl+U)',
103312             text: 'Underline the selected text.',
103313             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103314         },
103315         increasefontsize : {
103316             title: 'Grow Text',
103317             text: 'Increase the font size.',
103318             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103319         },
103320         decreasefontsize : {
103321             title: 'Shrink Text',
103322             text: 'Decrease the font size.',
103323             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103324         },
103325         backcolor : {
103326             title: 'Text Highlight Color',
103327             text: 'Change the background color of the selected text.',
103328             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103329         },
103330         forecolor : {
103331             title: 'Font Color',
103332             text: 'Change the color of the selected text.',
103333             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103334         },
103335         justifyleft : {
103336             title: 'Align Text Left',
103337             text: 'Align text to the left.',
103338             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103339         },
103340         justifycenter : {
103341             title: 'Center Text',
103342             text: 'Center text in the editor.',
103343             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103344         },
103345         justifyright : {
103346             title: 'Align Text Right',
103347             text: 'Align text to the right.',
103348             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103349         },
103350         insertunorderedlist : {
103351             title: 'Bullet List',
103352             text: 'Start a bulleted list.',
103353             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103354         },
103355         insertorderedlist : {
103356             title: 'Numbered List',
103357             text: 'Start a numbered list.',
103358             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103359         },
103360         createlink : {
103361             title: 'Hyperlink',
103362             text: 'Make the selected text a hyperlink.',
103363             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103364         },
103365         sourceedit : {
103366             title: 'Source Edit',
103367             text: 'Switch to source editing mode.',
103368             cls: Ext.baseCSSPrefix + 'html-editor-tip'
103369         }
103370     }
103371
103372     // hide stuff that is not compatible
103373     /**
103374      * @event blur
103375      * @hide
103376      */
103377     /**
103378      * @event change
103379      * @hide
103380      */
103381     /**
103382      * @event focus
103383      * @hide
103384      */
103385     /**
103386      * @event specialkey
103387      * @hide
103388      */
103389     /**
103390      * @cfg {String} fieldCls @hide
103391      */
103392     /**
103393      * @cfg {String} focusCls @hide
103394      */
103395     /**
103396      * @cfg {String} autoCreate @hide
103397      */
103398     /**
103399      * @cfg {String} inputType @hide
103400      */
103401     /**
103402      * @cfg {String} invalidCls @hide
103403      */
103404     /**
103405      * @cfg {String} invalidText @hide
103406      */
103407     /**
103408      * @cfg {String} msgFx @hide
103409      */
103410     /**
103411      * @cfg {Boolean} allowDomMove  @hide
103412      */
103413     /**
103414      * @cfg {String} applyTo @hide
103415      */
103416     /**
103417      * @cfg {String} readOnly  @hide
103418      */
103419     /**
103420      * @cfg {String} tabIndex  @hide
103421      */
103422     /**
103423      * @method validate
103424      * @hide
103425      */
103426 });
103427
103428 /**
103429  * @class Ext.form.field.Radio
103430  * @extends Ext.form.field.Checkbox
103431
103432 Single radio field. Similar to checkbox, but automatically handles making sure only one radio is checked
103433 at a time within a group of radios with the same name.
103434
103435 __Labeling:__
103436 In addition to the {@link Ext.form.Labelable standard field labeling options}, radio buttons
103437 may be given an optional {@link #boxLabel} which will be displayed immediately to the right of the input. Also
103438 see {@link Ext.form.RadioGroup} for a convenient method of grouping related radio buttons.
103439
103440 __Values:__
103441 The main value of a Radio field is a boolean, indicating whether or not the radio is checked.
103442
103443 The following values will check the radio:
103444 * `true`
103445 * `'true'`
103446 * `'1'`
103447 * `'on'`
103448
103449 Any other value will uncheck it.
103450
103451 In addition to the main boolean value, you may also specify a separate {@link #inputValue}. This will be sent
103452 as the parameter value when the form is {@link Ext.form.Basic#submit submitted}. You will want to set this
103453 value if you have multiple radio buttons with the same {@link #name}, as is almost always the case.
103454 {@img Ext.form.Radio/Ext.form.Radio.png Ext.form.Radio component}
103455 __Example usage:__
103456
103457     Ext.create('Ext.form.Panel', {
103458         title      : 'Order Form',
103459         width      : 300,
103460         bodyPadding: 10,
103461         renderTo   : Ext.getBody(),
103462         items: [
103463             {
103464                 xtype      : 'fieldcontainer',
103465                 fieldLabel : 'Size',
103466                 defaultType: 'radiofield',
103467                 defaults: {
103468                     flex: 1
103469                 },
103470                 layout: 'hbox',
103471                 items: [
103472                     {
103473                         boxLabel  : 'M',
103474                         name      : 'size',
103475                         inputValue: 'm',
103476                         id        : 'radio1'
103477                     }, {
103478                         boxLabel  : 'L',
103479                         name      : 'size',
103480                         inputValue: 'l',
103481                         id        : 'radio2'
103482                     }, {
103483                         boxLabel  : 'XL',
103484                         name      : 'size',
103485                         inputValue: 'xl',
103486                         id        : 'radio3'
103487                     }
103488                 ]
103489             },
103490             {
103491                 xtype      : 'fieldcontainer',
103492                 fieldLabel : 'Color',
103493                 defaultType: 'radiofield',
103494                 defaults: {
103495                     flex: 1
103496                 },
103497                 layout: 'hbox',
103498                 items: [
103499                     {
103500                         boxLabel  : 'Blue',
103501                         name      : 'color',
103502                         inputValue: 'blue',
103503                         id        : 'radio4'
103504                     }, {
103505                         boxLabel  : 'Grey',
103506                         name      : 'color',
103507                         inputValue: 'grey',
103508                         id        : 'radio5'
103509                     }, {
103510                         boxLabel  : 'Black',
103511                         name      : 'color',
103512                         inputValue: 'black',
103513                         id        : 'radio6'
103514                     }
103515                 ]
103516             }
103517         ],
103518         bbar: [
103519             {
103520                 text: 'Smaller Size',
103521                 handler: function() {
103522                     var radio1 = Ext.getCmp('radio1'),
103523                         radio2 = Ext.getCmp('radio2'),
103524                         radio3 = Ext.getCmp('radio3');
103525     
103526                     //if L is selected, change to M
103527                     if (radio2.getValue()) {
103528                         radio1.setValue(true);
103529                         return;
103530                     }
103531     
103532                     //if XL is selected, change to L
103533                     if (radio3.getValue()) {
103534                         radio2.setValue(true);
103535                         return;
103536                     }
103537     
103538                     //if nothing is set, set size to S
103539                     radio1.setValue(true);
103540                 }
103541             },
103542             {
103543                 text: 'Larger Size',
103544                 handler: function() {
103545                     var radio1 = Ext.getCmp('radio1'),
103546                         radio2 = Ext.getCmp('radio2'),
103547                         radio3 = Ext.getCmp('radio3');
103548     
103549                     //if M is selected, change to L
103550                     if (radio1.getValue()) {
103551                         radio2.setValue(true);
103552                         return;
103553                     }
103554     
103555                     //if L is selected, change to XL
103556                     if (radio2.getValue()) {
103557                         radio3.setValue(true);
103558                         return;
103559                     }
103560     
103561                     //if nothing is set, set size to XL
103562                     radio3.setValue(true);
103563                 }
103564             },
103565             '-',
103566             {
103567                 text: 'Select color',
103568                 menu: {
103569                     indent: false,
103570                     items: [
103571                         {
103572                             text: 'Blue',
103573                             handler: function() {
103574                                 var radio = Ext.getCmp('radio4');
103575                                 radio.setValue(true);
103576                             }
103577                         },
103578                         {
103579                             text: 'Grey',
103580                             handler: function() {
103581                                 var radio = Ext.getCmp('radio5');
103582                                 radio.setValue(true);
103583                             }
103584                         },
103585                         {
103586                             text: 'Black',
103587                             handler: function() {
103588                                 var radio = Ext.getCmp('radio6');
103589                                 radio.setValue(true);
103590                             }
103591                         }
103592                     ]
103593                 }
103594             }
103595         ]
103596     });
103597
103598
103599  * @constructor
103600  * Creates a new Radio
103601  * @param {Object} config Configuration options
103602  * @xtype radio
103603  * @docauthor Robert Dougan <rob@sencha.com>
103604  * @markdown
103605  */
103606 Ext.define('Ext.form.field.Radio', {
103607     extend:'Ext.form.field.Checkbox',
103608     alias: ['widget.radiofield', 'widget.radio'],
103609     alternateClassName: 'Ext.form.Radio',
103610     requires: ['Ext.form.RadioManager'],
103611
103612     isRadio: true,
103613
103614     /**
103615      * @cfg {String} uncheckedValue @hide
103616      */
103617
103618     // private
103619     inputType: 'radio',
103620     ariaRole: 'radio',
103621
103622     /**
103623      * If this radio is part of a group, it will return the selected value
103624      * @return {String}
103625      */
103626     getGroupValue: function() {
103627         var selected = this.getManager().getChecked(this.name);
103628         return selected ? selected.inputValue : null;
103629     },
103630
103631     /**
103632      * @private Handle click on the radio button
103633      */
103634     onBoxClick: function(e) {
103635         var me = this;
103636         if (!me.disabled && !me.readOnly) {
103637             this.setValue(true);
103638         }
103639     },
103640
103641     /**
103642      * Sets either the checked/unchecked status of this Radio, or, if a string value
103643      * is passed, checks a sibling Radio of the same name whose value is the value specified.
103644      * @param value {String/Boolean} Checked value, or the value of the sibling radio button to check.
103645      * @return {Ext.form.field.Radio} this
103646      */
103647     setValue: function(v) {
103648         var me = this,
103649             active;
103650
103651         if (Ext.isBoolean(v)) {
103652             me.callParent(arguments);
103653         } else {
103654             active = me.getManager().getWithValue(me.name, v).getAt(0);
103655             if (active) {
103656                 active.setValue(true);
103657             }
103658         }
103659         return me;
103660     },
103661
103662     /**
103663      * Returns the submit value for the checkbox which can be used when submitting forms.
103664      * @return {Boolean/null} True if checked, null if not.
103665      */
103666     getSubmitValue: function() {
103667         return this.checked ? this.inputValue : null;
103668     },
103669
103670     // inherit docs
103671     onChange: function(newVal, oldVal) {
103672         var me = this;
103673         me.callParent(arguments);
103674
103675         if (newVal) {
103676             this.getManager().getByName(me.name).each(function(item){
103677                 if (item !== me) {
103678                     item.setValue(false);
103679                 }
103680             }, me);
103681         }
103682     },
103683
103684     // inherit docs
103685     beforeDestroy: function(){
103686         this.callParent();
103687         this.getManager().removeAtKey(this.id);
103688     },
103689
103690     // inherit docs
103691     getManager: function() {
103692         return Ext.form.RadioManager;
103693     }
103694 });
103695
103696 /**
103697  * @class Ext.picker.Time
103698  * @extends Ext.view.BoundList
103699  * <p>A time picker which provides a list of times from which to choose. This is used by the
103700  * {@link Ext.form.field.Time} class to allow browsing and selection of valid times, but could also be used
103701  * with other components.</p>
103702  * <p>By default, all times starting at midnight and incrementing every 15 minutes will be presented.
103703  * This list of available times can be controlled using the {@link #minValue}, {@link #maxValue}, and
103704  * {@link #increment} configuration properties. The format of the times presented in the list can be
103705  * customized with the {@link #format} config.</p>
103706  * <p>To handle when the user selects a time from the list, you can subscribe to the {@link #selectionchange}
103707  * event.</p>
103708  *
103709  * {@img Ext.picker.Time/Ext.picker.Time.png Ext.picker.Time component}
103710  *
103711  * ## Code
103712      new Ext.create('Ext.picker.Time', {
103713         width: 60,
103714         minValue: Ext.Date.parse('04:30:00 AM', 'h:i:s A'),
103715         maxValue: Ext.Date.parse('08:00:00 AM', 'h:i:s A'),
103716         renderTo: Ext.getBody()
103717     });
103718  *
103719  * @constructor
103720  * Create a new TimePicker
103721  * @param {Object} config The config object
103722  *
103723  * @xtype timepicker
103724  */
103725 Ext.define('Ext.picker.Time', {
103726     extend: 'Ext.view.BoundList',
103727     alias: 'widget.timepicker',
103728     requires: ['Ext.data.Store', 'Ext.Date'],
103729
103730     /**
103731      * @cfg {Date} minValue
103732      * The minimum time to be shown in the list of times. This must be a Date object (only the time fields
103733      * will be used); no parsing of String values will be done. Defaults to undefined.
103734      */
103735
103736     /**
103737      * @cfg {Date} maxValue
103738      * The maximum time to be shown in the list of times. This must be a Date object (only the time fields
103739      * will be used); no parsing of String values will be done. Defaults to undefined.
103740      */
103741
103742     /**
103743      * @cfg {Number} increment
103744      * The number of minutes between each time value in the list (defaults to 15).
103745      */
103746     increment: 15,
103747
103748     /**
103749      * @cfg {String} format
103750      * The default time format string which can be overriden for localization support. The format must be
103751      * valid according to {@link Ext.Date#parse} (defaults to 'g:i A', e.g., '3:15 PM'). For 24-hour time
103752      * format try 'H:i' instead.
103753      */
103754     format : "g:i A",
103755
103756     /**
103757      * @hide
103758      * The field in the implicitly-generated Model objects that gets displayed in the list. This is
103759      * an internal field name only and is not useful to change via config.
103760      */
103761     displayField: 'disp',
103762
103763     /**
103764      * @private
103765      * Year, month, and day that all times will be normalized into internally.
103766      */
103767     initDate: [2008,1,1],
103768
103769     componentCls: Ext.baseCSSPrefix + 'timepicker',
103770
103771     /**
103772      * @hide
103773      */
103774     loadingText: '',
103775
103776     initComponent: function() {
103777         var me = this,
103778             dateUtil = Ext.Date,
103779             clearTime = dateUtil.clearTime,
103780             initDate = me.initDate.join('/');
103781
103782         // Set up absolute min and max for the entire day
103783         me.absMin = clearTime(new Date(initDate));
103784         me.absMax = dateUtil.add(clearTime(new Date(initDate)), 'mi', (24 * 60) - 1);
103785
103786         me.store = me.createStore();
103787         me.updateList();
103788
103789         this.callParent();
103790     },
103791
103792     /**
103793      * Set the {@link #minValue} and update the list of available times. This must be a Date
103794      * object (only the time fields will be used); no parsing of String values will be done.
103795      * @param {Date} value
103796      */
103797     setMinValue: function(value) {
103798         this.minValue = value;
103799         this.updateList();
103800     },
103801
103802     /**
103803      * Set the {@link #maxValue} and update the list of available times. This must be a Date
103804      * object (only the time fields will be used); no parsing of String values will be done.
103805      * @param {Date} value
103806      */
103807     setMaxValue: function(value) {
103808         this.maxValue = value;
103809         this.updateList();
103810     },
103811
103812     /**
103813      * @private
103814      * Sets the year/month/day of the given Date object to the {@link #initDate}, so that only
103815      * the time fields are significant. This makes values suitable for time comparison.
103816      * @param {Date} date
103817      */
103818     normalizeDate: function(date) {
103819         var initDate = this.initDate;
103820         date.setFullYear(initDate[0], initDate[1] - 1, initDate[2]);
103821         return date;
103822     },
103823
103824     /**
103825      * Update the list of available times in the list to be constrained within the
103826      * {@link #minValue} and {@link #maxValue}.
103827      */
103828     updateList: function() {
103829         var me = this,
103830             min = me.normalizeDate(me.minValue || me.absMin),
103831             max = me.normalizeDate(me.maxValue || me.absMax);
103832
103833         me.store.filterBy(function(record) {
103834             var date = record.get('date');
103835             return date >= min && date <= max;
103836         });
103837     },
103838
103839     /**
103840      * @private
103841      * Creates the internal {@link Ext.data.Store} that contains the available times. The store
103842      * is loaded with all possible times, and it is later filtered to hide those times outside
103843      * the minValue/maxValue.
103844      */
103845     createStore: function() {
103846         var me = this,
103847             utilDate = Ext.Date,
103848             times = [],
103849             min = me.absMin,
103850             max = me.absMax;
103851
103852         while(min <= max){
103853             times.push({
103854                 disp: utilDate.dateFormat(min, me.format),
103855                 date: min
103856             });
103857             min = utilDate.add(min, 'mi', me.increment);
103858         }
103859
103860         return Ext.create('Ext.data.Store', {
103861             fields: ['disp', 'date'],
103862             data: times
103863         });
103864     }
103865
103866 });
103867
103868 /**
103869  * @class Ext.form.field.Time
103870  * @extends Ext.form.field.Picker
103871  * <p>Provides a time input field with a time dropdown and automatic time validation.</p>
103872  * <p>This field recognizes and uses JavaScript Date objects as its main {@link #value} type (only the time
103873  * portion of the date is used; the month/day/year are ignored). In addition, it recognizes string values which
103874  * are parsed according to the {@link #format} and/or {@link #altFormats} configs. These may be reconfigured
103875  * to use time formats appropriate for the user's locale.</p>
103876  * <p>The field may be limited to a certain range of times by using the {@link #minValue} and {@link #maxValue}
103877  * configs, and the interval between time options in the dropdown can be changed with the {@link #increment} config.</p>
103878  * {@img Ext.form.Time/Ext.form.Time.png Ext.form.Time component}
103879  * <p>Example usage:</p>
103880  * <pre><code>
103881     Ext.create('Ext.form.Panel', {
103882         title: 'Time Card',
103883         width: 300,
103884         bodyPadding: 10,
103885         renderTo: Ext.getBody(),        
103886         items: [{
103887             xtype: 'timefield',
103888             name: 'in',
103889             fieldLabel: 'Time In',
103890             minValue: '6:00 AM',
103891             maxValue: '8:00 PM',
103892             increment: 30,
103893             anchor: '100%'
103894         }, {
103895             xtype: 'timefield',
103896             name: 'out',
103897             fieldLabel: 'Time Out',
103898             minValue: '6:00 AM',
103899             maxValue: '8:00 PM',
103900             increment: 30,
103901             anchor: '100%'
103902        }]
103903     });
103904 </code></pre>
103905  * @constructor
103906  * Create a new Time field
103907  * @param {Object} config
103908  * @xtype timefield
103909  */
103910 Ext.define('Ext.form.field.Time', {
103911     extend:'Ext.form.field.Picker',
103912     alias: 'widget.timefield',
103913     requires: ['Ext.form.field.Date', 'Ext.picker.Time', 'Ext.view.BoundListKeyNav', 'Ext.Date'],
103914     alternateClassName: ['Ext.form.TimeField', 'Ext.form.Time'],
103915
103916     /**
103917      * @cfg {String} triggerCls
103918      * An additional CSS class used to style the trigger button.  The trigger will always get the
103919      * {@link #triggerBaseCls} by default and <tt>triggerCls</tt> will be <b>appended</b> if specified.
103920      * Defaults to <tt>'x-form-time-trigger'</tt> for the Time field trigger.
103921      */
103922     triggerCls: Ext.baseCSSPrefix + 'form-time-trigger',
103923
103924     /**
103925      * @cfg {Date/String} minValue
103926      * The minimum allowed time. Can be either a Javascript date object with a valid time value or a string
103927      * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
103928      */
103929
103930     /**
103931      * @cfg {Date/String} maxValue
103932      * The maximum allowed time. Can be either a Javascript date object with a valid time value or a string
103933      * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
103934      */
103935
103936     /**
103937      * @cfg {String} minText
103938      * The error text to display when the entered time is before {@link #minValue} (defaults to
103939      * 'The time in this field must be equal to or after {0}').
103940      */
103941     minText : "The time in this field must be equal to or after {0}",
103942
103943     /**
103944      * @cfg {String} maxText
103945      * The error text to display when the entered time is after {@link #maxValue} (defaults to
103946      * 'The time in this field must be equal to or before {0}').
103947      */
103948     maxText : "The time in this field must be equal to or before {0}",
103949
103950     /**
103951      * @cfg {String} invalidText
103952      * The error text to display when the time in the field is invalid (defaults to
103953      * '{value} is not a valid time').
103954      */
103955     invalidText : "{0} is not a valid time",
103956
103957     /**
103958      * @cfg {String} format
103959      * The default time format string which can be overriden for localization support.  The format must be
103960      * valid according to {@link Ext.Date#parse} (defaults to 'g:i A', e.g., '3:15 PM').  For 24-hour time
103961      * format try 'H:i' instead.
103962      */
103963     format : "g:i A",
103964
103965     /**
103966      * @cfg {String} submitFormat The date format string which will be submitted to the server.
103967      * The format must be valid according to {@link Ext.Date#parse} (defaults to <tt>{@link #format}</tt>).
103968      */
103969
103970     /**
103971      * @cfg {String} altFormats
103972      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
103973      * format (defaults to 'g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A').
103974      */
103975     altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A",
103976
103977     /**
103978      * @cfg {Number} increment
103979      * The number of minutes between each time value in the list (defaults to 15).
103980      */
103981     increment: 15,
103982
103983     /**
103984      * @cfg {Number} pickerMaxHeight
103985      * The maximum height of the {@link Ext.picker.Time} dropdown. Defaults to 300.
103986      */
103987     pickerMaxHeight: 300,
103988
103989     /**
103990      * @cfg {Boolean} selectOnTab
103991      * Whether the Tab key should select the currently highlighted item. Defaults to <tt>true</tt>.
103992      */
103993     selectOnTab: true,
103994
103995     /**
103996      * @private
103997      * This is the date to use when generating time values in the absence of either minValue
103998      * or maxValue.  Using the current date causes DST issues on DST boundary dates, so this is an
103999      * arbitrary "safe" date that can be any date aside from DST boundary dates.
104000      */
104001     initDate: '1/1/2008',
104002     initDateFormat: 'j/n/Y',
104003
104004
104005     initComponent: function() {
104006         var me = this,
104007             min = me.minValue,
104008             max = me.maxValue;
104009         if (min) {
104010             me.setMinValue(min);
104011         }
104012         if (max) {
104013             me.setMaxValue(max);
104014         }
104015         this.callParent();
104016     },
104017
104018     initValue: function() {
104019         var me = this,
104020             value = me.value;
104021
104022         // If a String value was supplied, try to convert it to a proper Date object
104023         if (Ext.isString(value)) {
104024             me.value = me.rawToValue(value);
104025         }
104026
104027         me.callParent();
104028     },
104029
104030     /**
104031      * Replaces any existing {@link #minValue} with the new time and refreshes the picker's range.
104032      * @param {Date/String} value The minimum time that can be selected
104033      */
104034     setMinValue: function(value) {
104035         var me = this,
104036             picker = me.picker;
104037         me.setLimit(value, true);
104038         if (picker) {
104039             picker.setMinValue(me.minValue);
104040         }
104041     },
104042
104043     /**
104044      * Replaces any existing {@link #maxValue} with the new time and refreshes the picker's range.
104045      * @param {Date/String} value The maximum time that can be selected
104046      */
104047     setMaxValue: function(value) {
104048         var me = this,
104049             picker = me.picker;
104050         me.setLimit(value, false);
104051         if (picker) {
104052             picker.setMaxValue(me.maxValue);
104053         }
104054     },
104055
104056     /**
104057      * @private
104058      * Updates either the min or max value. Converts the user's value into a Date object whose
104059      * year/month/day is set to the {@link #initDate} so that only the time fields are significant.
104060      */
104061     setLimit: function(value, isMin) {
104062         var me = this,
104063             d, val;
104064         if (Ext.isString(value)) {
104065             d = me.parseDate(value);
104066         }
104067         else if (Ext.isDate(value)) {
104068             d = value;
104069         }
104070         if (d) {
104071             val = Ext.Date.clearTime(new Date(me.initDate));
104072             val.setHours(d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
104073             me[isMin ? 'minValue' : 'maxValue'] = val;
104074         }
104075     },
104076
104077     rawToValue: function(rawValue) {
104078         return this.parseDate(rawValue) || rawValue || null;
104079     },
104080
104081     valueToRaw: function(value) {
104082         return this.formatDate(this.parseDate(value));
104083     },
104084
104085     /**
104086      * Runs all of Time's validations and returns an array of any errors. Note that this first
104087      * runs Text's validations, so the returned array is an amalgamation of all field errors.
104088      * The additional validation checks are testing that the time format is valid, that the chosen
104089      * time is within the {@link #minValue} and {@link #maxValue} constraints set.
104090      * @param {Mixed} value The value to get errors for (defaults to the current field value)
104091      * @return {Array} All validation errors for this field
104092      */
104093     getErrors: function(value) {
104094         var me = this,
104095             format = Ext.String.format,
104096             errors = me.callParent(arguments),
104097             minValue = me.minValue,
104098             maxValue = me.maxValue,
104099             date;
104100
104101         value = me.formatDate(value || me.processRawValue(me.getRawValue()));
104102
104103         if (value === null || value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
104104              return errors;
104105         }
104106
104107         date = me.parseDate(value);
104108         if (!date) {
104109             errors.push(format(me.invalidText, value, me.format));
104110             return errors;
104111         }
104112
104113         if (minValue && date < minValue) {
104114             errors.push(format(me.minText, me.formatDate(minValue)));
104115         }
104116
104117         if (maxValue && date > maxValue) {
104118             errors.push(format(me.maxText, me.formatDate(maxValue)));
104119         }
104120
104121         return errors;
104122     },
104123
104124     formatDate: function() {
104125         return Ext.form.field.Date.prototype.formatDate.apply(this, arguments);
104126     },
104127
104128     /**
104129      * @private
104130      * Parses an input value into a valid Date object.
104131      * @param {String/Date} value
104132      */
104133     parseDate: function(value) {
104134         if (!value || Ext.isDate(value)) {
104135             return value;
104136         }
104137
104138         var me = this,
104139             val = me.safeParse(value, me.format),
104140             altFormats = me.altFormats,
104141             altFormatsArray = me.altFormatsArray,
104142             i = 0,
104143             len;
104144
104145         if (!val && altFormats) {
104146             altFormatsArray = altFormatsArray || altFormats.split('|');
104147             len = altFormatsArray.length;
104148             for (; i < len && !val; ++i) {
104149                 val = me.safeParse(value, altFormatsArray[i]);
104150             }
104151         }
104152         return val;
104153     },
104154
104155     safeParse: function(value, format){
104156         var me = this,
104157             utilDate = Ext.Date,
104158             parsedDate,
104159             result = null;
104160
104161         if (utilDate.formatContainsDateInfo(format)) {
104162             // assume we've been given a full date
104163             result = utilDate.parse(value, format);
104164         } else {
104165             // Use our initial safe date
104166             parsedDate = utilDate.parse(me.initDate + ' ' + value, me.initDateFormat + ' ' + format);
104167             if (parsedDate) {
104168                 result = parsedDate;
104169             }
104170         }
104171         return result;
104172     },
104173
104174     // @private
104175     getSubmitValue: function() {
104176         var me = this,
104177             format = me.submitFormat || me.format,
104178             value = me.getValue();
104179
104180         return value ? Ext.Date.format(value, format) : null;
104181     },
104182
104183     /**
104184      * @private
104185      * Creates the {@link Ext.picker.Time}
104186      */
104187     createPicker: function() {
104188         var me = this,
104189             picker = Ext.create('Ext.picker.Time', {
104190                 selModel: {
104191                     mode: 'SINGLE'
104192                 },
104193                 floating: true,
104194                 hidden: true,
104195                 minValue: me.minValue,
104196                 maxValue: me.maxValue,
104197                 increment: me.increment,
104198                 format: me.format,
104199                 ownerCt: this.ownerCt,
104200                 renderTo: document.body,
104201                 maxHeight: me.pickerMaxHeight,
104202                 focusOnToFront: false
104203             });
104204
104205         me.mon(picker.getSelectionModel(), {
104206             selectionchange: me.onListSelect,
104207             scope: me
104208         });
104209
104210         return picker;
104211     },
104212
104213     /**
104214      * @private
104215      * Enables the key nav for the Time picker when it is expanded.
104216      * TODO this is largely the same logic as ComboBox, should factor out.
104217      */
104218     onExpand: function() {
104219         var me = this,
104220             keyNav = me.pickerKeyNav,
104221             selectOnTab = me.selectOnTab,
104222             picker = me.getPicker(),
104223             lastSelected = picker.getSelectionModel().lastSelected,
104224             itemNode;
104225
104226         if (!keyNav) {
104227             keyNav = me.pickerKeyNav = Ext.create('Ext.view.BoundListKeyNav', this.inputEl, {
104228                 boundList: picker,
104229                 forceKeyDown: true,
104230                 tab: function(e) {
104231                     if (selectOnTab) {
104232                         this.selectHighlighted(e);
104233                         me.triggerBlur();
104234                     }
104235                     // Tab key event is allowed to propagate to field
104236                     return true;
104237                 }
104238             });
104239             // stop tab monitoring from Ext.form.field.Trigger so it doesn't short-circuit selectOnTab
104240             if (selectOnTab) {
104241                 me.ignoreMonitorTab = true;
104242             }
104243         }
104244         Ext.defer(keyNav.enable, 1, keyNav); //wait a bit so it doesn't react to the down arrow opening the picker
104245
104246         // Highlight the last selected item and scroll it into view
104247         if (lastSelected) {
104248             itemNode = picker.getNode(lastSelected);
104249             if (itemNode) {
104250                 picker.highlightItem(itemNode);
104251                 picker.el.scrollChildIntoView(itemNode, false);
104252             }
104253         }
104254     },
104255
104256     /**
104257      * @private
104258      * Disables the key nav for the Time picker when it is collapsed.
104259      */
104260     onCollapse: function() {
104261         var me = this,
104262             keyNav = me.pickerKeyNav;
104263         if (keyNav) {
104264             keyNav.disable();
104265             me.ignoreMonitorTab = false;
104266         }
104267     },
104268
104269     /**
104270      * @private
104271      * Handles a time being selected from the Time picker.
104272      */
104273     onListSelect: function(list, recordArray) {
104274         var me = this,
104275             record = recordArray[0],
104276             val = record ? record.get('date') : null;
104277         me.setValue(val);
104278         me.fireEvent('select', me, val);
104279         me.picker.clearHighlight();
104280         me.collapse();
104281         me.inputEl.focus();
104282     }
104283 });
104284
104285
104286 /**
104287  * @class Ext.grid.CellEditor
104288  * @extends Ext.Editor
104289  * Internal utility class that provides default configuration for cell editing.
104290  * @ignore
104291  */
104292 Ext.define('Ext.grid.CellEditor', {
104293     extend: 'Ext.Editor',
104294     constructor: function(config) {
104295         if (config.field) {
104296             config.field.monitorTab = false;
104297         }
104298         config.autoSize = {
104299             width: 'boundEl'
104300         };
104301         this.callParent(arguments);
104302     },
104303     
104304     /**
104305      * @private
104306      * Hide the grid cell when editor is shown.
104307      */
104308     onShow: function() {
104309         var first = this.boundEl.first();
104310         if (first) {
104311             first.hide();
104312         }
104313         this.callParent(arguments);
104314     },
104315     
104316     /**
104317      * @private
104318      * Show grid cell when editor is hidden.
104319      */
104320     onHide: function() {
104321         var first = this.boundEl.first();
104322         if (first) {
104323             first.show();
104324         }
104325         this.callParent(arguments);
104326     },
104327     
104328     /**
104329      * @private
104330      * Fix checkbox blur when it is clicked.
104331      */
104332     afterRender: function() {
104333         this.callParent(arguments);
104334         var field = this.field;
104335         if (field.isXType('checkboxfield')) {
104336             field.mon(field.inputEl, 'mousedown', this.onCheckBoxMouseDown, this);
104337             field.mon(field.inputEl, 'click', this.onCheckBoxClick, this);
104338         }
104339     },
104340     
104341     /**
104342      * @private
104343      * Because when checkbox is clicked it loses focus  completeEdit is bypassed.
104344      */
104345     onCheckBoxMouseDown: function() {
104346         this.completeEdit = Ext.emptyFn;
104347     },
104348     
104349     /**
104350      * @private
104351      * Restore checkbox focus and completeEdit method.
104352      */
104353     onCheckBoxClick: function() {
104354         delete this.completeEdit;
104355         this.field.focus(false, 10);
104356     },
104357     
104358     alignment: "tl-tl",
104359     hideEl : false,
104360     cls: Ext.baseCSSPrefix + "small-editor " + Ext.baseCSSPrefix + "grid-editor",
104361     shim: false,
104362     shadow: false
104363 });
104364 /**
104365  * @class Ext.grid.ColumnLayout
104366  * @extends Ext.layout.container.HBox
104367  * @private
104368  *
104369  * <p>This class is used only by the grid's HeaderContainer docked child.</p>
104370  *
104371  * <p>This class adds the ability to shrink the vertical size of the inner container element back if a grouped
104372  * column header has all its child columns dragged out, and the whole HeaderContainer needs to shrink back down.</p>
104373  *
104374  * <p>It also enforces the grid's HeaderContainer's forceFit config by, after every calaculateChildBoxes call, converting
104375  * all pixel widths into flex values, so that propertions are maintained upon width change of the grid.</p>
104376  *
104377  * <p>Also, after every layout, after all headers have attained their 'stretchmax' height, it goes through and calls
104378  * <code>setPadding</code> on the columns so that they lay out correctly. TODO: implement a ColumnHeader component
104379  * layout which takes responsibility for this, and will run upon resize.</p>
104380  */
104381 Ext.define('Ext.grid.ColumnLayout', {
104382     extend: 'Ext.layout.container.HBox',
104383     alias: 'layout.gridcolumn',
104384     type : 'column',
104385
104386     // Height-stretched innerCt must be able to revert back to unstretched height
104387     clearInnerCtOnLayout: false,
104388
104389     constructor: function() {
104390         var me = this;
104391         me.callParent(arguments);
104392         if (!Ext.isDefined(me.availableSpaceOffset)) {
104393             me.availableSpaceOffset = (Ext.getScrollBarWidth() - 2);
104394         }
104395     },
104396
104397     beforeLayout: function() {
104398         var me = this,
104399             i = 0,
104400             items = me.getLayoutItems(),
104401             len = items.length,
104402             item, returnValue;
104403
104404         returnValue = me.callParent(arguments);
104405
104406         // Size to a sane minimum height before possibly being stretched to accommodate grouped headers
104407         me.innerCt.setHeight(23);
104408
104409         // Unstretch child items before the layout which stretches them.
104410         if (me.align == 'stretchmax') {
104411             for (; i < len; i++) {
104412                 item = items[i];
104413                 item.el.setStyle({
104414                     height: 'auto'
104415                 });
104416                 item.titleContainer.setStyle({
104417                     height: 'auto',
104418                     paddingTop: '0'
104419                 });
104420                 if (item.componentLayout && item.componentLayout.lastComponentSize) {
104421                     item.componentLayout.lastComponentSize.height = item.el.dom.offsetHeight;
104422                 }
104423             }
104424         }
104425         return returnValue;
104426     },
104427
104428     // Override to enforce the forceFit config.
104429     calculateChildBoxes: function(visibleItems, targetSize) {
104430         var me = this,
104431             calculations = me.callParent(arguments),
104432             boxes = calculations.boxes,
104433             metaData = calculations.meta,
104434             len = boxes.length, i = 0, box, item;
104435
104436         if (targetSize.width && !me.isColumn) {
104437             // If configured forceFit then all columns will be flexed
104438             if (me.owner.forceFit) {
104439
104440                 for (; i < len; i++) {
104441                     box = boxes[i];
104442                     item = box.component;
104443
104444                     // Set a sane minWidth for the Box layout to be able to squeeze flexed Headers down to.
104445                     item.minWidth = Ext.grid.plugin.HeaderResizer.prototype.minColWidth;
104446
104447                     // For forceFit, just use allocated width as the flex value, and the proportions
104448                     // will end up the same whatever HeaderContainer width they are being forced into.
104449                     item.flex = box.width;
104450                 }
104451
104452                 // Recalculate based upon all columns now being flexed instead of sized.
104453                 calculations = me.callParent(arguments);
104454             }
104455             else if (metaData.tooNarrow) {
104456                 targetSize.width = metaData.desiredSize;
104457             }
104458         }
104459
104460         return calculations;
104461     },
104462
104463     afterLayout: function() {
104464         var me = this,
104465             i = 0,
104466             items = me.getLayoutItems(),
104467             len = items.length;
104468
104469         me.callParent(arguments);
104470
104471         // Set up padding in items
104472         if (me.align == 'stretchmax') {
104473             for (; i < len; i++) {
104474                 items[i].setPadding();
104475             }
104476         }
104477     },
104478
104479     // FIX: when flexing we actually don't have enough space as we would
104480     // typically because of the scrollOffset on the GridView, must reserve this
104481     updateInnerCtSize: function(tSize, calcs) {
104482         var me    = this,
104483             extra = 0;
104484
104485         // Columns must not account for scroll offset
104486         if (!me.isColumn && calcs.meta.tooNarrow) {
104487             if (
104488                 Ext.isWebKit ||
104489                 Ext.isGecko ||
104490                 (Ext.isIEQuirks && (Ext.isIE6 || Ext.isIE7 || Ext.isIE8))
104491             ) {
104492                 extra = 1;
104493             // IE6-8 not quirks
104494             } else if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
104495                 extra = 2;
104496             }
104497             
104498             // this is the 1px accounted for in the Scroller when subtracting 1px.
104499             extra++;
104500             tSize.width = calcs.meta.desiredSize + (me.reserveOffset ? me.availableSpaceOffset : 0) + extra;
104501         }
104502         return me.callParent(arguments);
104503     },
104504
104505     doOwnerCtLayouts: function() {
104506         var ownerCt = this.owner.ownerCt;
104507         if (!ownerCt.componentLayout.layoutBusy) {
104508             ownerCt.doComponentLayout();
104509         }
104510     }
104511 });
104512 /**
104513  * @class Ext.grid.LockingView
104514  * This class is used internally to provide a single interface when using
104515  * a locking grid. Internally, the locking grid creates 2 separate grids,
104516  * so this class is used to map calls appropriately.
104517  * @ignore
104518  */
104519 Ext.define('Ext.grid.LockingView', {
104520     
104521     mixins: {
104522         observable: 'Ext.util.Observable'
104523     },
104524     
104525     eventRelayRe: /^(beforeitem|beforecontainer|item|container|cell)/,
104526     
104527     constructor: function(config){
104528         var me = this,
104529             eventNames = [],
104530             eventRe = me.eventRelayRe,
104531             locked = config.locked.getView(),
104532             normal = config.normal.getView(),
104533             events,
104534             event;
104535         
104536         Ext.apply(me, {
104537             lockedView: locked,
104538             normalView: normal,
104539             lockedGrid: config.locked,
104540             normalGrid: config.normal,
104541             panel: config.panel
104542         });
104543         me.mixins.observable.constructor.call(me, config);
104544         
104545         // relay events
104546         events = locked.events;
104547         for (event in events) {
104548             if (events.hasOwnProperty(event) && eventRe.test(event)) {
104549                 eventNames.push(event);
104550             }
104551         }
104552         me.relayEvents(locked, eventNames);
104553         me.relayEvents(normal, eventNames);
104554         
104555         normal.on({
104556             scope: me,
104557             itemmouseleave: me.onItemMouseLeave,
104558             itemmouseenter: me.onItemMouseEnter
104559         });
104560         
104561         locked.on({
104562             scope: me,
104563             itemmouseleave: me.onItemMouseLeave,
104564             itemmouseenter: me.onItemMouseEnter
104565         });
104566     },
104567     
104568     getGridColumns: function() {
104569         var cols = this.lockedGrid.headerCt.getGridColumns();
104570         return cols.concat(this.normalGrid.headerCt.getGridColumns());
104571     },
104572     
104573     onItemMouseEnter: function(view, record){
104574         var me = this,
104575             locked = me.lockedView,
104576             other = me.normalView,
104577             item;
104578             
104579         if (view.trackOver) {
104580             if (view !== locked) {
104581                 other = locked;
104582             }
104583             item = other.getNode(record);
104584             other.highlightItem(item);
104585         }
104586     },
104587     
104588     onItemMouseLeave: function(view, record){
104589         var me = this,
104590             locked = me.lockedView,
104591             other = me.normalView;
104592             
104593         if (view.trackOver) {
104594             if (view !== locked) {
104595                 other = locked;
104596             }
104597             other.clearHighlight();
104598         }
104599     },
104600     
104601     relayFn: function(name, args){
104602         args = args || [];
104603         
104604         var view = this.lockedView;
104605         view[name].apply(view, args || []);    
104606         view = this.normalView;
104607         view[name].apply(view, args || []);   
104608     },
104609     
104610     getSelectionModel: function(){
104611         return this.panel.getSelectionModel();    
104612     },
104613     
104614     getStore: function(){
104615         return this.panel.store;
104616     },
104617     
104618     getNode: function(nodeInfo){
104619         // default to the normal view
104620         return this.normalView.getNode(nodeInfo);
104621     },
104622     
104623     getCell: function(record, column){
104624         var view = this.lockedView,
104625             row;
104626         
104627         
104628         if (view.getHeaderAtIndex(column) === -1) {
104629             view = this.normalView;
104630         }
104631         
104632         row = view.getNode(record);
104633         return Ext.fly(row).down(column.getCellSelector());
104634     },
104635     
104636     getRecord: function(node){
104637         var result = this.lockedView.getRecord(node);
104638         if (!node) {
104639             result = this.normalView.getRecord(node);
104640         }
104641         return result;
104642     },
104643     
104644     refreshNode: function(){
104645         this.relayFn('refreshNode', arguments);
104646     },
104647     
104648     refresh: function(){
104649         this.relayFn('refresh', arguments);
104650     },
104651     
104652     bindStore: function(){
104653         this.relayFn('bindStore', arguments);
104654     },
104655     
104656     addRowCls: function(){
104657         this.relayFn('addRowCls', arguments);
104658     },
104659     
104660     removeRowCls: function(){
104661         this.relayFn('removeRowCls', arguments);
104662     }
104663        
104664 });
104665 /**
104666  * @class Ext.grid.Lockable
104667  * @private
104668  *
104669  * Lockable is a private mixin which injects lockable behavior into any
104670  * TablePanel subclass such as GridPanel or TreePanel. TablePanel will
104671  * automatically inject the Ext.grid.Lockable mixin in when one of the
104672  * these conditions are met:
104673  * - The TablePanel has the lockable configuration set to true
104674  * - One of the columns in the TablePanel has locked set to true/false
104675  *
104676  * Each TablePanel subclass *must* register an alias. It should have an array
104677  * of configurations to copy to the 2 separate tablepanel's that will be generated
104678  * to note what configurations should be copied. These are named normalCfgCopy and
104679  * lockedCfgCopy respectively.
104680  *
104681  * Columns which are locked must specify a fixed width. They do *NOT* support a
104682  * flex width.
104683  *
104684  * Configurations which are specified in this class will be available on any grid or
104685  * tree which is using the lockable functionality.
104686  */
104687 Ext.define('Ext.grid.Lockable', {
104688     
104689     requires: ['Ext.grid.LockingView'],
104690     
104691     /**
104692      * @cfg {Boolean} syncRowHeight Synchronize rowHeight between the normal and
104693      * locked grid view. This is turned on by default. If your grid is guaranteed
104694      * to have rows of all the same height, you should set this to false to
104695      * optimize performance.
104696      */
104697     syncRowHeight: true,
104698     
104699     /**
104700      * @cfg {String} subGridXType The xtype of the subgrid to specify. If this is
104701      * not specified lockable will determine the subgrid xtype to create by the
104702      * following rule. Use the superclasses xtype if the superclass is NOT
104703      * tablepanel, otherwise use the xtype itself.
104704      */
104705     
104706     /**
104707      * @cfg {Object} lockedViewConfig A view configuration to be applied to the
104708      * locked side of the grid. Any conflicting configurations between lockedViewConfig
104709      * and viewConfig will be overwritten by the lockedViewConfig.
104710      */
104711
104712     /**
104713      * @cfg {Object} normalViewConfig A view configuration to be applied to the
104714      * normal/unlocked side of the grid. Any conflicting configurations between normalViewConfig
104715      * and viewConfig will be overwritten by the normalViewConfig.
104716      */
104717     
104718     // private variable to track whether or not the spacer is hidden/visible
104719     spacerHidden: true,
104720     
104721     // i8n text
104722     unlockText: 'Unlock',
104723     lockText: 'Lock',
104724     
104725     determineXTypeToCreate: function() {
104726         var me = this,
104727             typeToCreate;
104728
104729         if (me.subGridXType) {
104730             typeToCreate = me.subGridXType;
104731         } else {
104732             var xtypes     = this.getXTypes().split('/'),
104733                 xtypesLn   = xtypes.length,
104734                 xtype      = xtypes[xtypesLn - 1],
104735                 superxtype = xtypes[xtypesLn - 2];
104736                 
104737             if (superxtype !== 'tablepanel') {
104738                 typeToCreate = superxtype;
104739             } else {
104740                 typeToCreate = xtype;
104741             }
104742         }
104743         
104744         return typeToCreate;
104745     },
104746     
104747     // injectLockable will be invoked before initComponent's parent class implementation
104748     // is called, so throughout this method this. are configurations
104749     injectLockable: function() {
104750         // ensure lockable is set to true in the TablePanel
104751         this.lockable = true;
104752         // Instruct the TablePanel it already has a view and not to create one.
104753         // We are going to aggregate 2 copies of whatever TablePanel we are using
104754         this.hasView = true;
104755
104756         var me = this,
104757             // xtype of this class, 'treepanel' or 'gridpanel'
104758             // (Note: this makes it a requirement that any subclass that wants to use lockable functionality needs to register an
104759             // alias.)
104760             xtype = me.determineXTypeToCreate(),
104761             // share the selection model
104762             selModel = me.getSelectionModel(),
104763             lockedGrid = {
104764                 xtype: xtype,
104765                 // Lockable does NOT support animations for Tree
104766                 enableAnimations: false,
104767                 scroll: false,
104768                 scrollerOwner: false,
104769                 selModel: selModel,
104770                 border: false,
104771                 cls: Ext.baseCSSPrefix + 'grid-inner-locked'
104772             },
104773             normalGrid = {
104774                 xtype: xtype,
104775                 enableAnimations: false,
104776                 scrollerOwner: false,
104777                 selModel: selModel,
104778                 border: false
104779             },
104780             i = 0,
104781             columns,
104782             lockedHeaderCt,
104783             normalHeaderCt;
104784         
104785         me.addCls(Ext.baseCSSPrefix + 'grid-locked');
104786         
104787         // copy appropriate configurations to the respective
104788         // aggregated tablepanel instances and then delete them
104789         // from the master tablepanel.
104790         Ext.copyTo(normalGrid, me, me.normalCfgCopy);
104791         Ext.copyTo(lockedGrid, me, me.lockedCfgCopy);
104792         for (; i < me.normalCfgCopy.length; i++) {
104793             delete me[me.normalCfgCopy[i]];
104794         }
104795         for (i = 0; i < me.lockedCfgCopy.length; i++) {
104796             delete me[me.lockedCfgCopy[i]];
104797         }
104798         
104799         me.lockedHeights = [];
104800         me.normalHeights = [];
104801         
104802         columns = me.processColumns(me.columns);
104803
104804         lockedGrid.width = columns.lockedWidth;
104805         lockedGrid.columns = columns.locked;
104806         normalGrid.columns = columns.normal;
104807         
104808         me.store = Ext.StoreManager.lookup(me.store);
104809         lockedGrid.store = me.store;
104810         normalGrid.store = me.store;
104811         
104812         // normal grid should flex the rest of the width
104813         normalGrid.flex = 1;
104814         lockedGrid.viewConfig = me.lockedViewConfig || {};
104815         lockedGrid.viewConfig.loadingUseMsg = false;
104816         normalGrid.viewConfig = me.normalViewConfig || {};
104817         
104818         Ext.applyIf(lockedGrid.viewConfig, me.viewConfig);
104819         Ext.applyIf(normalGrid.viewConfig, me.viewConfig);
104820         
104821         me.normalGrid = Ext.ComponentManager.create(normalGrid);
104822         me.lockedGrid = Ext.ComponentManager.create(lockedGrid);
104823         
104824         me.view = Ext.create('Ext.grid.LockingView', {
104825             locked: me.lockedGrid,
104826             normal: me.normalGrid,
104827             panel: me    
104828         });
104829         
104830         if (me.syncRowHeight) {
104831             me.lockedGrid.getView().on({
104832                 refresh: me.onLockedGridAfterRefresh,
104833                 itemupdate: me.onLockedGridAfterUpdate,
104834                 scope: me
104835             });
104836             
104837             me.normalGrid.getView().on({
104838                 refresh: me.onNormalGridAfterRefresh,
104839                 itemupdate: me.onNormalGridAfterUpdate,
104840                 scope: me
104841             });
104842         }
104843         
104844         lockedHeaderCt = me.lockedGrid.headerCt;
104845         normalHeaderCt = me.normalGrid.headerCt;
104846         
104847         lockedHeaderCt.lockedCt = true;
104848         lockedHeaderCt.lockableInjected = true;
104849         normalHeaderCt.lockableInjected = true;
104850         
104851         lockedHeaderCt.on({
104852             columnshow: me.onLockedHeaderShow,
104853             columnhide: me.onLockedHeaderHide,
104854             columnmove: me.onLockedHeaderMove,
104855             sortchange: me.onLockedHeaderSortChange,
104856             columnresize: me.onLockedHeaderResize,
104857             scope: me
104858         });
104859         
104860         normalHeaderCt.on({
104861             columnmove: me.onNormalHeaderMove,
104862             sortchange: me.onNormalHeaderSortChange,
104863             scope: me
104864         });
104865         
104866         me.normalGrid.on({
104867             scrollershow: me.onScrollerShow,
104868             scrollerhide: me.onScrollerHide,
104869             scope: me
104870         });
104871         
104872         me.lockedGrid.on('afterlayout', me.onLockedGridAfterLayout, me, {single: true});
104873         
104874         me.modifyHeaderCt();
104875         me.items = [me.lockedGrid, me.normalGrid];
104876
104877         me.layout = {
104878             type: 'hbox',
104879             align: 'stretch'
104880         };
104881     },
104882     
104883     processColumns: function(columns){
104884         // split apart normal and lockedWidths
104885         var i = 0,
104886             len = columns.length,
104887             lockedWidth = 0,
104888             lockedHeaders = [],
104889             normalHeaders = [],
104890             column;
104891             
104892         for (; i < len; ++i) {
104893             column = columns[i];
104894             // mark the column as processed so that the locked attribute does not
104895             // trigger trying to aggregate the columns again.
104896             column.processed = true;
104897             if (column.locked) {
104898                 if (column.flex) {
104899                     Ext.Error.raise("Columns which are locked do NOT support a flex width. You must set a width on the " + columns[i].text + "column.");
104900                 }
104901                 lockedWidth += column.width;
104902                 lockedHeaders.push(column);
104903             } else {
104904                 normalHeaders.push(column);
104905             }
104906         }
104907         return {
104908             lockedWidth: lockedWidth,
104909             locked: lockedHeaders,
104910             normal: normalHeaders    
104911         };
104912     },
104913     
104914     // create a new spacer after the table is refreshed
104915     onLockedGridAfterLayout: function() {
104916         var me         = this,
104917             lockedView = me.lockedGrid.getView();
104918         lockedView.on({
104919             refresh: me.createSpacer,
104920             beforerefresh: me.destroySpacer,
104921             scope: me
104922         });
104923     },
104924     
104925     // trigger a pseudo refresh on the normal side
104926     onLockedHeaderMove: function() {
104927         if (this.syncRowHeight) {
104928             this.onNormalGridAfterRefresh();
104929         }
104930     },
104931     
104932     // trigger a pseudo refresh on the locked side
104933     onNormalHeaderMove: function() {
104934         if (this.syncRowHeight) {
104935             this.onLockedGridAfterRefresh();
104936         }
104937     },
104938     
104939     // create a spacer in lockedsection and store a reference
104940     // TODO: Should destroy before refreshing content
104941     createSpacer: function() {
104942         var me   = this,
104943             // This affects scrolling all the way to the bottom of a locked grid
104944             // additional test, sort a column and make sure it synchronizes
104945             w    = Ext.getScrollBarWidth() + (Ext.isIE ? 2 : 0),
104946             view = me.lockedGrid.getView(),
104947             el   = view.el;
104948
104949         me.spacerEl = Ext.core.DomHelper.append(el, {
104950             cls: me.spacerHidden ? (Ext.baseCSSPrefix + 'hidden') : '',
104951             style: 'height: ' + w + 'px;'
104952         }, true);
104953     },
104954     
104955     destroySpacer: function() {
104956         var me = this;
104957         if (me.spacerEl) {
104958             me.spacerEl.destroy();
104959             delete me.spacerEl;
104960         }
104961     },
104962     
104963     // cache the heights of all locked rows and sync rowheights
104964     onLockedGridAfterRefresh: function() {
104965         var me     = this,
104966             view   = me.lockedGrid.getView(),
104967             el     = view.el,
104968             rowEls = el.query(view.getItemSelector()),
104969             ln     = rowEls.length,
104970             i = 0;
104971             
104972         // reset heights each time.
104973         me.lockedHeights = [];
104974         
104975         for (; i < ln; i++) {
104976             me.lockedHeights[i] = rowEls[i].clientHeight;
104977         }
104978         me.syncRowHeights();
104979     },
104980     
104981     // cache the heights of all normal rows and sync rowheights
104982     onNormalGridAfterRefresh: function() {
104983         var me     = this,
104984             view   = me.normalGrid.getView(),
104985             el     = view.el,
104986             rowEls = el.query(view.getItemSelector()),
104987             ln     = rowEls.length,
104988             i = 0;
104989             
104990         // reset heights each time.
104991         me.normalHeights = [];
104992         
104993         for (; i < ln; i++) {
104994             me.normalHeights[i] = rowEls[i].clientHeight;
104995         }
104996         me.syncRowHeights();
104997     },
104998     
104999     // rows can get bigger/smaller
105000     onLockedGridAfterUpdate: function(record, index, node) {
105001         this.lockedHeights[index] = node.clientHeight;
105002         this.syncRowHeights();
105003     },
105004     
105005     // rows can get bigger/smaller
105006     onNormalGridAfterUpdate: function(record, index, node) {
105007         this.normalHeights[index] = node.clientHeight;
105008         this.syncRowHeights();
105009     },
105010     
105011     // match the rowheights to the biggest rowheight on either
105012     // side
105013     syncRowHeights: function() {
105014         var me = this,
105015             lockedHeights = me.lockedHeights,
105016             normalHeights = me.normalHeights,
105017             calcHeights   = [],
105018             ln = lockedHeights.length,
105019             i  = 0,
105020             lockedView, normalView,
105021             lockedRowEls, normalRowEls,
105022             vertScroller = me.getVerticalScroller(),
105023             scrollTop;
105024
105025         // ensure there are an equal num of locked and normal
105026         // rows before synchronization
105027         if (lockedHeights.length && normalHeights.length) {
105028             lockedView = me.lockedGrid.getView();
105029             normalView = me.normalGrid.getView();
105030             lockedRowEls = lockedView.el.query(lockedView.getItemSelector());
105031             normalRowEls = normalView.el.query(normalView.getItemSelector());
105032
105033             // loop thru all of the heights and sync to the other side
105034             for (; i < ln; i++) {
105035                 // ensure both are numbers
105036                 if (!isNaN(lockedHeights[i]) && !isNaN(normalHeights[i])) {
105037                     if (lockedHeights[i] > normalHeights[i]) {
105038                         Ext.fly(normalRowEls[i]).setHeight(lockedHeights[i]);
105039                     } else if (lockedHeights[i] < normalHeights[i]) {
105040                         Ext.fly(lockedRowEls[i]).setHeight(normalHeights[i]);
105041                     }
105042                 }
105043             }
105044
105045             // invalidate the scroller and sync the scrollers
105046             me.normalGrid.invalidateScroller();
105047             
105048             // synchronize the view with the scroller, if we have a virtualScrollTop
105049             // then the user is using a PagingScroller 
105050             if (vertScroller && vertScroller.setViewScrollTop) {
105051                 vertScroller.setViewScrollTop(me.virtualScrollTop);
105052             } else {
105053                 // We don't use setScrollTop here because if the scrollTop is
105054                 // set to the exact same value some browsers won't fire the scroll
105055                 // event. Instead, we directly set the scrollTop.
105056                 scrollTop = normalView.el.dom.scrollTop;
105057                 normalView.el.dom.scrollTop = scrollTop;
105058                 lockedView.el.dom.scrollTop = scrollTop;
105059             }
105060             
105061             // reset the heights
105062             me.lockedHeights = [];
105063             me.normalHeights = [];
105064         }
105065     },
105066     
105067     // track when scroller is shown
105068     onScrollerShow: function(scroller, direction) {
105069         if (direction === 'horizontal') {
105070             this.spacerHidden = false;
105071             this.spacerEl.removeCls(Ext.baseCSSPrefix + 'hidden');
105072         }
105073     },
105074     
105075     // track when scroller is hidden
105076     onScrollerHide: function(scroller, direction) {
105077         if (direction === 'horizontal') {
105078             this.spacerHidden = true;
105079             this.spacerEl.addCls(Ext.baseCSSPrefix + 'hidden');
105080         }
105081     },
105082
105083     
105084     // inject Lock and Unlock text
105085     modifyHeaderCt: function() {
105086         var me = this;
105087         me.lockedGrid.headerCt.getMenuItems = me.getMenuItems(true);
105088         me.normalGrid.headerCt.getMenuItems = me.getMenuItems(false);
105089     },
105090     
105091     onUnlockMenuClick: function() {
105092         this.unlock();
105093     },
105094     
105095     onLockMenuClick: function() {
105096         this.lock();
105097     },
105098     
105099     getMenuItems: function(locked) {
105100         var me            = this,
105101             unlockText    = me.unlockText,
105102             lockText      = me.lockText,
105103             // TODO: Refactor to use Ext.baseCSSPrefix
105104             unlockCls     = 'xg-hmenu-unlock',
105105             lockCls       = 'xg-hmenu-lock',
105106             unlockHandler = Ext.Function.bind(me.onUnlockMenuClick, me),
105107             lockHandler   = Ext.Function.bind(me.onLockMenuClick, me);
105108         
105109         // runs in the scope of headerCt
105110         return function() {
105111             var o = Ext.grid.header.Container.prototype.getMenuItems.call(this);
105112             o.push('-',{
105113                 cls: unlockCls,
105114                 text: unlockText,
105115                 handler: unlockHandler,
105116                 disabled: !locked
105117             });
105118             o.push({
105119                 cls: lockCls,
105120                 text: lockText,
105121                 handler: lockHandler,
105122                 disabled: locked
105123             });
105124             return o;
105125         };
105126     },
105127     
105128     // going from unlocked section to locked
105129     /**
105130      * Locks the activeHeader as determined by which menu is open OR a header
105131      * as specified.
105132      * @param {Ext.grid.column.Column} header (Optional) Header to unlock from the locked section. Defaults to the header which has the menu open currently.
105133      * @param {Number} toIdx (Optional) The index to move the unlocked header to. Defaults to appending as the last item.
105134      * @private
105135      */
105136     lock: function(activeHd, toIdx) {
105137         var me         = this,
105138             normalGrid = me.normalGrid,
105139             lockedGrid = me.lockedGrid,
105140             normalHCt  = normalGrid.headerCt,
105141             lockedHCt  = lockedGrid.headerCt;
105142             
105143         activeHd = activeHd || normalHCt.getMenu().activeHeader;
105144         
105145         // if column was previously flexed, get/set current width
105146         // and remove the flex
105147         if (activeHd.flex) {
105148             activeHd.width = activeHd.getWidth();
105149             delete activeHd.flex;
105150         }
105151         
105152         normalHCt.remove(activeHd, false);
105153         lockedHCt.suspendLayout = true;
105154         if (Ext.isDefined(toIdx)) {
105155             lockedHCt.insert(toIdx, activeHd);
105156         } else {
105157             lockedHCt.add(activeHd);
105158         }
105159         lockedHCt.suspendLayout = false;
105160         me.syncLockedSection();
105161     },
105162     
105163     syncLockedSection: function() {
105164         var me = this;
105165         me.syncLockedWidth();
105166         me.lockedGrid.getView().refresh();
105167         me.normalGrid.getView().refresh();
105168     },
105169     
105170     // adjust the locked section to the width of its respective
105171     // headerCt
105172     syncLockedWidth: function() {
105173         var me = this,
105174             width = me.lockedGrid.headerCt.getFullWidth(true);
105175         me.lockedGrid.setWidth(width);
105176     },
105177     
105178     onLockedHeaderResize: function() {
105179         this.syncLockedWidth();
105180     },
105181     
105182     onLockedHeaderHide: function() {
105183         this.syncLockedWidth();
105184     },
105185     
105186     onLockedHeaderShow: function() {
105187         this.syncLockedWidth();
105188     },
105189     
105190     onLockedHeaderSortChange: function(headerCt, header, sortState) {
105191         if (sortState) {
105192             // no real header, and silence the event so we dont get into an
105193             // infinite loop
105194             this.normalGrid.headerCt.clearOtherSortStates(null, true);
105195         }
105196     },
105197     
105198     onNormalHeaderSortChange: function(headerCt, header, sortState) {
105199         if (sortState) {
105200             // no real header, and silence the event so we dont get into an
105201             // infinite loop
105202             this.lockedGrid.headerCt.clearOtherSortStates(null, true);
105203         }
105204     },
105205     
105206     // going from locked section to unlocked
105207     /**
105208      * Unlocks the activeHeader as determined by which menu is open OR a header
105209      * as specified.
105210      * @param {Ext.grid.column.Column} header (Optional) Header to unlock from the locked section. Defaults to the header which has the menu open currently.
105211      * @param {Number} toIdx (Optional) The index to move the unlocked header to. Defaults to 0.
105212      * @private
105213      */
105214     unlock: function(activeHd, toIdx) {
105215         var me         = this,
105216             normalGrid = me.normalGrid,
105217             lockedGrid = me.lockedGrid,
105218             normalHCt  = normalGrid.headerCt,
105219             lockedHCt  = lockedGrid.headerCt;
105220
105221         if (!Ext.isDefined(toIdx)) {
105222             toIdx = 0;
105223         }
105224         activeHd = activeHd || lockedHCt.getMenu().activeHeader;
105225         
105226         lockedHCt.remove(activeHd, false);
105227         me.syncLockedWidth();
105228         me.lockedGrid.getView().refresh();
105229         normalHCt.insert(toIdx, activeHd);
105230         me.normalGrid.getView().refresh();
105231     },
105232     
105233     // we want to totally override the reconfigure behaviour here, since we're creating 2 sub-grids
105234     reconfigureLockable: function(store, columns) {
105235         var me = this,
105236             lockedGrid = me.lockedGrid,
105237             normalGrid = me.normalGrid;
105238         
105239         if (columns) {
105240             lockedGrid.headerCt.removeAll();
105241             normalGrid.headerCt.removeAll();
105242             
105243             columns = me.processColumns(columns);
105244             lockedGrid.setWidth(columns.lockedWidth);
105245             lockedGrid.headerCt.add(columns.locked);
105246             normalGrid.headerCt.add(columns.normal);
105247         }
105248         
105249         if (store) {
105250             store = Ext.data.StoreManager.lookup(store);
105251             me.store = store;
105252             lockedGrid.bindStore(store);
105253             normalGrid.bindStore(store);
105254         } else {
105255             lockedGrid.getView().refresh();
105256             normalGrid.getView().refresh();
105257         }
105258     }
105259 });
105260
105261 /**
105262  * @class Ext.grid.Scroller
105263  * @extends Ext.Component
105264  *
105265  * Docked in an Ext.grid.Panel, controls virtualized scrolling and synchronization
105266  * across different sections.
105267  *
105268  * @private
105269  */
105270 Ext.define('Ext.grid.Scroller', {
105271     extend: 'Ext.Component',
105272     alias: 'widget.gridscroller',
105273     weight: 110,
105274     cls: Ext.baseCSSPrefix + 'scroller',
105275     focusable: false,
105276     
105277     renderTpl: ['<div class="' + Ext.baseCSSPrefix + 'stretcher"></div>'],
105278     
105279     initComponent: function() {
105280         var me       = this,
105281             dock     = me.dock,
105282             cls      = Ext.baseCSSPrefix + 'scroller-vertical',
105283             sizeProp = 'width',
105284             // Subtracting 2px would give us a perfect fit of the scroller
105285             // however, some browsers wont allow us to scroll content thats not
105286             // visible, therefore we use 1px.
105287             // Note: This 1px offset matches code in Ext.grid.ColumnLayout when
105288             // reserving room for the scrollbar
105289             scrollbarWidth = Ext.getScrollBarWidth() + (Ext.isIE ? 1 : -1);
105290
105291         me.offsets = {bottom: 0};
105292
105293         if (dock === 'top' || dock === 'bottom') {
105294             cls = Ext.baseCSSPrefix + 'scroller-horizontal';
105295             sizeProp = 'height';
105296         }
105297         me[sizeProp] = scrollbarWidth;
105298         
105299         me.cls += (' ' + cls);
105300         
105301         Ext.applyIf(me.renderSelectors, {
105302             stretchEl: '.' + Ext.baseCSSPrefix + 'stretcher'
105303         });
105304         me.callParent();
105305     },
105306     
105307     
105308     afterRender: function() {
105309         var me = this;
105310         me.callParent();
105311         me.ownerCt.on('afterlayout', me.onOwnerAfterLayout, me);
105312         me.mon(me.el, 'scroll', me.onElScroll, me);
105313         Ext.cache[me.el.id].skipGarbageCollection = true;
105314     },
105315     
105316     getSizeCalculation: function() {
105317         var owner  = this.getPanel(),
105318             dock   = this.dock,
105319             elDom  = this.el.dom,
105320             width  = 1,
105321             height = 1,
105322             view, tbl;
105323             
105324         if (dock === 'top' || dock === 'bottom') {
105325             // TODO: Must gravitate to a single region..
105326             // Horizontal scrolling only scrolls virtualized region
105327             var items  = owner.query('tableview'),
105328                 center = items[1] || items[0];
105329             
105330             if (!center) {
105331                 return false;
105332             }
105333             // center is not guaranteed to have content, such as when there
105334             // are zero rows in the grid/tree. We read the width from the
105335             // headerCt instead.
105336             width = center.headerCt.getFullWidth();
105337             
105338             if (Ext.isIEQuirks) {
105339                 width--;
105340             }
105341             // Account for the 1px removed in Scroller.
105342             width--;
105343         } else {            
105344             view = owner.down('tableview:not([lockableInjected])');
105345             if (!view) {
105346                 return false;
105347             }
105348             tbl = view.el;
105349             if (!tbl) {
105350                 return false;
105351             }
105352             
105353             // needs to also account for header and scroller (if still in picture)
105354             // should calculate from headerCt.
105355             height = tbl.dom.scrollHeight;
105356         }
105357         if (isNaN(width)) {
105358             width = 1;
105359         }
105360         if (isNaN(height)) {
105361             height = 1;
105362         }
105363         return {
105364             width: width,
105365             height: height
105366         };
105367     },
105368     
105369     invalidate: function(firstPass) {
105370         if (!this.stretchEl || !this.ownerCt) {
105371             return;
105372         }
105373         var size  = this.getSizeCalculation(),
105374             elDom = this.el.dom;
105375         if (size) {
105376             this.stretchEl.setSize(size);
105377         
105378             // BrowserBug: IE7
105379             // This makes the scroller enabled, when initially rendering.
105380             elDom.scrollTop = elDom.scrollTop;
105381         }
105382     },
105383
105384     onOwnerAfterLayout: function(owner, layout) {
105385         this.invalidate();
105386     },
105387
105388     /**
105389      * Sets the scrollTop and constrains the value between 0 and max.
105390      * @param {Number} scrollTop
105391      * @return {Number} The resulting scrollTop value after being constrained
105392      */
105393     setScrollTop: function(scrollTop) {
105394         if (this.el) {
105395             var elDom = this.el.dom;
105396             return elDom.scrollTop = Ext.Number.constrain(scrollTop, 0, elDom.scrollHeight - elDom.clientHeight);
105397         }
105398     },
105399
105400     /**
105401      * Sets the scrollLeft and constrains the value between 0 and max.
105402      * @param {Number} scrollLeft
105403      * @return {Number} The resulting scrollLeft value after being constrained
105404      */
105405     setScrollLeft: function(scrollLeft) {
105406         if (this.el) {
105407             var elDom = this.el.dom;
105408             return elDom.scrollLeft = Ext.Number.constrain(scrollLeft, 0, elDom.scrollWidth - elDom.clientWidth);
105409         }
105410     },
105411
105412     /**
105413      * Scroll by deltaY
105414      * @param {Number} delta
105415      * @return {Number} The resulting scrollTop value
105416      */
105417     scrollByDeltaY: function(delta) {
105418         if (this.el) {
105419             var elDom = this.el.dom;
105420             return this.setScrollTop(elDom.scrollTop + delta);
105421         }
105422     },
105423
105424     /**
105425      * Scroll by deltaX
105426      * @param {Number} delta
105427      * @return {Number} The resulting scrollLeft value
105428      */
105429     scrollByDeltaX: function(delta) {
105430         if (this.el) {
105431             var elDom = this.el.dom;
105432             return this.setScrollLeft(elDom.scrollLeft + delta);
105433         }
105434     },
105435     
105436     
105437     /**
105438      * Scroll to the top.
105439      */
105440     scrollToTop : function(){
105441         this.setScrollTop(0);
105442     },
105443     
105444     // synchronize the scroller with the bound gridviews
105445     onElScroll: function(event, target) {
105446         this.fireEvent('bodyscroll', event, target);
105447     },
105448
105449     getPanel: function() {
105450         var me = this;
105451         if (!me.panel) {
105452             me.panel = this.up('[scrollerOwner]');
105453         }
105454         return me.panel;
105455     }
105456 });
105457
105458
105459 /**
105460  * @class Ext.grid.PagingScroller
105461  * @extends Ext.grid.Scroller
105462  *
105463  * @private
105464  */
105465 Ext.define('Ext.grid.PagingScroller', {
105466     extend: 'Ext.grid.Scroller',
105467     alias: 'widget.paginggridscroller',
105468     //renderTpl: null,
105469     //tpl: [
105470     //    '<tpl for="pages">',
105471     //        '<div class="' + Ext.baseCSSPrefix + 'stretcher" style="width: {width}px;height: {height}px;"></div>',
105472     //    '</tpl>'
105473     //],
105474     /**
105475      * @cfg {Number} percentageFromEdge This is a number above 0 and less than 1 which specifies
105476      * at what percentage to begin fetching the next page. For example if the pageSize is 100
105477      * and the percentageFromEdge is the default of 0.35, the paging scroller will prefetch pages
105478      * when scrolling up between records 0 and 34 and when scrolling down between records 65 and 99.
105479      */
105480     percentageFromEdge: 0.35,
105481     
105482     /**
105483      * @cfg {Number} scrollToLoadBuffer This is the time in milliseconds to buffer load requests
105484      * when scrolling the PagingScrollbar.
105485      */
105486     scrollToLoadBuffer: 200,
105487     
105488     activePrefetch: true,
105489     
105490     chunkSize: 50,
105491     snapIncrement: 25,
105492     
105493     syncScroll: true,
105494     
105495     initComponent: function() {
105496         var me = this,
105497             ds = me.store;
105498
105499         ds.on('guaranteedrange', this.onGuaranteedRange, this);
105500         this.callParent(arguments);
105501     },
105502     
105503     
105504     onGuaranteedRange: function(range, start, end) {
105505         var me = this,
105506             ds = me.store,
105507             rs;
105508         // this should never happen
105509         if (range.length && me.visibleStart < range[0].index) {
105510             return;
105511         }
105512         
105513         ds.loadRecords(range);
105514
105515         if (!me.firstLoad) {
105516             if (me.rendered) {
105517                 me.invalidate();
105518             } else {
105519                 me.on('afterrender', this.invalidate, this, {single: true});
105520             }
105521             me.firstLoad = true;
105522         } else {
105523             // adjust to visible
105524             me.syncTo();
105525         }
105526     },
105527     
105528     syncTo: function() {
105529         var me            = this,
105530             pnl           = me.getPanel(),
105531             store         = pnl.store,
105532             scrollerElDom = this.el.dom,
105533             rowOffset     = me.visibleStart - store.guaranteedStart,
105534             scrollBy      = rowOffset * me.rowHeight,
105535             scrollHeight  = scrollerElDom.scrollHeight,
105536             clientHeight  = scrollerElDom.clientHeight,
105537             scrollTop     = scrollerElDom.scrollTop,
105538             useMaximum;
105539         
105540         // BrowserBug: clientHeight reports 0 in IE9 StrictMode
105541         // Instead we are using offsetHeight and hardcoding borders
105542         if (Ext.isIE9 && Ext.isStrict) {
105543             clientHeight = scrollerElDom.offsetHeight + 2;
105544         }
105545
105546         // This should always be zero or greater than zero but staying
105547         // safe and less than 0 we'll scroll to the bottom.        
105548         useMaximum = (scrollHeight - clientHeight - scrollTop <= 0);
105549         this.setViewScrollTop(scrollBy, useMaximum);
105550     },
105551     
105552     getPageData : function(){
105553         var panel = this.getPanel(),
105554             store = panel.store,
105555             totalCount = store.getTotalCount();
105556             
105557         return {
105558             total : totalCount,
105559             currentPage : store.currentPage,
105560             pageCount: Math.ceil(totalCount / store.pageSize),
105561             fromRecord: ((store.currentPage - 1) * store.pageSize) + 1,
105562             toRecord: Math.min(store.currentPage * store.pageSize, totalCount)
105563         };
105564     },
105565     
105566     onElScroll: function(e, t) {
105567         var me = this,
105568             panel = me.getPanel(),
105569             store = panel.store,
105570             pageSize = store.pageSize,
105571             guaranteedStart = store.guaranteedStart,
105572             guaranteedEnd = store.guaranteedEnd,
105573             totalCount = store.getTotalCount(),
105574             numFromEdge = Math.ceil(me.percentageFromEdge * store.pageSize),
105575             position = t.scrollTop,
105576             visibleStart = Math.floor(position / me.rowHeight),
105577             view = panel.down('tableview'),
105578             viewEl = view.el,
105579             visibleHeight = viewEl.getHeight(),
105580             visibleAhead = Math.ceil(visibleHeight / me.rowHeight),
105581             visibleEnd = visibleStart + visibleAhead,
105582             prevPage = Math.floor(visibleStart / store.pageSize),
105583             nextPage = Math.floor(visibleEnd / store.pageSize) + 2,
105584             lastPage = Math.ceil(totalCount / store.pageSize),
105585             //requestStart = visibleStart,
105586             requestStart = Math.floor(visibleStart / me.snapIncrement) * me.snapIncrement,
105587             requestEnd = requestStart + pageSize - 1,
105588             activePrefetch = me.activePrefetch;
105589
105590         me.visibleStart = visibleStart;
105591         me.visibleEnd = visibleEnd;
105592         
105593         
105594         me.syncScroll = true;
105595         if (totalCount >= pageSize) {
105596             // end of request was past what the total is, grab from the end back a pageSize
105597             if (requestEnd > totalCount - 1) {
105598                 this.cancelLoad();
105599                 if (store.rangeSatisfied(totalCount - pageSize, totalCount - 1)) {
105600                     me.syncScroll = true;
105601                 }
105602                 store.guaranteeRange(totalCount - pageSize, totalCount - 1);
105603             // Out of range, need to reset the current data set
105604             } else if (visibleStart < guaranteedStart || visibleEnd > guaranteedEnd) {
105605                 if (store.rangeSatisfied(requestStart, requestEnd)) {
105606                     this.cancelLoad();
105607                     store.guaranteeRange(requestStart, requestEnd);
105608                 } else {
105609                     store.mask();
105610                     me.attemptLoad(requestStart, requestEnd);
105611                 }
105612                 // dont sync the scroll view immediately, sync after the range has been guaranteed
105613                 me.syncScroll = false;
105614             } else if (activePrefetch && visibleStart < (guaranteedStart + numFromEdge) && prevPage > 0) {
105615                 me.syncScroll = true;
105616                 store.prefetchPage(prevPage);
105617             } else if (activePrefetch && visibleEnd > (guaranteedEnd - numFromEdge) && nextPage < lastPage) {
105618                 me.syncScroll = true;
105619                 store.prefetchPage(nextPage);
105620             }
105621         }
105622     
105623     
105624         if (me.syncScroll) {
105625             me.syncTo();
105626         }
105627     },
105628     
105629     getSizeCalculation: function() {
105630         // Use the direct ownerCt here rather than the scrollerOwner
105631         // because we are calculating widths/heights.
105632         var owner = this.ownerCt,
105633             view   = owner.getView(),
105634             store  = this.store,
105635             dock   = this.dock,
105636             elDom  = this.el.dom,
105637             width  = 1,
105638             height = 1;
105639         
105640         if (!this.rowHeight) {
105641             this.rowHeight = view.el.down(view.getItemSelector()).getHeight(false, true);
105642         }
105643
105644         height = store.getTotalCount() * this.rowHeight;
105645
105646         if (isNaN(width)) {
105647             width = 1;
105648         }
105649         if (isNaN(height)) {
105650             height = 1;
105651         }
105652         return {
105653             width: width,
105654             height: height
105655         };
105656     },
105657     
105658     attemptLoad: function(start, end) {
105659         var me = this;
105660         if (!me.loadTask) {
105661             me.loadTask = Ext.create('Ext.util.DelayedTask', me.doAttemptLoad, me, []);
105662         }
105663         me.loadTask.delay(me.scrollToLoadBuffer, me.doAttemptLoad, me, [start, end]);
105664     },
105665     
105666     cancelLoad: function() {
105667         if (this.loadTask) {
105668             this.loadTask.cancel();
105669         }
105670     },
105671     
105672     doAttemptLoad:  function(start, end) {
105673         var store = this.getPanel().store;
105674         store.guaranteeRange(start, end);
105675     },
105676     
105677     setViewScrollTop: function(scrollTop, useMax) {
105678         var owner = this.getPanel(),
105679             items = owner.query('tableview'),
105680             i = 0,
105681             len = items.length,
105682             center,
105683             centerEl,
105684             calcScrollTop,
105685             maxScrollTop,
105686             scrollerElDom = this.el.dom;
105687             
105688         owner.virtualScrollTop = scrollTop;
105689             
105690         center = items[1] || items[0];
105691         centerEl = center.el.dom;
105692         
105693         maxScrollTop = ((owner.store.pageSize * this.rowHeight) - centerEl.clientHeight);
105694         calcScrollTop = (scrollTop % ((owner.store.pageSize * this.rowHeight) + 1));
105695         if (useMax) {
105696             calcScrollTop = maxScrollTop;
105697         }
105698         if (calcScrollTop > maxScrollTop) {
105699             //Ext.Error.raise("Calculated scrollTop was larger than maxScrollTop");
105700             return;
105701             // calcScrollTop = maxScrollTop;
105702         }
105703         for (; i < len; i++) {
105704             items[i].el.dom.scrollTop = calcScrollTop;
105705         }
105706     }
105707 });
105708
105709
105710 /**
105711  * @class Ext.panel.Table
105712  * @extends Ext.panel.Panel
105713  * @xtype tablepanel
105714  * @private
105715  * @author Nicolas Ferrero
105716  * TablePanel is a private class and the basis of both TreePanel and GridPanel.
105717  *
105718  * TablePanel aggregates:
105719  *
105720  *  - a Selection Model
105721  *  - a View
105722  *  - a Store
105723  *  - Scrollers
105724  *  - Ext.grid.header.Container
105725  *
105726  */
105727 Ext.define('Ext.panel.Table', {
105728     extend: 'Ext.panel.Panel',
105729
105730     alias: 'widget.tablepanel',
105731
105732     uses: [
105733         'Ext.selection.RowModel',
105734         'Ext.grid.Scroller',
105735         'Ext.grid.header.Container',
105736         'Ext.grid.Lockable'
105737     ],
105738
105739     cls: Ext.baseCSSPrefix + 'grid',
105740     extraBodyCls: Ext.baseCSSPrefix + 'grid-body',
105741
105742     layout: 'fit',
105743     /**
105744      * Boolean to indicate that a view has been injected into the panel.
105745      * @property hasView
105746      */
105747     hasView: false,
105748
105749     // each panel should dictate what viewType and selType to use
105750     viewType: null,
105751     selType: 'rowmodel',
105752
105753     /**
105754      * @cfg {Number} scrollDelta
105755      * Number of pixels to scroll when scrolling with mousewheel.
105756      * Defaults to 40.
105757      */
105758     scrollDelta: 40,
105759
105760     /**
105761      * @cfg {String/Boolean} scroll
105762      * Valid values are 'both', 'horizontal' or 'vertical'. true implies 'both'. false implies 'none'.
105763      * Defaults to true.
105764      */
105765     scroll: true,
105766
105767     /**
105768      * @cfg {Array} columns
105769      * An array of {@link Ext.grid.column.Column column} definition objects which define all columns that appear in this grid. Each
105770      * column definition provides the header text for the column, and a definition of where the data for that column comes from.
105771      */
105772
105773     /**
105774      * @cfg {Boolean} forceFit
105775      * Specify as <code>true</code> to force the columns to fit into the available width. Headers are first sized according to configuration, whether that be
105776      * a specific width, or flex. Then they are all proportionally changed in width so that the entire content width is used..
105777      */
105778
105779     /**
105780      * @cfg {Boolean} hideHeaders
105781      * Specify as <code>true</code> to hide the headers.
105782      */
105783
105784     /**
105785      * @cfg {Boolean} sortableColumns
105786      * Defaults to true. Set to false to disable column sorting via clicking the
105787      * header and via the Sorting menu items.
105788      */
105789     sortableColumns: true,
105790
105791     verticalScrollDock: 'right',
105792     verticalScrollerType: 'gridscroller',
105793
105794     horizontalScrollerPresentCls: Ext.baseCSSPrefix + 'horizontal-scroller-present',
105795     verticalScrollerPresentCls: Ext.baseCSSPrefix + 'vertical-scroller-present',
105796
105797     // private property used to determine where to go down to find views
105798     // this is here to support locking.
105799     scrollerOwner: true,
105800
105801     invalidateScrollerOnRefresh: true,
105802     
105803     enableColumnMove: true,
105804     enableColumnResize: true,
105805
105806
105807     initComponent: function() {
105808         if (!this.viewType) {
105809             Ext.Error.raise("You must specify a viewType config.");
105810         }
105811         if (!this.store) {
105812             Ext.Error.raise("You must specify a store config");
105813         }
105814         if (this.headers) {
105815             Ext.Error.raise("The headers config is not supported. Please specify columns instead.");
105816         }
105817
105818         var me          = this,
105819             scroll      = me.scroll,
105820             vertical    = false,
105821             horizontal  = false,
105822             headerCtCfg = me.columns || me.colModel,
105823             i           = 0,
105824             view,
105825             border = me.border;
105826
105827         // Set our determinScrollbars method to reference a buffered call to determinScrollbars which fires on a 30ms buffer.
105828         me.determineScrollbars = Ext.Function.createBuffered(me.determineScrollbars, 30);
105829         me.injectView = Ext.Function.createBuffered(me.injectView, 30);
105830
105831         if (me.hideHeaders) {
105832             border = false;
105833         }
105834
105835         // The columns/colModel config may be either a fully instantiated HeaderContainer, or an array of Column definitions, or a config object of a HeaderContainer
105836         // Either way, we extract a columns property referencing an array of Column definitions.
105837         if (headerCtCfg instanceof Ext.grid.header.Container) {
105838             me.headerCt = headerCtCfg;
105839             me.headerCt.border = border;
105840             me.columns = me.headerCt.items.items;
105841         } else {
105842             if (Ext.isArray(headerCtCfg)) {
105843                 headerCtCfg = {
105844                     items: headerCtCfg,
105845                     border: border
105846                 };
105847             }
105848             Ext.apply(headerCtCfg, {
105849                 forceFit: me.forceFit,
105850                 sortable: me.sortableColumns,
105851                 enableColumnMove: me.enableColumnMove,
105852                 enableColumnResize: me.enableColumnResize,
105853                 border:  border
105854             });
105855             me.columns = headerCtCfg.items;
105856
105857              // If any of the Column objects contain a locked property, and are not processed, this is a lockable TablePanel, a
105858              // special view will be injected by the Ext.grid.Lockable mixin, so no processing of .
105859              if (Ext.ComponentQuery.query('{locked !== undefined}{processed != true}', me.columns).length) {
105860                  me.self.mixin('lockable', Ext.grid.Lockable);
105861                  me.injectLockable();
105862              }
105863         }
105864
105865         me.store = Ext.data.StoreManager.lookup(me.store);
105866         me.addEvents(
105867             /**
105868              * @event scrollerhide
105869              * Fires when a scroller is hidden
105870              * @param {Ext.grid.Scroller} scroller
105871              * @param {String} orientation Orientation, can be 'vertical' or 'horizontal'
105872              */
105873             'scrollerhide',
105874             /**
105875              * @event scrollershow
105876              * Fires when a scroller is shown
105877              * @param {Ext.grid.Scroller} scroller
105878              * @param {String} orientation Orientation, can be 'vertical' or 'horizontal'
105879              */
105880             'scrollershow'
105881         );
105882
105883         me.bodyCls = me.bodyCls || '';
105884         me.bodyCls += (' ' + me.extraBodyCls);
105885
105886         // autoScroll is not a valid configuration
105887         delete me.autoScroll;
105888
105889         // If this TablePanel is lockable (Either configured lockable, or any of the defined columns has a 'locked' property)
105890         // than a special lockable view containing 2 side-by-side grids will have been injected so we do not need to set up any UI.
105891         if (!me.hasView) {
105892
105893             // If we were not configured with a ready-made headerCt (either by direct config with a headerCt property, or by passing
105894             // a HeaderContainer instance as the 'columns' property, then go ahead and create one from the config object created above.
105895             if (!me.headerCt) {
105896                 me.headerCt = Ext.create('Ext.grid.header.Container', headerCtCfg);
105897             }
105898
105899             // Extract the array of Column objects
105900             me.columns = me.headerCt.items.items;
105901
105902             if (me.hideHeaders) {
105903                 me.headerCt.height = 0;
105904                 me.headerCt.border = false;
105905                 me.headerCt.addCls(Ext.baseCSSPrefix + 'grid-header-ct-hidden');
105906                 me.addCls(Ext.baseCSSPrefix + 'grid-header-hidden');
105907                 // IE Quirks Mode fix
105908                 // If hidden configuration option was used, several layout calculations will be bypassed.
105909                 if (Ext.isIEQuirks) {
105910                     me.headerCt.style = {
105911                         display: 'none'
105912                     };
105913                 }
105914             }
105915
105916             // turn both on.
105917             if (scroll === true || scroll === 'both') {
105918                 vertical = horizontal = true;
105919             } else if (scroll === 'horizontal') {
105920                 horizontal = true;
105921             } else if (scroll === 'vertical') {
105922                 vertical = true;
105923             // All other values become 'none' or false.
105924             } else {
105925                 me.headerCt.availableSpaceOffset = 0;
105926             }
105927
105928             if (vertical) {
105929                 me.verticalScroller = me.verticalScroller || {};
105930                 Ext.applyIf(me.verticalScroller, {
105931                     dock: me.verticalScrollDock,
105932                     xtype: me.verticalScrollerType,
105933                     store: me.store
105934                 });
105935                 me.verticalScroller = Ext.ComponentManager.create(me.verticalScroller);
105936                 me.mon(me.verticalScroller, {
105937                     bodyscroll: me.onVerticalScroll,
105938                     scope: me
105939                 });
105940             }
105941
105942             if (horizontal) {
105943                 me.horizontalScroller = Ext.ComponentManager.create({
105944                     xtype: 'gridscroller',
105945                     section: me,
105946                     dock: 'bottom',
105947                     store: me.store
105948                 });
105949                 me.mon(me.horizontalScroller, {
105950                     bodyscroll: me.onHorizontalScroll,
105951                     scope: me
105952                 });
105953             }
105954
105955             me.headerCt.on('columnresize', me.onHeaderResize, me);
105956             me.relayEvents(me.headerCt, ['columnresize', 'columnmove', 'columnhide', 'columnshow', 'sortchange']);
105957             me.features = me.features || [];
105958             me.dockedItems = me.dockedItems || [];
105959             me.dockedItems.unshift(me.headerCt);
105960             me.viewConfig = me.viewConfig || {};
105961             me.viewConfig.invalidateScrollerOnRefresh = me.invalidateScrollerOnRefresh;
105962
105963             // AbstractDataView will look up a Store configured as an object
105964             // getView converts viewConfig into a View instance
105965             view = me.getView();
105966
105967             if (view) {
105968                 me.mon(view.store, {
105969                     load: me.onStoreLoad,
105970                     scope: me
105971                 });
105972                 me.mon(view, {
105973                     refresh: {
105974                         fn: this.onViewRefresh,
105975                         scope: me,
105976                         buffer: 50
105977                     },
105978                     itemupdate: me.onViewItemUpdate,
105979                     scope: me
105980                 });
105981                 this.relayEvents(view, [
105982                     /**
105983                      * @event beforeitemmousedown
105984                      * Fires before the mousedown event on an item is processed. Returns false to cancel the default action.
105985                      * @param {Ext.view.View} this
105986                      * @param {Ext.data.Model} record The record that belongs to the item
105987                      * @param {HTMLElement} item The item's element
105988                      * @param {Number} index The item's index
105989                      * @param {Ext.EventObject} e The raw event object
105990                      */
105991                     'beforeitemmousedown',
105992                     /**
105993                      * @event beforeitemmouseup
105994                      * Fires before the mouseup event on an item is processed. Returns false to cancel the default action.
105995                      * @param {Ext.view.View} this
105996                      * @param {Ext.data.Model} record The record that belongs to the item
105997                      * @param {HTMLElement} item The item's element
105998                      * @param {Number} index The item's index
105999                      * @param {Ext.EventObject} e The raw event object
106000                      */
106001                     'beforeitemmouseup',
106002                     /**
106003                      * @event beforeitemmouseenter
106004                      * Fires before the mouseenter event on an item is processed. Returns false to cancel the default action.
106005                      * @param {Ext.view.View} this
106006                      * @param {Ext.data.Model} record The record that belongs to the item
106007                      * @param {HTMLElement} item The item's element
106008                      * @param {Number} index The item's index
106009                      * @param {Ext.EventObject} e The raw event object
106010                      */
106011                     'beforeitemmouseenter',
106012                     /**
106013                      * @event beforeitemmouseleave
106014                      * Fires before the mouseleave event on an item is processed. Returns false to cancel the default action.
106015                      * @param {Ext.view.View} this
106016                      * @param {Ext.data.Model} record The record that belongs to the item
106017                      * @param {HTMLElement} item The item's element
106018                      * @param {Number} index The item's index
106019                      * @param {Ext.EventObject} e The raw event object
106020                      */
106021                     'beforeitemmouseleave',
106022                     /**
106023                      * @event beforeitemclick
106024                      * Fires before the click event on an item is processed. Returns false to cancel the default action.
106025                      * @param {Ext.view.View} this
106026                      * @param {Ext.data.Model} record The record that belongs to the item
106027                      * @param {HTMLElement} item The item's element
106028                      * @param {Number} index The item's index
106029                      * @param {Ext.EventObject} e The raw event object
106030                      */
106031                     'beforeitemclick',
106032                     /**
106033                      * @event beforeitemdblclick
106034                      * Fires before the dblclick event on an item is processed. Returns false to cancel the default action.
106035                      * @param {Ext.view.View} this
106036                      * @param {Ext.data.Model} record The record that belongs to the item
106037                      * @param {HTMLElement} item The item's element
106038                      * @param {Number} index The item's index
106039                      * @param {Ext.EventObject} e The raw event object
106040                      */
106041                     'beforeitemdblclick',
106042                     /**
106043                      * @event beforeitemcontextmenu
106044                      * Fires before the contextmenu event on an item is processed. Returns false to cancel the default action.
106045                      * @param {Ext.view.View} this
106046                      * @param {Ext.data.Model} record The record that belongs to the item
106047                      * @param {HTMLElement} item The item's element
106048                      * @param {Number} index The item's index
106049                      * @param {Ext.EventObject} e The raw event object
106050                      */
106051                     'beforeitemcontextmenu',
106052                     /**
106053                      * @event itemmousedown
106054                      * Fires when there is a mouse down on an item
106055                      * @param {Ext.view.View} this
106056                      * @param {Ext.data.Model} record The record that belongs to the item
106057                      * @param {HTMLElement} item The item's element
106058                      * @param {Number} index The item's index
106059                      * @param {Ext.EventObject} e The raw event object
106060                      */
106061                     'itemmousedown',
106062                     /**
106063                      * @event itemmouseup
106064                      * Fires when there is a mouse up on an item
106065                      * @param {Ext.view.View} this
106066                      * @param {Ext.data.Model} record The record that belongs to the item
106067                      * @param {HTMLElement} item The item's element
106068                      * @param {Number} index The item's index
106069                      * @param {Ext.EventObject} e The raw event object
106070                      */
106071                     'itemmouseup',
106072                     /**
106073                      * @event itemmouseenter
106074                      * Fires when the mouse enters an item.
106075                      * @param {Ext.view.View} this
106076                      * @param {Ext.data.Model} record The record that belongs to the item
106077                      * @param {HTMLElement} item The item's element
106078                      * @param {Number} index The item's index
106079                      * @param {Ext.EventObject} e The raw event object
106080                      */
106081                     'itemmouseenter',
106082                     /**
106083                      * @event itemmouseleave
106084                      * Fires when the mouse leaves an item.
106085                      * @param {Ext.view.View} this
106086                      * @param {Ext.data.Model} record The record that belongs to the item
106087                      * @param {HTMLElement} item The item's element
106088                      * @param {Number} index The item's index
106089                      * @param {Ext.EventObject} e The raw event object
106090                      */
106091                     'itemmouseleave',
106092                     /**
106093                      * @event itemclick
106094                      * Fires when an item is clicked.
106095                      * @param {Ext.view.View} this
106096                      * @param {Ext.data.Model} record The record that belongs to the item
106097                      * @param {HTMLElement} item The item's element
106098                      * @param {Number} index The item's index
106099                      * @param {Ext.EventObject} e The raw event object
106100                      */
106101                     'itemclick',
106102                     /**
106103                      * @event itemdblclick
106104                      * Fires when an item is double clicked.
106105                      * @param {Ext.view.View} this
106106                      * @param {Ext.data.Model} record The record that belongs to the item
106107                      * @param {HTMLElement} item The item's element
106108                      * @param {Number} index The item's index
106109                      * @param {Ext.EventObject} e The raw event object
106110                      */
106111                     'itemdblclick',
106112                     /**
106113                      * @event itemcontextmenu
106114                      * Fires when an item is right clicked.
106115                      * @param {Ext.view.View} this
106116                      * @param {Ext.data.Model} record The record that belongs to the item
106117                      * @param {HTMLElement} item The item's element
106118                      * @param {Number} index The item's index
106119                      * @param {Ext.EventObject} e The raw event object
106120                      */
106121                     'itemcontextmenu',
106122                     /**
106123                      * @event beforecontainermousedown
106124                      * Fires before the mousedown event on the container is processed. Returns false to cancel the default action.
106125                      * @param {Ext.view.View} this
106126                      * @param {Ext.EventObject} e The raw event object
106127                      */
106128                     'beforecontainermousedown',
106129                     /**
106130                      * @event beforecontainermouseup
106131                      * Fires before the mouseup event on the container is processed. Returns false to cancel the default action.
106132                      * @param {Ext.view.View} this
106133                      * @param {Ext.EventObject} e The raw event object
106134                      */
106135                     'beforecontainermouseup',
106136                     /**
106137                      * @event beforecontainermouseover
106138                      * Fires before the mouseover event on the container is processed. Returns false to cancel the default action.
106139                      * @param {Ext.view.View} this
106140                      * @param {Ext.EventObject} e The raw event object
106141                      */
106142                     'beforecontainermouseover',
106143                     /**
106144                      * @event beforecontainermouseout
106145                      * Fires before the mouseout event on the container is processed. Returns false to cancel the default action.
106146                      * @param {Ext.view.View} this
106147                      * @param {Ext.EventObject} e The raw event object
106148                      */
106149                     'beforecontainermouseout',
106150                     /**
106151                      * @event beforecontainerclick
106152                      * Fires before the click event on the container is processed. Returns false to cancel the default action.
106153                      * @param {Ext.view.View} this
106154                      * @param {Ext.EventObject} e The raw event object
106155                      */
106156                     'beforecontainerclick',
106157                     /**
106158                      * @event beforecontainerdblclick
106159                      * Fires before the dblclick event on the container is processed. Returns false to cancel the default action.
106160                      * @param {Ext.view.View} this
106161                      * @param {Ext.EventObject} e The raw event object
106162                      */
106163                     'beforecontainerdblclick',
106164                     /**
106165                      * @event beforecontainercontextmenu
106166                      * Fires before the contextmenu event on the container is processed. Returns false to cancel the default action.
106167                      * @param {Ext.view.View} this
106168                      * @param {Ext.EventObject} e The raw event object
106169                      */
106170                     'beforecontainercontextmenu',
106171                     /**
106172                      * @event containermouseup
106173                      * Fires when there is a mouse up on the container
106174                      * @param {Ext.view.View} this
106175                      * @param {Ext.EventObject} e The raw event object
106176                      */
106177                     'containermouseup',
106178                     /**
106179                      * @event containermouseover
106180                      * Fires when you move the mouse over the container.
106181                      * @param {Ext.view.View} this
106182                      * @param {Ext.EventObject} e The raw event object
106183                      */
106184                     'containermouseover',
106185                     /**
106186                      * @event containermouseout
106187                      * Fires when you move the mouse out of the container.
106188                      * @param {Ext.view.View} this
106189                      * @param {Ext.EventObject} e The raw event object
106190                      */
106191                     'containermouseout',
106192                     /**
106193                      * @event containerclick
106194                      * Fires when the container is clicked.
106195                      * @param {Ext.view.View} this
106196                      * @param {Ext.EventObject} e The raw event object
106197                      */
106198                     'containerclick',
106199                     /**
106200                      * @event containerdblclick
106201                      * Fires when the container is double clicked.
106202                      * @param {Ext.view.View} this
106203                      * @param {Ext.EventObject} e The raw event object
106204                      */
106205                     'containerdblclick',
106206                     /**
106207                      * @event containercontextmenu
106208                      * Fires when the container is right clicked.
106209                      * @param {Ext.view.View} this
106210                      * @param {Ext.EventObject} e The raw event object
106211                      */
106212                     'containercontextmenu',
106213
106214                     /**
106215                      * @event selectionchange
106216                      * Fires when the selected nodes change. Relayed event from the underlying selection model.
106217                      * @param {Ext.view.View} this
106218                      * @param {Array} selections Array of the selected nodes
106219                      */
106220                     'selectionchange',
106221                     /**
106222                      * @event beforeselect
106223                      * Fires before a selection is made. If any handlers return false, the selection is cancelled.
106224                      * @param {Ext.view.View} this
106225                      * @param {HTMLElement} node The node to be selected
106226                      * @param {Array} selections Array of currently selected nodes
106227                      */
106228                     'beforeselect'
106229                 ]);
106230             }
106231         }
106232         me.callParent(arguments);
106233     },
106234
106235     // state management
106236     initStateEvents: function(){
106237         var events = this.stateEvents;
106238         // push on stateEvents if they don't exist
106239         Ext.each(['columnresize', 'columnmove', 'columnhide', 'columnshow', 'sortchange'], function(event){
106240             if (Ext.Array.indexOf(events, event)) {
106241                 events.push(event);
106242             }
106243         });
106244         this.callParent();
106245     },
106246
106247     getState: function(){
106248         var state = {
106249             columns: []
106250         },
106251         sorter = this.store.sorters.first();
106252
106253         this.headerCt.items.each(function(header){
106254             state.columns.push({
106255                 id: header.headerId,
106256                 width: header.flex ? undefined : header.width,
106257                 hidden: header.hidden,
106258                 sortable: header.sortable
106259             });
106260         });
106261
106262         if (sorter) {
106263             state.sort = {
106264                 property: sorter.property,
106265                 direction: sorter.direction
106266             };
106267         }
106268         return state;
106269     },
106270
106271     applyState: function(state) {
106272         var headers = state.columns,
106273             length = headers ? headers.length : 0,
106274             headerCt = this.headerCt,
106275             items = headerCt.items,
106276             sorter = state.sort,
106277             store = this.store,
106278             i = 0,
106279             index,
106280             headerState,
106281             header;
106282
106283         for (; i < length; ++i) {
106284             headerState = headers[i];
106285             header = headerCt.down('gridcolumn[headerId=' + headerState.id + ']');
106286             index = items.indexOf(header);
106287             if (i !== index) {
106288                 headerCt.moveHeader(index, i);
106289             }
106290             header.sortable = headerState.sortable;
106291             if (Ext.isDefined(headerState.width)) {
106292                 delete header.flex;
106293                 if (header.rendered) {
106294                     header.setWidth(headerState.width);
106295                 } else {
106296                     header.minWidth = header.width = headerState.width;
106297                 }
106298             }
106299             header.hidden = headerState.hidden;
106300         }
106301
106302         if (sorter) {
106303             if (store.remoteSort) {
106304                 store.sorters.add(Ext.create('Ext.util.Sorter', {
106305                     property: sorter.property,
106306                     direction: sorter.direction
106307                 }));
106308             }
106309             else {
106310                 store.sort(sorter.property, sorter.direction);
106311             }
106312         }
106313     },
106314
106315     /**
106316      * Returns the store associated with this Panel.
106317      * @return {Ext.data.Store} The store
106318      */
106319     getStore: function(){
106320         return this.store;
106321     },
106322
106323     /**
106324      * Gets the view for this panel.
106325      * @return {Ext.view.Table}
106326      */
106327     getView: function() {
106328         var me = this,
106329             sm;
106330
106331         if (!me.view) {
106332             sm = me.getSelectionModel();
106333             me.view = me.createComponent(Ext.apply({}, me.viewConfig, {
106334                 xtype: me.viewType,
106335                 store: me.store,
106336                 headerCt: me.headerCt,
106337                 selModel: sm,
106338                 features: me.features,
106339                 panel: me
106340             }));
106341             me.mon(me.view, {
106342                 uievent: me.processEvent,
106343                 scope: me
106344             });
106345             sm.view = me.view;
106346             me.headerCt.view = me.view;
106347             me.relayEvents(me.view, ['cellclick', 'celldblclick']);
106348         }
106349         return me.view;
106350     },
106351
106352     /**
106353      * @private
106354      * @override
106355      * autoScroll is never valid for all classes which extend TablePanel.
106356      */
106357     setAutoScroll: Ext.emptyFn,
106358
106359     // This method hijacks Ext.view.Table's el scroll method.
106360     // This enables us to keep the virtualized scrollbars in sync
106361     // with the view. It currently does NOT support animation.
106362     elScroll: function(direction, distance, animate) {
106363         var me = this,
106364             scroller;
106365
106366         if (direction === "up" || direction === "left") {
106367             distance = -distance;
106368         }
106369
106370         if (direction === "down" || direction === "up") {
106371             scroller = me.getVerticalScroller();
106372             scroller.scrollByDeltaY(distance);
106373         } else {
106374             scroller = me.getHorizontalScroller();
106375             scroller.scrollByDeltaX(distance);
106376         }
106377     },
106378     
106379     afterLayout: function() {
106380         this.callParent(arguments);
106381         this.injectView();
106382     },
106383     
106384
106385     /**
106386      * @private
106387      * Called after this Component has achieved its correct initial size, after all layouts have done their thing.
106388      * This is so we can add the View only after the initial size is known. This method is buffered 30ms.
106389      */
106390     injectView: function() {
106391         if (!this.hasView && !this.collapsed) {
106392             var me   = this,
106393                 view = me.getView();
106394
106395             me.hasView = true;
106396             me.add(view);
106397
106398             // hijack the view el's scroll method
106399             view.el.scroll = Ext.Function.bind(me.elScroll, me);
106400             // We use to listen to document.body wheel events, but that's a
106401             // little much. We scope just to the view now.
106402             me.mon(view.el, {
106403                 mousewheel: me.onMouseWheel,
106404                 scope: me
106405             });
106406         }
106407     },
106408
106409     afterExpand: function() {
106410         this.callParent(arguments);
106411         if (!this.hasView) {
106412             this.injectView();
106413         }
106414     },
106415
106416     /**
106417      * @private
106418      * Process UI events from the view. Propagate them to whatever internal Components need to process them
106419      * @param {String} type Event type, eg 'click'
106420      * @param {TableView} view TableView Component
106421      * @param {HtmlElement} cell Cell HtmlElement the event took place within
106422      * @param {Number} recordIndex Index of the associated Store Model (-1 if none)
106423      * @param {Number} cellIndex Cell index within the row
106424      * @param {EventObject} e Original event
106425      */
106426     processEvent: function(type, view, cell, recordIndex, cellIndex, e) {
106427         var me = this,
106428             header;
106429
106430         if (cellIndex !== -1) {
106431             header = me.headerCt.getGridColumns()[cellIndex];
106432             return header.processEvent.apply(header, arguments);
106433         }
106434     },
106435
106436     /**
106437      * Request a recalculation of scrollbars and put them in if they are needed.
106438      */
106439     determineScrollbars: function() {
106440         var me = this,
106441             viewElDom,
106442             centerScrollWidth,
106443             centerClientWidth,
106444             scrollHeight,
106445             clientHeight;
106446
106447         if (!me.collapsed && me.view && me.view.el) {
106448             viewElDom = me.view.el.dom;
106449             //centerScrollWidth = viewElDom.scrollWidth;
106450             centerScrollWidth = me.headerCt.getFullWidth();
106451             /**
106452              * clientWidth often returns 0 in IE resulting in an
106453              * infinity result, here we use offsetWidth bc there are
106454              * no possible scrollbars and we don't care about margins
106455              */
106456             centerClientWidth = viewElDom.offsetWidth;
106457             if (me.verticalScroller && me.verticalScroller.el) {
106458                 scrollHeight = me.verticalScroller.getSizeCalculation().height;
106459             } else {
106460                 scrollHeight = viewElDom.scrollHeight;
106461             }
106462
106463             clientHeight = viewElDom.clientHeight;
106464
106465             if (!me.collapsed && scrollHeight > clientHeight) {
106466                 me.showVerticalScroller();
106467             } else {
106468                 me.hideVerticalScroller();
106469             }
106470
106471             if (!me.collapsed && centerScrollWidth > (centerClientWidth + Ext.getScrollBarWidth() - 2)) {
106472                 me.showHorizontalScroller();
106473             } else {
106474                 me.hideHorizontalScroller();
106475             }
106476         }
106477     },
106478
106479     onHeaderResize: function() {
106480         if (this.view && this.view.rendered) {
106481             this.determineScrollbars();
106482             this.invalidateScroller();
106483         }
106484     },
106485
106486     /**
106487      * Hide the verticalScroller and remove the horizontalScrollerPresentCls.
106488      */
106489     hideHorizontalScroller: function() {
106490         var me = this;
106491
106492         if (me.horizontalScroller && me.horizontalScroller.ownerCt === me) {
106493             me.verticalScroller.offsets.bottom = 0;
106494             me.removeDocked(me.horizontalScroller, false);
106495             me.removeCls(me.horizontalScrollerPresentCls);
106496             me.fireEvent('scrollerhide', me.horizontalScroller, 'horizontal');
106497         }
106498
106499     },
106500
106501     /**
106502      * Show the horizontalScroller and add the horizontalScrollerPresentCls.
106503      */
106504     showHorizontalScroller: function() {
106505         var me = this;
106506
106507         if (me.verticalScroller) {
106508             me.verticalScroller.offsets.bottom = Ext.getScrollBarWidth() - 2;
106509         }
106510         if (me.horizontalScroller && me.horizontalScroller.ownerCt !== me) {
106511             me.addDocked(me.horizontalScroller);
106512             me.addCls(me.horizontalScrollerPresentCls);
106513             me.fireEvent('scrollershow', me.horizontalScroller, 'horizontal');
106514         }
106515     },
106516
106517     /**
106518      * Hide the verticalScroller and remove the verticalScrollerPresentCls.
106519      */
106520     hideVerticalScroller: function() {
106521         var me = this,
106522             headerCt = me.headerCt;
106523
106524         // only trigger a layout when reserveOffset is changing
106525         if (headerCt && headerCt.layout.reserveOffset) {
106526             headerCt.layout.reserveOffset = false;
106527             headerCt.doLayout();
106528         }
106529         if (me.verticalScroller && me.verticalScroller.ownerCt === me) {
106530             me.removeDocked(me.verticalScroller, false);
106531             me.removeCls(me.verticalScrollerPresentCls);
106532             me.fireEvent('scrollerhide', me.verticalScroller, 'vertical');
106533         }
106534     },
106535
106536     /**
106537      * Show the verticalScroller and add the verticalScrollerPresentCls.
106538      */
106539     showVerticalScroller: function() {
106540         var me = this,
106541             headerCt = me.headerCt;
106542
106543         // only trigger a layout when reserveOffset is changing
106544         if (headerCt && !headerCt.layout.reserveOffset) {
106545             headerCt.layout.reserveOffset = true;
106546             headerCt.doLayout();
106547         }
106548         if (me.verticalScroller && me.verticalScroller.ownerCt !== me) {
106549             me.addDocked(me.verticalScroller);
106550             me.addCls(me.verticalScrollerPresentCls);
106551             me.fireEvent('scrollershow', me.verticalScroller, 'vertical');
106552         }
106553     },
106554
106555     /**
106556      * Invalides scrollers that are present and forces a recalculation.
106557      * (Not related to showing/hiding the scrollers)
106558      */
106559     invalidateScroller: function() {
106560         var me = this,
106561             vScroll = me.verticalScroller,
106562             hScroll = me.horizontalScroller;
106563
106564         if (vScroll) {
106565             vScroll.invalidate();
106566         }
106567         if (hScroll) {
106568             hScroll.invalidate();
106569         }
106570     },
106571
106572     // refresh the view when a header moves
106573     onHeaderMove: function(headerCt, header, fromIdx, toIdx) {
106574         this.view.refresh();
106575     },
106576
106577     // Section onHeaderHide is invoked after view.
106578     onHeaderHide: function(headerCt, header) {
106579         this.invalidateScroller();
106580     },
106581
106582     onHeaderShow: function(headerCt, header) {
106583         this.invalidateScroller();
106584     },
106585
106586     getVerticalScroller: function() {
106587         return this.getScrollerOwner().down('gridscroller[dock=' + this.verticalScrollDock + ']');
106588     },
106589
106590     getHorizontalScroller: function() {
106591         return this.getScrollerOwner().down('gridscroller[dock=bottom]');
106592     },
106593
106594     onMouseWheel: function(e) {
106595         var me = this,
106596             browserEvent = e.browserEvent,
106597             vertScroller = me.getVerticalScroller(),
106598             horizScroller = me.getHorizontalScroller(),
106599             scrollDelta = me.scrollDelta,
106600             deltaY, deltaX,
106601             vertScrollerEl, horizScrollerEl,
106602             origScrollLeft, origScrollTop,
106603             newScrollLeft, newScrollTop;
106604
106605         // Track original scroll values, so we can see if we've
106606         // reached the end of our scroll height/width.
106607         if (horizScroller) {
106608             horizScrollerEl = horizScroller.el;
106609             if (horizScrollerEl) {
106610                 origScrollLeft = horizScrollerEl.dom.scrollLeft;
106611             }
106612         }
106613         if (vertScroller) {
106614             vertScrollerEl = vertScroller.el;
106615             if (vertScrollerEl) {
106616                 origScrollTop = vertScrollerEl.dom.scrollTop;
106617             }
106618         }
106619
106620         // Webkit Horizontal Axis
106621         if (browserEvent.wheelDeltaX || browserEvent.wheelDeltaY) {
106622             deltaX = -browserEvent.wheelDeltaX / 120 * scrollDelta / 3;
106623             deltaY = -browserEvent.wheelDeltaY / 120 * scrollDelta / 3;
106624             if (horizScroller) {
106625                 newScrollLeft = horizScroller.scrollByDeltaX(deltaX);
106626             }
106627             if (vertScroller) {
106628                 newScrollTop = vertScroller.scrollByDeltaY(deltaY);
106629             }
106630         } else {
106631             // Gecko Horizontal Axis
106632             if (browserEvent.axis && browserEvent.axis === 1) {
106633                 if (horizScroller) {
106634                     deltaX = -(scrollDelta * e.getWheelDelta()) / 3;
106635                     newScrollLeft = horizScroller.scrollByDeltaX(deltaX);
106636                 }
106637             } else {
106638                 if (vertScroller) {
106639
106640                     deltaY = -(scrollDelta * e.getWheelDelta() / 3);
106641                     newScrollTop = vertScroller.scrollByDeltaY(deltaY);
106642                 }
106643             }
106644         }
106645
106646         // If after given our delta, the scroller has not progressed, then we're
106647         // at the end of our scroll range and shouldn't stop the browser event.
106648         if ((deltaX !== 0 && newScrollLeft !== origScrollLeft) ||
106649             (deltaY !== 0 && newScrollTop !== origScrollTop)) {
106650             e.stopEvent();
106651         }
106652     },
106653
106654     /**
106655      * @private
106656      * Determine and invalidate scrollers on view refresh
106657      */
106658     onViewRefresh: function() {
106659         if (Ext.isIE) {
106660             this.syncCellHeight();
106661         }
106662         this.determineScrollbars();
106663         if (this.invalidateScrollerOnRefresh) {
106664             this.invalidateScroller();
106665         }
106666     },
106667
106668     onViewItemUpdate: function(record, index, tr) {
106669         if (Ext.isIE) {
106670             this.syncCellHeight([tr]);
106671         }
106672     },
106673
106674     // BrowserBug: IE will not stretch the td to fit the height of the entire
106675     // tr, so manually sync cellheights on refresh and when an item has been
106676     // updated.
106677     syncCellHeight: function(trs) {
106678         var me    = this,
106679             i     = 0,
106680             tds,
106681             j, tdsLn,
106682             tr, td,
106683             trsLn,
106684             rowHeights = [],
106685             cellHeights,
106686             cellClsSelector = ('.' + Ext.baseCSSPrefix + 'grid-cell');
106687
106688         trs   = trs || me.view.getNodes();
106689         
106690         trsLn = trs.length;
106691         // Reading loop
106692         for (; i < trsLn; i++) {
106693             tr = trs[i];
106694             tds = Ext.fly(tr).query(cellClsSelector);
106695             tdsLn = tds.length;
106696             cellHeights = [];
106697             for (j = 0; j < tdsLn; j++) {
106698                 td = tds[j];
106699                 cellHeights.push(td.clientHeight);
106700             }
106701             rowHeights.push(Ext.Array.max(cellHeights));
106702         }
106703
106704         // Setting loop
106705         for (i = 0; i < trsLn; i++) {
106706             tr = trs[i];
106707             tdsLn = tr.childNodes.length;
106708             for (j = 0; j < tdsLn; j++) {
106709                 td = Ext.fly(tr.childNodes[j]);
106710                 if (rowHeights[i]) {
106711                     if (td.is(cellClsSelector)) {
106712                         td.setHeight(rowHeights[i]);
106713                     } else {
106714                         td.down(cellClsSelector).setHeight(rowHeights[i]);
106715                     }
106716                 }
106717                 
106718             }
106719         }
106720     },
106721
106722     /**
106723      * Sets the scrollTop of the TablePanel.
106724      * @param {Number} deltaY
106725      */
106726     setScrollTop: function(top) {
106727         var me               = this,
106728             rootCmp          = me.getScrollerOwner(),
106729             verticalScroller = me.getVerticalScroller();
106730
106731         rootCmp.virtualScrollTop = top;
106732         if (verticalScroller) {
106733             verticalScroller.setScrollTop(top);
106734         }
106735
106736     },
106737
106738     getScrollerOwner: function() {
106739         var rootCmp = this;
106740         if (!this.scrollerOwner) {
106741             rootCmp = this.up('[scrollerOwner]');
106742         }
106743         return rootCmp;
106744     },
106745
106746     /**
106747      * Scrolls the TablePanel by deltaY
106748      * @param {Number} deltaY
106749      */
106750     scrollByDeltaY: function(deltaY) {
106751         var rootCmp = this.getScrollerOwner(),
106752             scrollerRight;
106753         scrollerRight = rootCmp.down('gridscroller[dock=' + this.verticalScrollDock + ']');
106754         if (scrollerRight) {
106755             scrollerRight.scrollByDeltaY(deltaY);
106756         }
106757     },
106758
106759
106760     /**
106761      * Scrolls the TablePanel by deltaX
106762      * @param {Number} deltaY
106763      */
106764     scrollByDeltaX: function(deltaX) {
106765         this.horizontalScroller.scrollByDeltaX(deltaX);
106766     },
106767
106768     /**
106769      * Get left hand side marker for header resizing.
106770      * @private
106771      */
106772     getLhsMarker: function() {
106773         var me = this;
106774
106775         if (!me.lhsMarker) {
106776             me.lhsMarker = Ext.core.DomHelper.append(me.el, {
106777                 cls: Ext.baseCSSPrefix + 'grid-resize-marker'
106778             }, true);
106779         }
106780         return me.lhsMarker;
106781     },
106782
106783     /**
106784      * Get right hand side marker for header resizing.
106785      * @private
106786      */
106787     getRhsMarker: function() {
106788         var me = this;
106789
106790         if (!me.rhsMarker) {
106791             me.rhsMarker = Ext.core.DomHelper.append(me.el, {
106792                 cls: Ext.baseCSSPrefix + 'grid-resize-marker'
106793             }, true);
106794         }
106795         return me.rhsMarker;
106796     },
106797
106798     /**
106799      * Returns the selection model being used and creates it via the configuration
106800      * if it has not been created already.
106801      * @return {Ext.selection.Model} selModel
106802      */
106803     getSelectionModel: function(){
106804         if (!this.selModel) {
106805             this.selModel = {};
106806         }
106807
106808         var mode = 'SINGLE',
106809             type;
106810         if (this.simpleSelect) {
106811             mode = 'SIMPLE';
106812         } else if (this.multiSelect) {
106813             mode = 'MULTI';
106814         }
106815
106816         Ext.applyIf(this.selModel, {
106817             allowDeselect: this.allowDeselect,
106818             mode: mode
106819         });
106820
106821         if (!this.selModel.events) {
106822             type = this.selModel.selType || this.selType;
106823             this.selModel = Ext.create('selection.' + type, this.selModel);
106824         }
106825
106826         if (!this.selModel.hasRelaySetup) {
106827             this.relayEvents(this.selModel, ['selectionchange', 'select', 'deselect']);
106828             this.selModel.hasRelaySetup = true;
106829         }
106830
106831         // lock the selection model if user
106832         // has disabled selection
106833         if (this.disableSelection) {
106834             this.selModel.locked = true;
106835         }
106836         return this.selModel;
106837     },
106838
106839     onVerticalScroll: function(event, target) {
106840         var owner = this.getScrollerOwner(),
106841             items = owner.query('tableview'),
106842             i = 0,
106843             len = items.length;
106844
106845         for (; i < len; i++) {
106846             items[i].el.dom.scrollTop = target.scrollTop;
106847         }
106848     },
106849
106850     onHorizontalScroll: function(event, target) {
106851         var owner = this.getScrollerOwner(),
106852             items = owner.query('tableview'),
106853             i = 0,
106854             len = items.length,
106855             center,
106856             centerEl,
106857             centerScrollWidth,
106858             centerClientWidth,
106859             width;
106860
106861         center = items[1] || items[0];
106862         centerEl = center.el.dom;
106863         centerScrollWidth = centerEl.scrollWidth;
106864         centerClientWidth = centerEl.offsetWidth;
106865         width = this.horizontalScroller.getWidth();
106866
106867         centerEl.scrollLeft = target.scrollLeft;
106868         this.headerCt.el.dom.scrollLeft = target.scrollLeft;
106869     },
106870
106871     // template method meant to be overriden
106872     onStoreLoad: Ext.emptyFn,
106873
106874     getEditorParent: function() {
106875         return this.body;
106876     },
106877
106878     bindStore: function(store) {
106879         var me = this;
106880         me.store = store;
106881         me.getView().bindStore(store);
106882     },
106883
106884     reconfigure: function(store, columns) {
106885         var me = this;
106886
106887         if (me.lockable) {
106888             me.reconfigureLockable(store, columns);
106889             return;
106890         }
106891
106892         if (columns) {
106893             me.headerCt.removeAll();
106894             me.headerCt.add(columns);
106895         }
106896         if (store) {
106897             store = Ext.StoreManager.lookup(store);
106898             me.bindStore(store);
106899         } else {
106900             me.getView().refresh();
106901         }
106902     },
106903
106904     afterComponentLayout: function() {
106905         this.callParent(arguments);
106906         this.determineScrollbars();
106907         this.invalidateScroller();
106908     }
106909 });
106910 /**
106911  * @class Ext.view.Table
106912  * @extends Ext.view.View
106913
106914 This class encapsulates the user interface for a tabular data set.
106915 It acts as a centralized manager for controlling the various interface
106916 elements of the view. This includes handling events, such as row and cell
106917 level based DOM events. It also reacts to events from the underlying {@link Ext.selection.Model}
106918 to provide visual feedback to the user. 
106919
106920 This class does not provide ways to manipulate the underlying data of the configured
106921 {@link Ext.data.Store}.
106922
106923 This is the base class for both {@link Ext.grid.View} and {@link Ext.tree.View} and is not
106924 to be used directly.
106925
106926  * @markdown
106927  * @abstract
106928  * @xtype tableview
106929  * @author Nicolas Ferrero
106930  */
106931 Ext.define('Ext.view.Table', {
106932     extend: 'Ext.view.View',
106933     alias: 'widget.tableview',
106934     uses: [
106935         'Ext.view.TableChunker',
106936         'Ext.util.DelayedTask',
106937         'Ext.util.MixedCollection'
106938     ],
106939
106940     cls: Ext.baseCSSPrefix + 'grid-view',
106941
106942     // row
106943     itemSelector: '.' + Ext.baseCSSPrefix + 'grid-row',
106944     // cell
106945     cellSelector: '.' + Ext.baseCSSPrefix + 'grid-cell',
106946
106947     selectedItemCls: Ext.baseCSSPrefix + 'grid-row-selected',
106948     selectedCellCls: Ext.baseCSSPrefix + 'grid-cell-selected',
106949     focusedItemCls: Ext.baseCSSPrefix + 'grid-row-focused',
106950     overItemCls: Ext.baseCSSPrefix + 'grid-row-over',
106951     altRowCls:   Ext.baseCSSPrefix + 'grid-row-alt',
106952     rowClsRe: /(?:^|\s*)grid-row-(first|last|alt)(?:\s+|$)/g,
106953     cellRe: new RegExp('x-grid-cell-([^\\s]+) ', ''),
106954
106955     // cfg docs inherited
106956     trackOver: true,
106957
106958     /**
106959      * Override this function to apply custom CSS classes to rows during rendering.  You can also supply custom
106960      * parameters to the row template for the current row to customize how it is rendered using the <b>rowParams</b>
106961      * parameter.  This function should return the CSS class name (or empty string '' for none) that will be added
106962      * to the row's wrapping div.  To apply multiple class names, simply return them space-delimited within the string
106963      * (e.g., 'my-class another-class'). Example usage:
106964     <pre><code>
106965 viewConfig: {
106966     forceFit: true,
106967     showPreview: true, // custom property
106968     enableRowBody: true, // required to create a second, full-width row to show expanded Record data
106969     getRowClass: function(record, rowIndex, rp, ds){ // rp = rowParams
106970         if(this.showPreview){
106971             rp.body = '&lt;p>'+record.data.excerpt+'&lt;/p>';
106972             return 'x-grid3-row-expanded';
106973         }
106974         return 'x-grid3-row-collapsed';
106975     }
106976 },
106977     </code></pre>
106978      * @param {Model} model The {@link Ext.data.Model} corresponding to the current row.
106979      * @param {Number} index The row index.
106980      * @param {Object} rowParams (DEPRECATED) A config object that is passed to the row template during rendering that allows
106981      * customization of various aspects of a grid row.
106982      * <p>If {@link #enableRowBody} is configured <b><tt></tt>true</b>, then the following properties may be set
106983      * by this function, and will be used to render a full-width expansion row below each grid row:</p>
106984      * <ul>
106985      * <li><code>body</code> : String <div class="sub-desc">An HTML fragment to be used as the expansion row's body content (defaults to '').</div></li>
106986      * <li><code>bodyStyle</code> : String <div class="sub-desc">A CSS style specification that will be applied to the expansion row's &lt;tr> element. (defaults to '').</div></li>
106987      * </ul>
106988      * The following property will be passed in, and may be appended to:
106989      * <ul>
106990      * <li><code>tstyle</code> : String <div class="sub-desc">A CSS style specification that willl be applied to the &lt;table> element which encapsulates
106991      * both the standard grid row, and any expansion row.</div></li>
106992      * </ul>
106993      * @param {Store} store The {@link Ext.data.Store} this grid is bound to
106994      * @method getRowClass
106995      * @return {String} a CSS class name to add to the row.
106996      */
106997     getRowClass: null,
106998
106999     initComponent: function() {
107000         this.scrollState = {};
107001         this.selModel.view = this;
107002         this.headerCt.view = this;
107003         this.initFeatures();
107004         this.setNewTemplate();
107005         this.callParent();
107006         this.mon(this.store, {
107007             load: this.onStoreLoad,
107008             scope: this
107009         });
107010
107011         // this.addEvents(
107012         //     /**
107013         //      * @event rowfocus
107014         //      * @param {Ext.data.Record} record
107015         //      * @param {HTMLElement} row
107016         //      * @param {Number} rowIdx
107017         //      */
107018         //     'rowfocus'
107019         // );
107020     },
107021
107022     // scroll to top of the grid when store loads
107023     onStoreLoad: function(){
107024         if (this.invalidateScrollerOnRefresh) {
107025             if (Ext.isGecko) {
107026                 if (!this.scrollToTopTask) {
107027                     this.scrollToTopTask = Ext.create('Ext.util.DelayedTask', this.scrollToTop, this);
107028                 }
107029                 this.scrollToTopTask.delay(1);
107030             } else {
107031                 this.scrollToTop();
107032             }
107033         }
107034     },
107035
107036     // scroll the view to the top
107037     scrollToTop: Ext.emptyFn,
107038     
107039     /**
107040      * Get the columns used for generating a template via TableChunker.
107041      * See {@link Ext.grid.header.Container#getGridColumns}.
107042      * @private
107043      */
107044     getGridColumns: function() {
107045         return this.headerCt.getGridColumns();    
107046     },
107047     
107048     /**
107049      * Get a leaf level header by index regardless of what the nesting
107050      * structure is.
107051      * @private
107052      * @param {Number} index The index
107053      */
107054     getHeaderAtIndex: function(index) {
107055         return this.headerCt.getHeaderAtIndex(index);
107056     },
107057     
107058     /**
107059      * Get the cell (td) for a particular record and column.
107060      * @param {Ext.data.Model} record
107061      * @param {Ext.grid.column.Colunm} column
107062      * @private
107063      */
107064     getCell: function(record, column) {
107065         var row = this.getNode(record);
107066         return Ext.fly(row).down(column.getCellSelector());
107067     },
107068
107069     /**
107070      * Get a reference to a feature
107071      * @param {String} id The id of the feature
107072      * @return {Ext.grid.feature.Feature} The feature. Undefined if not found
107073      */
107074     getFeature: function(id) {
107075         var features = this.featuresMC;
107076         if (features) {
107077             return features.get(id);
107078         }
107079     },
107080
107081     /**
107082      * Initializes each feature and bind it to this view.
107083      * @private
107084      */
107085     initFeatures: function() {
107086         this.features = this.features || [];
107087         var features = this.features,
107088             ln       = features.length,
107089             i        = 0;
107090
107091         this.featuresMC = Ext.create('Ext.util.MixedCollection');
107092         for (; i < ln; i++) {
107093             // ensure feature hasnt already been instantiated
107094             if (!features[i].isFeature) {
107095                 features[i] = Ext.create('feature.'+features[i].ftype, features[i]);
107096             }
107097             // inject a reference to view
107098             features[i].view = this;
107099             this.featuresMC.add(features[i]);
107100         }
107101     },
107102
107103     /**
107104      * Gives features an injection point to attach events to the markup that
107105      * has been created for this view.
107106      * @private
107107      */
107108     attachEventsForFeatures: function() {
107109         var features = this.features,
107110             ln       = features.length,
107111             i        = 0;
107112
107113         for (; i < ln; i++) {
107114             if (features[i].isFeature) {
107115                 features[i].attachEvents();
107116             }
107117         }
107118     },
107119
107120     afterRender: function() {
107121         this.callParent();
107122         this.mon(this.el, {
107123             scroll: this.fireBodyScroll,
107124             scope: this
107125         });
107126         this.attachEventsForFeatures();
107127     },
107128
107129     fireBodyScroll: function(e, t) {
107130         this.fireEvent('bodyscroll', e, t);
107131     },
107132
107133     // TODO: Refactor headerCt dependency here to colModel
107134     /**
107135      * Uses the headerCt to transform data from dataIndex keys in a record to
107136      * headerId keys in each header and then run them through each feature to
107137      * get additional data for variables they have injected into the view template.
107138      * @private
107139      */
107140     prepareData: function(data, idx, record) {
107141         var orig     = this.headerCt.prepareData(data, idx, record, this),
107142             features = this.features,
107143             ln       = features.length,
107144             i        = 0,
107145             node, feature;
107146
107147         for (; i < ln; i++) {
107148             feature = features[i];
107149             if (feature.isFeature) {
107150                 Ext.apply(orig, feature.getAdditionalData(data, idx, record, orig, this));
107151             }
107152         }
107153
107154         return orig;
107155     },
107156
107157     // TODO: Refactor headerCt dependency here to colModel
107158     collectData: function(records, startIndex) {
107159         var preppedRecords = this.callParent(arguments),
107160             headerCt  = this.headerCt,
107161             fullWidth = headerCt.getFullWidth(),
107162             features  = this.features,
107163             ln = features.length,
107164             o = {
107165                 rows: preppedRecords,
107166                 fullWidth: fullWidth
107167             },
107168             i  = 0,
107169             feature,
107170             j = 0,
107171             jln,
107172             rowParams;
107173
107174         jln = preppedRecords.length;
107175         // process row classes, rowParams has been deprecated and has been moved
107176         // to the individual features that implement the behavior. 
107177         if (this.getRowClass) {
107178             for (; j < jln; j++) {
107179                 rowParams = {};
107180                 preppedRecords[j]['rowCls'] = this.getRowClass(records[j], j, rowParams, this.store);
107181                 if (rowParams.alt) {
107182                     Ext.Error.raise("The getRowClass alt property is no longer supported.");
107183                 }
107184                 if (rowParams.tstyle) {
107185                     Ext.Error.raise("The getRowClass tstyle property is no longer supported.");
107186                 }
107187                 if (rowParams.cells) {
107188                     Ext.Error.raise("The getRowClass cells property is no longer supported.");
107189                 }
107190                 if (rowParams.body) {
107191                     Ext.Error.raise("The getRowClass body property is no longer supported. Use the getAdditionalData method of the rowbody feature.");
107192                 }
107193                 if (rowParams.bodyStyle) {
107194                     Ext.Error.raise("The getRowClass bodyStyle property is no longer supported.");
107195                 }
107196                 if (rowParams.cols) {
107197                     Ext.Error.raise("The getRowClass cols property is no longer supported.");
107198                 }
107199             }
107200         }
107201         // currently only one feature may implement collectData. This is to modify
107202         // what's returned to the view before its rendered
107203         for (; i < ln; i++) {
107204             feature = features[i];
107205             if (feature.isFeature && feature.collectData && !feature.disabled) {
107206                 o = feature.collectData(records, preppedRecords, startIndex, fullWidth, o);
107207                 break;
107208             }
107209         }
107210         return o;
107211     },
107212
107213     // TODO: Refactor header resizing to column resizing
107214     /**
107215      * When a header is resized, setWidth on the individual columns resizer class,
107216      * the top level table, save/restore scroll state, generate a new template and
107217      * restore focus to the grid view's element so that keyboard navigation
107218      * continues to work.
107219      * @private
107220      */
107221     onHeaderResize: function(header, w, suppressFocus) {
107222         var el = this.el;
107223         if (el) {
107224             this.saveScrollState();
107225             // Grab the col and set the width, css
107226             // class is generated in TableChunker.
107227             // Select composites because there may be several chunks.
107228             el.select('.' + Ext.baseCSSPrefix + 'grid-col-resizer-'+header.id).setWidth(w);
107229             el.select('.' + Ext.baseCSSPrefix + 'grid-table-resizer').setWidth(this.headerCt.getFullWidth());
107230             this.restoreScrollState();
107231             this.setNewTemplate();
107232             if (!suppressFocus) {
107233                 this.el.focus();
107234             }
107235         }
107236     },
107237
107238     /**
107239      * When a header is shown restore its oldWidth if it was previously hidden.
107240      * @private
107241      */
107242     onHeaderShow: function(headerCt, header, suppressFocus) {
107243         // restore headers that were dynamically hidden
107244         if (header.oldWidth) {
107245             this.onHeaderResize(header, header.oldWidth, suppressFocus);
107246             delete header.oldWidth;
107247         // flexed headers will have a calculated size set
107248         // this additional check has to do with the fact that
107249         // defaults: {width: 100} will fight with a flex value
107250         } else if (header.width && !header.flex) {
107251             this.onHeaderResize(header, header.width, suppressFocus);
107252         }
107253         this.setNewTemplate();
107254     },
107255
107256     /**
107257      * When the header hides treat it as a resize to 0.
107258      * @private
107259      */
107260     onHeaderHide: function(headerCt, header, suppressFocus) {
107261         this.onHeaderResize(header, 0, suppressFocus);
107262     },
107263
107264     /**
107265      * Set a new template based on the current columns displayed in the
107266      * grid.
107267      * @private
107268      */
107269     setNewTemplate: function() {
107270         var columns = this.headerCt.getColumnsForTpl(true);
107271         this.tpl = this.getTableChunker().getTableTpl({
107272             columns: columns,
107273             features: this.features
107274         });
107275     },
107276
107277     /**
107278      * Get the configured chunker or default of Ext.view.TableChunker
107279      */
107280     getTableChunker: function() {
107281         return this.chunker || Ext.view.TableChunker;
107282     },
107283
107284     /**
107285      * Add a CSS Class to a specific row.
107286      * @param {HTMLElement/String/Number/Ext.data.Model} rowInfo An HTMLElement, index or instance of a model representing this row
107287      * @param {String} cls
107288      */
107289     addRowCls: function(rowInfo, cls) {
107290         var row = this.getNode(rowInfo);
107291         if (row) {
107292             Ext.fly(row).addCls(cls);
107293         }
107294     },
107295
107296     /**
107297      * Remove a CSS Class from a specific row.
107298      * @param {HTMLElement/String/Number/Ext.data.Model} rowInfo An HTMLElement, index or instance of a model representing this row
107299      * @param {String} cls
107300      */
107301     removeRowCls: function(rowInfo, cls) {
107302         var row = this.getNode(rowInfo);
107303         if (row) {
107304             Ext.fly(row).removeCls(cls);
107305         }
107306     },
107307
107308     // GridSelectionModel invokes onRowSelect as selection changes
107309     onRowSelect : function(rowIdx) {
107310         this.addRowCls(rowIdx, this.selectedItemCls);
107311     },
107312
107313     // GridSelectionModel invokes onRowDeselect as selection changes
107314     onRowDeselect : function(rowIdx) {
107315         this.removeRowCls(rowIdx, this.selectedItemCls);
107316         this.removeRowCls(rowIdx, this.focusedItemCls);
107317     },
107318     
107319     onCellSelect: function(position) {
107320         var cell = this.getCellByPosition(position);
107321         if (cell) {
107322             cell.addCls(this.selectedCellCls);
107323         }
107324     },
107325     
107326     onCellDeselect: function(position) {
107327         var cell = this.getCellByPosition(position);
107328         if (cell) {
107329             cell.removeCls(this.selectedCellCls);
107330         }
107331         
107332     },
107333     
107334     onCellFocus: function(position) {
107335         //var cell = this.getCellByPosition(position);
107336         this.focusCell(position);
107337     },
107338     
107339     getCellByPosition: function(position) {
107340         var row    = position.row,
107341             column = position.column,
107342             store  = this.store,
107343             node   = this.getNode(row),
107344             header = this.headerCt.getHeaderAtIndex(column),
107345             cellSelector,
107346             cell = false;
107347             
107348         if (header) {
107349             cellSelector = header.getCellSelector();
107350             cell = Ext.fly(node).down(cellSelector);
107351         }
107352         return cell;
107353     },
107354
107355     // GridSelectionModel invokes onRowFocus to 'highlight'
107356     // the last row focused
107357     onRowFocus: function(rowIdx, highlight, supressFocus) {
107358         var row = this.getNode(rowIdx);
107359
107360         if (highlight) {
107361             this.addRowCls(rowIdx, this.focusedItemCls);
107362             if (!supressFocus) {
107363                 this.focusRow(rowIdx);
107364             }
107365             //this.el.dom.setAttribute('aria-activedescendant', row.id);
107366         } else {
107367             this.removeRowCls(rowIdx, this.focusedItemCls);
107368         }
107369     },
107370
107371     /**
107372      * Focus a particular row and bring it into view. Will fire the rowfocus event.
107373      * @cfg {Mixed} An HTMLElement template node, index of a template node, the
107374      * id of a template node or the record associated with the node.
107375      */
107376     focusRow: function(rowIdx) {
107377         var row        = this.getNode(rowIdx),
107378             el         = this.el,
107379             adjustment = 0,
107380             panel      = this.ownerCt,
107381             rowRegion,
107382             elRegion,
107383             record;
107384             
107385         if (row && this.el) {
107386             elRegion  = el.getRegion();
107387             rowRegion = Ext.fly(row).getRegion();
107388             // row is above
107389             if (rowRegion.top < elRegion.top) {
107390                 adjustment = rowRegion.top - elRegion.top;
107391             // row is below
107392             } else if (rowRegion.bottom > elRegion.bottom) {
107393                 adjustment = rowRegion.bottom - elRegion.bottom;
107394             }
107395             record = this.getRecord(row);
107396             rowIdx = this.store.indexOf(record);
107397
107398             if (adjustment) {
107399                 // scroll the grid itself, so that all gridview's update.
107400                 panel.scrollByDeltaY(adjustment);
107401             }
107402             this.fireEvent('rowfocus', record, row, rowIdx);
107403         }
107404     },
107405
107406     focusCell: function(position) {
107407         var cell        = this.getCellByPosition(position),
107408             el          = this.el,
107409             adjustmentY = 0,
107410             adjustmentX = 0,
107411             elRegion    = el.getRegion(),
107412             panel       = this.ownerCt,
107413             cellRegion,
107414             record;
107415
107416         if (cell) {
107417             cellRegion = cell.getRegion();
107418             // cell is above
107419             if (cellRegion.top < elRegion.top) {
107420                 adjustmentY = cellRegion.top - elRegion.top;
107421             // cell is below
107422             } else if (cellRegion.bottom > elRegion.bottom) {
107423                 adjustmentY = cellRegion.bottom - elRegion.bottom;
107424             }
107425
107426             // cell is left
107427             if (cellRegion.left < elRegion.left) {
107428                 adjustmentX = cellRegion.left - elRegion.left;
107429             // cell is right
107430             } else if (cellRegion.right > elRegion.right) {
107431                 adjustmentX = cellRegion.right - elRegion.right;
107432             }
107433
107434             if (adjustmentY) {
107435                 // scroll the grid itself, so that all gridview's update.
107436                 panel.scrollByDeltaY(adjustmentY);
107437             }
107438             if (adjustmentX) {
107439                 panel.scrollByDeltaX(adjustmentX);
107440             }
107441             el.focus();
107442             this.fireEvent('cellfocus', record, cell, position);
107443         }
107444     },
107445
107446     /**
107447      * Scroll by delta. This affects this individual view ONLY and does not
107448      * synchronize across views or scrollers.
107449      * @param {Number} delta
107450      * @param {String} dir (optional) Valid values are scrollTop and scrollLeft. Defaults to scrollTop.
107451      * @private
107452      */
107453     scrollByDelta: function(delta, dir) {
107454         dir = dir || 'scrollTop';
107455         var elDom = this.el.dom;
107456         elDom[dir] = (elDom[dir] += delta);
107457     },
107458
107459     onUpdate: function(ds, index) {
107460         this.callParent(arguments);
107461     },
107462
107463     /**
107464      * Save the scrollState in a private variable.
107465      * Must be used in conjunction with restoreScrollState
107466      */
107467     saveScrollState: function() {
107468         var dom = this.el.dom,
107469             state = this.scrollState;
107470
107471         state.left = dom.scrollLeft;
107472         state.top = dom.scrollTop;
107473     },
107474
107475     /**
107476      * Restore the scrollState.
107477      * Must be used in conjunction with saveScrollState
107478      * @private
107479      */
107480     restoreScrollState: function() {
107481         var dom = this.el.dom,
107482             state = this.scrollState,
107483             headerEl = this.headerCt.el.dom;
107484
107485         headerEl.scrollLeft = dom.scrollLeft = state.left;
107486         dom.scrollTop = state.top;
107487     },
107488
107489     /**
107490      * Refresh the grid view.
107491      * Saves and restores the scroll state, generates a new template, stripes rows
107492      * and invalidates the scrollers.
107493      * @param {Boolean} firstPass This is a private flag for internal use only.
107494      */
107495     refresh: function(firstPass) {
107496         var me = this,
107497             table;
107498
107499         //this.saveScrollState();
107500         me.setNewTemplate();
107501         
107502         // The table.unselectable() call below adds a selectstart listener to the table element.
107503         // Before we clear the whole dataview in the callParent, we remove all the listeners from the
107504         // table. This prevents a big memory leak on IE6 and IE7.
107505         if (me.rendered) {
107506             table = me.el.child('table');
107507             if (table) {
107508                 table.removeAllListeners();
107509             }
107510         }
107511         
107512         me.callParent(arguments);
107513
107514         //this.restoreScrollState();
107515         if (me.rendered) {
107516             // Make the table view unselectable
107517             table = me.el.child('table');
107518             if (table) {
107519                 table.unselectable();
107520             }
107521             
107522             if (!firstPass) {
107523                 // give focus back to gridview
107524                 me.el.focus();
107525             }
107526         }
107527     },
107528
107529     processItemEvent: function(type, record, row, rowIndex, e) {
107530         var me = this,
107531             cell = e.getTarget(me.cellSelector, row),
107532             cellIndex = cell ? cell.cellIndex : -1,
107533             map = me.statics().EventMap,
107534             selModel = me.getSelectionModel(),
107535             result;
107536
107537         if (type == 'keydown' && !cell && selModel.getCurrentPosition) {
107538             // CellModel, otherwise we can't tell which cell to invoke
107539             cell = me.getCellByPosition(selModel.getCurrentPosition());
107540             if (cell) {
107541                 cell = cell.dom;
107542                 cellIndex = cell.cellIndex;
107543             }
107544         }
107545
107546         result = me.fireEvent('uievent', type, me, cell, rowIndex, cellIndex, e);
107547
107548         if (result === false || me.callParent(arguments) === false) {
107549             return false;
107550         }
107551
107552         // Don't handle cellmouseenter and cellmouseleave events for now
107553         if (type == 'mouseover' || type == 'mouseout') {
107554             return true;
107555         }
107556
107557         return !(
107558             // We are adding cell and feature events  
107559             (me['onBeforeCell' + map[type]](cell, cellIndex, record, row, rowIndex, e) === false) ||
107560             (me.fireEvent('beforecell' + type, me, cell, cellIndex, record, row, rowIndex, e) === false) ||
107561             (me['onCell' + map[type]](cell, cellIndex, record, row, rowIndex, e) === false) ||
107562             (me.fireEvent('cell' + type, me, cell, cellIndex, record, row, rowIndex, e) === false)
107563         );
107564     },
107565
107566     processSpecialEvent: function(e) {
107567         var me = this,
107568             map = this.statics().EventMap,
107569             features = this.features,
107570             ln = features.length,
107571             type = e.type,
107572             i, feature, prefix, featureTarget,
107573             beforeArgs, args,
107574             panel = me.ownerCt;
107575
107576         this.callParent(arguments);
107577
107578         if (type == 'mouseover' || type == 'mouseout') {
107579             return;
107580         }
107581
107582         for (i = 0; i < ln; i++) {
107583             feature = features[i];
107584             if (feature.hasFeatureEvent) {
107585                 featureTarget = e.getTarget(feature.eventSelector, me.getTargetEl());
107586                 if (featureTarget) {
107587                     prefix = feature.eventPrefix;
107588                     // allows features to implement getFireEventArgs to change the
107589                     // fireEvent signature
107590                     beforeArgs = feature.getFireEventArgs('before' + prefix + type, me, featureTarget);
107591                     args = feature.getFireEventArgs(prefix + type, me, featureTarget);
107592                     
107593                     if (
107594                         // before view event
107595                         (me.fireEvent.apply(me, beforeArgs) === false) ||
107596                         // panel grid event
107597                         (panel.fireEvent.apply(panel, beforeArgs) === false) ||
107598                         // view event
107599                         (me.fireEvent.apply(me, args) === false) ||
107600                         // panel event
107601                         (panel.fireEvent.apply(panel, args) === false)
107602                     ) {
107603                         return false;
107604                     }
107605                 }
107606             }
107607         }
107608         return true;
107609     },
107610
107611     onCellMouseDown: Ext.emptyFn,
107612     onCellMouseUp: Ext.emptyFn,
107613     onCellClick: Ext.emptyFn,
107614     onCellDblClick: Ext.emptyFn,
107615     onCellContextMenu: Ext.emptyFn,
107616     onCellKeyDown: Ext.emptyFn,
107617     onBeforeCellMouseDown: Ext.emptyFn,
107618     onBeforeCellMouseUp: Ext.emptyFn,
107619     onBeforeCellClick: Ext.emptyFn,
107620     onBeforeCellDblClick: Ext.emptyFn,
107621     onBeforeCellContextMenu: Ext.emptyFn,
107622     onBeforeCellKeyDown: Ext.emptyFn,
107623
107624     /**
107625      * Expand a particular header to fit the max content width.
107626      * This will ONLY expand, not contract.
107627      * @private
107628      */
107629     expandToFit: function(header) {
107630         var maxWidth = this.getMaxContentWidth(header);
107631         delete header.flex;
107632         header.setWidth(maxWidth);
107633     },
107634
107635     /**
107636      * Get the max contentWidth of the header's text and all cells
107637      * in the grid under this header.
107638      * @private
107639      */
107640     getMaxContentWidth: function(header) {
107641         var cellSelector = header.getCellInnerSelector(),
107642             cells        = this.el.query(cellSelector),
107643             i = 0,
107644             ln = cells.length,
107645             maxWidth = header.el.dom.scrollWidth,
107646             scrollWidth;
107647
107648         for (; i < ln; i++) {
107649             scrollWidth = cells[i].scrollWidth;
107650             if (scrollWidth > maxWidth) {
107651                 maxWidth = scrollWidth;
107652             }
107653         }
107654         return maxWidth;
107655     },
107656
107657     getPositionByEvent: function(e) {
107658         var cellNode = e.getTarget(this.cellSelector),
107659             rowNode  = e.getTarget(this.itemSelector),
107660             record   = this.getRecord(rowNode),
107661             header   = this.getHeaderByCell(cellNode);
107662
107663         return this.getPosition(record, header);
107664     },
107665
107666     getHeaderByCell: function(cell) {
107667         if (cell) {
107668             var m = cell.className.match(this.cellRe);
107669             if (m && m[1]) {
107670                 return Ext.getCmp(m[1]);
107671             }
107672         }
107673         return false;
107674     },
107675
107676     /**
107677      * @param {Object} position The current row and column: an object containing the following properties:<ul>
107678      * <li>row<div class="sub-desc"> The row <b>index</b></div></li>
107679      * <li>column<div class="sub-desc">The column <b>index</b></div></li>
107680      * </ul>
107681      * @param {String} direction 'up', 'down', 'right' and 'left'
107682      * @param {Ext.EventObject} e event
107683      * @param {Boolean} preventWrap Set to true to prevent wrap around to the next or previous row.
107684      * @param {Function} verifierFn A function to verify the validity of the calculated position. When using this function, you must return true to allow the newPosition to be returned.
107685      * @param {Scope} scope Scope to run the verifierFn in
107686      * @returns {Object} newPosition An object containing the following properties:<ul>
107687      * <li>row<div class="sub-desc"> The row <b>index</b></div></li>
107688      * <li>column<div class="sub-desc">The column <b>index</b></div></li>
107689      * </ul>
107690      * @private
107691      */
107692     walkCells: function(pos, direction, e, preventWrap, verifierFn, scope) {
107693         var row      = pos.row,
107694             column   = pos.column,
107695             rowCount = this.store.getCount(),
107696             firstCol = this.getFirstVisibleColumnIndex(),
107697             lastCol  = this.getLastVisibleColumnIndex(),
107698             newPos   = {row: row, column: column},
107699             activeHeader = this.headerCt.getHeaderAtIndex(column);
107700
107701         // no active header or its currently hidden
107702         if (!activeHeader || activeHeader.hidden) {
107703             return false;
107704         }
107705
107706         e = e || {};
107707         direction = direction.toLowerCase();
107708         switch (direction) {
107709             case 'right':
107710                 // has the potential to wrap if its last
107711                 if (column === lastCol) {
107712                     // if bottom row and last column, deny right
107713                     if (preventWrap || row === rowCount - 1) {
107714                         return false;
107715                     }
107716                     if (!e.ctrlKey) {
107717                         // otherwise wrap to nextRow and firstCol
107718                         newPos.row = row + 1;
107719                         newPos.column = firstCol;
107720                     }
107721                 // go right
107722                 } else {
107723                     if (!e.ctrlKey) {
107724                         newPos.column = column + this.getRightGap(activeHeader);
107725                     } else {
107726                         newPos.column = lastCol;
107727                     }
107728                 }
107729                 break;
107730
107731             case 'left':
107732                 // has the potential to wrap
107733                 if (column === firstCol) {
107734                     // if top row and first column, deny left
107735                     if (preventWrap || row === 0) {
107736                         return false;
107737                     }
107738                     if (!e.ctrlKey) {
107739                         // otherwise wrap to prevRow and lastCol
107740                         newPos.row = row - 1;
107741                         newPos.column = lastCol;
107742                     }
107743                 // go left
107744                 } else {
107745                     if (!e.ctrlKey) {
107746                         newPos.column = column + this.getLeftGap(activeHeader);
107747                     } else {
107748                         newPos.column = firstCol;
107749                     }
107750                 }
107751                 break;
107752
107753             case 'up':
107754                 // if top row, deny up
107755                 if (row === 0) {
107756                     return false;
107757                 // go up
107758                 } else {
107759                     if (!e.ctrlKey) {
107760                         newPos.row = row - 1;
107761                     } else {
107762                         newPos.row = 0;
107763                     }
107764                 }
107765                 break;
107766
107767             case 'down':
107768                 // if bottom row, deny down
107769                 if (row === rowCount - 1) {
107770                     return false;
107771                 // go down
107772                 } else {
107773                     if (!e.ctrlKey) {
107774                         newPos.row = row + 1;
107775                     } else {
107776                         newPos.row = rowCount - 1;
107777                     }
107778                 }
107779                 break;
107780         }
107781
107782         if (verifierFn && verifierFn.call(scope || window, newPos) !== true) {
107783             return false;
107784         } else {
107785             return newPos;
107786         }
107787     },
107788     getFirstVisibleColumnIndex: function() {
107789         var headerCt   = this.getHeaderCt(),
107790             allColumns = headerCt.getGridColumns(),
107791             visHeaders = Ext.ComponentQuery.query(':not([hidden])', allColumns),
107792             firstHeader = visHeaders[0];
107793
107794         return headerCt.getHeaderIndex(firstHeader);
107795     },
107796
107797     getLastVisibleColumnIndex: function() {
107798         var headerCt   = this.getHeaderCt(),
107799             allColumns = headerCt.getGridColumns(),
107800             visHeaders = Ext.ComponentQuery.query(':not([hidden])', allColumns),
107801             lastHeader = visHeaders[visHeaders.length - 1];
107802
107803         return headerCt.getHeaderIndex(lastHeader);
107804     },
107805
107806     getHeaderCt: function() {
107807         return this.headerCt;
107808     },
107809
107810     getPosition: function(record, header) {
107811         var me = this,
107812             store = me.store,
107813             gridCols = me.headerCt.getGridColumns();
107814
107815         return {
107816             row: store.indexOf(record),
107817             column: Ext.Array.indexOf(gridCols, header)
107818         };
107819     },
107820
107821     /**
107822      * Determines the 'gap' between the closest adjacent header to the right
107823      * that is not hidden.
107824      * @private
107825      */
107826     getRightGap: function(activeHeader) {
107827         var headerCt        = this.getHeaderCt(),
107828             headers         = headerCt.getGridColumns(),
107829             activeHeaderIdx = Ext.Array.indexOf(headers, activeHeader),
107830             i               = activeHeaderIdx + 1,
107831             nextIdx;
107832
107833         for (; i <= headers.length; i++) {
107834             if (!headers[i].hidden) {
107835                 nextIdx = i;
107836                 break;
107837             }
107838         }
107839
107840         return nextIdx - activeHeaderIdx;
107841     },
107842
107843     beforeDestroy: function() {
107844         if (this.rendered) {
107845             table = this.el.child('table');
107846             if (table) {
107847                 table.removeAllListeners();
107848             }
107849         }
107850         this.callParent(arguments);
107851     },
107852
107853     /**
107854      * Determines the 'gap' between the closest adjacent header to the left
107855      * that is not hidden.
107856      * @private
107857      */
107858     getLeftGap: function(activeHeader) {
107859         var headerCt        = this.getHeaderCt(),
107860             headers         = headerCt.getGridColumns(),
107861             activeHeaderIdx = Ext.Array.indexOf(headers, activeHeader),
107862             i               = activeHeaderIdx - 1,
107863             prevIdx;
107864
107865         for (; i >= 0; i--) {
107866             if (!headers[i].hidden) {
107867                 prevIdx = i;
107868                 break;
107869             }
107870         }
107871
107872         return prevIdx - activeHeaderIdx;
107873     }
107874 });
107875 /**
107876  * @class Ext.grid.View
107877  * @extends Ext.view.Table
107878
107879 The grid View class provides extra {@link Ext.grid.Panel} specific functionality to the
107880 {@link Ext.view.Table}. In general, this class is not instanced directly, instead a viewConfig
107881 option is passed to the grid:
107882
107883     Ext.create('Ext.grid.Panel', {
107884         // other options
107885         viewConfig: {
107886             stripeRows: false
107887         }
107888     });
107889     
107890 __Drag Drop__
107891 Drag and drop functionality can be achieved in the grid by attaching a {@link Ext.grid.plugin.DragDrop} plugin
107892 when creating the view.
107893
107894     Ext.create('Ext.grid.Panel', {
107895         // other options
107896         viewConfig: {
107897             plugins: {
107898                 ddGroup: 'people-group',
107899                 ptype: 'gridviewdragdrop',
107900                 enableDrop: false
107901             }
107902         }
107903     });
107904
107905  * @markdown
107906  */
107907 Ext.define('Ext.grid.View', {
107908     extend: 'Ext.view.Table',
107909     alias: 'widget.gridview',
107910
107911     /**
107912      * @cfg {Boolean} stripeRows <tt>true</tt> to stripe the rows. Default is <tt>false</tt>.
107913      * <p>This causes the CSS class <tt><b>x-grid-row-alt</b></tt> to be added to alternate rows of
107914      * the grid. A default CSS rule is provided which sets a background color, but you can override this
107915      * with a rule which either overrides the <b>background-color</b> style using the '!important'
107916      * modifier, or which uses a CSS selector of higher specificity.</p>
107917      */
107918     stripeRows: true,
107919     
107920     invalidateScrollerOnRefresh: true,
107921     
107922     /**
107923      * Scroll the GridView to the top by scrolling the scroller.
107924      * @private
107925      */
107926     scrollToTop : function(){
107927         if (this.rendered) {
107928             var section = this.ownerCt,
107929                 verticalScroller = section.verticalScroller;
107930                 
107931             if (verticalScroller) {
107932                 verticalScroller.scrollToTop();
107933             }
107934         }
107935     },
107936
107937     // after adding a row stripe rows from then on
107938     onAdd: function(ds, records, index) {
107939         this.callParent(arguments);
107940         this.doStripeRows(index);
107941     },
107942     
107943     // after removing a row stripe rows from then on
107944     onRemove: function(ds, records, index) {
107945         this.callParent(arguments);
107946         this.doStripeRows(index);
107947     },
107948     
107949     /**
107950      * Stripe rows from a particular row index
107951      * @param {Number} startRow
107952      * @private
107953      */
107954     doStripeRows: function(startRow) {
107955         // ensure stripeRows configuration is turned on
107956         if (this.stripeRows) {
107957             var rows   = this.getNodes(startRow),
107958                 rowsLn = rows.length,
107959                 i      = 0,
107960                 row;
107961                 
107962             for (; i < rowsLn; i++) {
107963                 row = rows[i];
107964                 // Remove prior applied row classes.
107965                 row.className = row.className.replace(this.rowClsRe, ' ');
107966                 // Every odd row will get an additional cls
107967                 if (i % 2 === 1) {
107968                     row.className += (' ' + this.altRowCls);
107969                 }
107970             }
107971         }
107972     },
107973     
107974     refresh: function(firstPass) {
107975         this.callParent(arguments);
107976         this.doStripeRows(0);
107977         // TODO: Remove gridpanel dependency
107978         var g = this.up('gridpanel');
107979         if (g && this.invalidateScrollerOnRefresh) {
107980             g.invalidateScroller();
107981         }
107982     }
107983 });
107984
107985 /**
107986  * @author Aaron Conran
107987  * @class Ext.grid.Panel
107988  * @extends Ext.panel.Table
107989  *
107990  * Grids are an excellent way of showing large amounts of tabular data on the client side. Essentially a supercharged 
107991  * `<table>`, GridPanel makes it easy to fetch, sort and filter large amounts of data.
107992  * 
107993  * Grids are composed of 2 main pieces - a {@link Ext.data.Store Store} full of data and a set of columns to render.
107994  *
107995  * {@img Ext.grid.Panel/Ext.grid.Panel1.png Ext.grid.Panel component}
107996  *
107997  * ## Basic GridPanel
107998  *
107999  *     Ext.create('Ext.data.Store', {
108000  *         storeId:'simpsonsStore',
108001  *         fields:['name', 'email', 'phone'],
108002  *         data:{'items':[
108003  *             {"name":"Lisa", "email":"lisa@simpsons.com", "phone":"555-111-1224"},
108004  *             {"name":"Bart", "email":"bart@simpsons.com", "phone":"555--222-1234"},
108005  *             {"name":"Homer", "email":"home@simpsons.com", "phone":"555-222-1244"},                        
108006  *             {"name":"Marge", "email":"marge@simpsons.com", "phone":"555-222-1254"}            
108007  *         ]},
108008  *         proxy: {
108009  *             type: 'memory',
108010  *             reader: {
108011  *                 type: 'json',
108012  *                 root: 'items'
108013  *             }
108014  *         }
108015  *     });
108016  *     
108017  *     Ext.create('Ext.grid.Panel', {
108018  *         title: 'Simpsons',
108019  *         store: Ext.data.StoreManager.lookup('simpsonsStore'),
108020  *         columns: [
108021  *             {header: 'Name',  dataIndex: 'name'},
108022  *             {header: 'Email', dataIndex: 'email', flex:1},
108023  *             {header: 'Phone', dataIndex: 'phone'}
108024  *         ],
108025  *         height: 200,
108026  *         width: 400,
108027  *         renderTo: Ext.getBody()
108028  *     });
108029  * 
108030  * The code above produces a simple grid with three columns. We specified a Store which will load JSON data inline. 
108031  * In most apps we would be placing the grid inside another container and wouldn't need to use the
108032  * {@link #height}, {@link #width} and {@link #renderTo} configurations but they are included here to make it easy to get
108033  * up and running.
108034  * 
108035  * The grid we created above will contain a header bar with a title ('Simpsons'), a row of column headers directly underneath
108036  * and finally the grid rows under the headers.
108037  * 
108038  * ## Configuring columns
108039  * 
108040  * By default, each column is sortable and will toggle between ASC and DESC sorting when you click on its header. Each
108041  * column header is also reorderable by default, and each gains a drop-down menu with options to hide and show columns.
108042  * It's easy to configure each column - here we use the same example as above and just modify the columns config:
108043  * 
108044  *     columns: [
108045  *         {
108046  *             header: 'Name',
108047  *             dataIndex: 'name',
108048  *             sortable: false,
108049  *             hideable: false,
108050  *             flex: 1
108051  *         },
108052  *         {
108053  *             header: 'Email',
108054  *             dataIndex: 'email',
108055  *             hidden: true
108056  *         },
108057  *         {
108058  *             header: 'Phone',
108059  *             dataIndex: 'phone',
108060  *             width: 100
108061  *         }
108062  *     ]
108063  * 
108064  * We turned off sorting and hiding on the 'Name' column so clicking its header now has no effect. We also made the Email
108065  * column hidden by default (it can be shown again by using the menu on any other column). We also set the Phone column to
108066  * a fixed with of 100px and flexed the Name column, which means it takes up all remaining width after the other columns 
108067  * have been accounted for. See the {@link Ext.grid.column.Column column docs} for more details.
108068  * 
108069  * ## Renderers
108070  * 
108071  * As well as customizing columns, it's easy to alter the rendering of individual cells using renderers. A renderer is 
108072  * tied to a particular column and is passed the value that would be rendered into each cell in that column. For example,
108073  * we could define a renderer function for the email column to turn each email address into a mailto link:
108074  * 
108075  *     columns: [
108076  *         {
108077  *             header: 'Email',
108078  *             dataIndex: 'email',
108079  *             renderer: function(value) {
108080  *                 return Ext.String.format('<a href="mailto:{0}">{1}</a>', value, value);
108081  *             }
108082  *         }
108083  *     ]
108084  * 
108085  * See the {@link Ext.grid.column.Column column docs} for more information on renderers.
108086  * 
108087  * ## Selection Models
108088  * 
108089  * Sometimes all you want is to render data onto the screen for viewing, but usually it's necessary to interact with or 
108090  * update that data. Grids use a concept called a Selection Model, which is simply a mechanism for selecting some part of
108091  * the data in the grid. The two main types of Selection Model are RowSelectionModel, where entire rows are selected, and
108092  * CellSelectionModel, where individual cells are selected.
108093  * 
108094  * Grids use a Row Selection Model by default, but this is easy to customise like so:
108095  * 
108096  *     Ext.create('Ext.grid.Panel', {
108097  *         selType: 'cellmodel',
108098  *         store: ...
108099  *     });
108100  * 
108101  * Specifying the `cellmodel` changes a couple of things. Firstly, clicking on a cell now
108102  * selects just that cell (using a {@link Ext.selection.RowModel rowmodel} will select the entire row), and secondly the
108103  * keyboard navigation will walk from cell to cell instead of row to row. Cell-based selection models are usually used in
108104  * conjunction with editing.
108105  * 
108106  * {@img Ext.grid.Panel/Ext.grid.Panel2.png Ext.grid.Panel cell editing}
108107  *
108108  * ## Editing
108109  * 
108110  * Grid has built-in support for in-line editing. There are two chief editing modes - cell editing and row editing. Cell
108111  * editing is easy to add to your existing column setup - here we'll just modify the example above to include an editor
108112  * on both the name and the email columns:
108113  * 
108114  *     Ext.create('Ext.grid.Panel', {
108115  *         title: 'Simpsons',
108116  *         store: Ext.data.StoreManager.lookup('simpsonsStore'),
108117  *         columns: [
108118  *             {header: 'Name',  dataIndex: 'name', field: 'textfield'},
108119  *             {header: 'Email', dataIndex: 'email', flex:1, 
108120  *                 field:{
108121  *                     xtype:'textfield',
108122  *                     allowBlank:false
108123  *                 }
108124  *             },
108125  *             {header: 'Phone', dataIndex: 'phone'}
108126  *         ],
108127  *         selType: 'cellmodel',
108128  *         plugins: [
108129  *             Ext.create('Ext.grid.plugin.CellEditing', {
108130  *                 clicksToEdit: 1
108131  *             })
108132  *         ],
108133  *         height: 200,
108134  *         width: 400,
108135  *         renderTo: Ext.getBody()
108136  *     });
108137  * 
108138  * This requires a little explanation. We're passing in {@link #store store} and {@link #columns columns} as normal, but 
108139  * this time we've also specified a {@link #field field} on two of our columns. For the Name column we just want a default
108140  * textfield to edit the value, so we specify 'textfield'. For the Email column we customized the editor slightly by 
108141  * passing allowBlank: false, which will provide inline validation.
108142  * 
108143  * To support cell editing, we also specified that the grid should use the 'cellmodel' {@link #selType}, and created an
108144  * instance of the {@link Ext.grid.plugin.CellEditing CellEditing plugin}, which we configured to activate each editor after a
108145  * single click.
108146  * 
108147  * {@img Ext.grid.Panel/Ext.grid.Panel3.png Ext.grid.Panel row editing}
108148  *
108149  * ## Row Editing
108150  * 
108151  * The other type of editing is row-based editing, using the RowEditor component. This enables you to edit an entire row
108152  * at a time, rather than editing cell by cell. Row Editing works in exactly the same way as cell editing, all we need to
108153  * do is change the plugin type to {@link Ext.grid.plugin.RowEditing}, and set the selType to 'rowmodel':
108154  * 
108155  *     Ext.create('Ext.grid.Panel', {
108156  *         title: 'Simpsons',
108157  *         store: Ext.data.StoreManager.lookup('simpsonsStore'),
108158  *         columns: [
108159  *             {header: 'Name',  dataIndex: 'name', field: 'textfield'},
108160  *             {header: 'Email', dataIndex: 'email', flex:1, 
108161  *                 field:{
108162  *                     xtype:'textfield',
108163  *                     allowBlank:false
108164  *                 }
108165  *             },
108166  *             {header: 'Phone', dataIndex: 'phone'}
108167  *         ],
108168  *         selType: 'rowmodel',
108169  *         plugins: [
108170  *             Ext.create('Ext.grid.plugin.RowEditing', {
108171  *                 clicksToEdit: 1
108172  *             })
108173  *         ],
108174  *         height: 200,
108175  *         width: 400,
108176  *         renderTo: Ext.getBody()
108177  *     });
108178  * 
108179  * Again we passed some configuration to our {@link Ext.grid.plugin.RowEditing} plugin, and now when we click each row a row
108180  * editor will appear and enable us to edit each of the columns we have specified an editor for.
108181  * 
108182  * ## Sorting & Filtering
108183  * 
108184  * Every grid is attached to a {@link Ext.data.Store Store}, which provides multi-sort and filtering capabilities. It's
108185  * easy to set up a grid to be sorted from the start:
108186  * 
108187  *     var myGrid = Ext.create('Ext.grid.Panel', {
108188  *         store: {
108189  *             fields: ['name', 'email', 'phone'],
108190  *             sorters: ['name', 'phone']
108191  *         },
108192  *         columns: [
108193  *             {text: 'Name',  dataIndex: 'name'},
108194  *             {text: 'Email', dataIndex: 'email'}
108195  *         ]
108196  *     });
108197  * 
108198  * Sorting at run time is easily accomplished by simply clicking each column header. If you need to perform sorting on 
108199  * more than one field at run time it's easy to do so by adding new sorters to the store:
108200  * 
108201  *     myGrid.store.sort([
108202  *         {property: 'name',  direction: 'ASC'},
108203  *         {property: 'email', direction: 'DESC'},
108204  *     ]);
108205  * 
108206  * {@img Ext.grid.Panel/Ext.grid.Panel4.png Ext.grid.Panel grouping}
108207  * 
108208  * ## Grouping
108209  * 
108210  * Grid supports the grouping of rows by any field. For example if we had a set of employee records, we might want to 
108211  * group by the department that each employee works in. Here's how we might set that up:
108212  * 
108213  *     var store = Ext.create('Ext.data.Store', {
108214  *         storeId:'employeeStore',
108215  *         fields:['name', 'senority', 'department'],
108216  *         groupField: 'department',
108217  *         data:{'employees':[
108218  *             {"name":"Michael Scott", "senority":7, "department":"Manangement"},
108219  *             {"name":"Dwight Schrute", "senority":2, "department":"Sales"},
108220  *             {"name":"Jim Halpert", "senority":3, "department":"Sales"},
108221  *             {"name":"Kevin Malone", "senority":4, "department":"Accounting"},
108222  *             {"name":"Angela Martin", "senority":5, "department":"Accounting"}                        
108223  *         ]},
108224  *         proxy: {
108225  *             type: 'memory',
108226  *             reader: {
108227  *                 type: 'json',
108228  *                 root: 'employees'
108229  *             }
108230  *         }
108231  *     });
108232  *     
108233  *     Ext.create('Ext.grid.Panel', {
108234  *         title: 'Employees',
108235  *         store: Ext.data.StoreManager.lookup('employeeStore'),
108236  *         columns: [
108237  *             {header: 'Name',  dataIndex: 'name'},
108238  *             {header: 'Senority', dataIndex: 'senority'}
108239  *         ],        
108240  *         features: [{ftype:'grouping'}],
108241  *         width: 200,
108242  *         height: 275,
108243  *         renderTo: Ext.getBody()
108244  *     });
108245  * 
108246  * ## Infinite Scrolling
108247  *
108248  * Grid supports infinite scrolling as an alternative to using a paging toolbar. Your users can scroll through thousands
108249  * of records without the performance penalties of renderering all the records on screen at once. The grid should be bound
108250  * to a store with a pageSize specified.
108251  *
108252  *     var grid = Ext.create('Ext.grid.Panel', {
108253  *         // Use a PagingGridScroller (this is interchangeable with a PagingToolbar)
108254  *         verticalScrollerType: 'paginggridscroller',
108255  *         // do not reset the scrollbar when the view refreshs
108256  *         invalidateScrollerOnRefresh: false,
108257  *         // infinite scrolling does not support selection
108258  *         disableSelection: true,
108259  *         // ...
108260  *     });
108261  * 
108262  * ## Paging
108263  *
108264  * Grid supports paging through large sets of data via a PagingToolbar or PagingGridScroller (see the Infinite Scrolling section above).
108265  * To leverage paging via a toolbar or scroller, you need to set a pageSize configuration on the Store.
108266  *
108267  *     var itemsPerPage = 2;   // set the number of items you want per page
108268  *     
108269  *     var store = Ext.create('Ext.data.Store', {
108270  *         id:'simpsonsStore',
108271  *         autoLoad: false,
108272  *         fields:['name', 'email', 'phone'],
108273  *         pageSize: itemsPerPage, // items per page
108274  *         proxy: {
108275  *             type: 'ajax',
108276  *             url: 'pagingstore.js',  // url that will load data with respect to start and limit params
108277  *             reader: {
108278  *                 type: 'json',
108279  *                 root: 'items',
108280  *                 totalProperty: 'total'
108281  *             }
108282  *         }
108283  *     });
108284  *     
108285  *     // specify segment of data you want to load using params
108286  *     store.load({
108287  *         params:{
108288  *             start:0,    
108289  *             limit: itemsPerPage
108290  *         }
108291  *     });
108292  *     
108293  *     Ext.create('Ext.grid.Panel', {
108294  *         title: 'Simpsons',
108295  *         store: store,
108296  *         columns: [
108297  *             {header: 'Name',  dataIndex: 'name'},
108298  *             {header: 'Email', dataIndex: 'email', flex:1},
108299  *             {header: 'Phone', dataIndex: 'phone'}
108300  *         ],
108301  *         width: 400,
108302  *         height: 125,
108303  *         dockedItems: [{
108304  *             xtype: 'pagingtoolbar',
108305  *             store: store,   // same store GridPanel is using
108306  *             dock: 'bottom',
108307  *             displayInfo: true
108308  *         }],
108309  *         renderTo: Ext.getBody()
108310  *     }); 
108311  * 
108312  * {@img Ext.grid.Panel/Ext.grid.Panel5.png Ext.grid.Panel grouping}
108313  * 
108314  * @docauthor Ed Spencer
108315  */
108316 Ext.define('Ext.grid.Panel', {
108317     extend: 'Ext.panel.Table',
108318     requires: ['Ext.grid.View'],
108319     alias: ['widget.gridpanel', 'widget.grid'],
108320     alternateClassName: ['Ext.list.ListView', 'Ext.ListView', 'Ext.grid.GridPanel'],
108321     viewType: 'gridview',
108322     
108323     lockable: false,
108324     
108325     // Required for the Lockable Mixin. These are the configurations which will be copied to the
108326     // normal and locked sub tablepanels
108327     normalCfgCopy: ['invalidateScrollerOnRefresh', 'verticalScroller', 'verticalScrollDock', 'verticalScrollerType', 'scroll'],
108328     lockedCfgCopy: ['invalidateScrollerOnRefresh'],
108329     
108330     /**
108331      * @cfg {Boolean} columnLines Adds column line styling
108332      */
108333     
108334     initComponent: function() {
108335         var me = this;
108336
108337         if (me.columnLines) {
108338             me.setColumnLines(me.columnLines);
108339         }
108340         
108341         me.callParent();
108342     },
108343     
108344     setColumnLines: function(show) {
108345         var me = this,
108346             method = (show) ? 'addClsWithUI' : 'removeClsWithUI';
108347         
108348         me[method]('with-col-lines')
108349     }
108350 });
108351 // Currently has the following issues:
108352 // - Does not handle postEditValue
108353 // - Fields without editors need to sync with their values in Store
108354 // - starting to edit another record while already editing and dirty should probably prevent it
108355 // - aggregating validation messages
108356 // - tabIndex is not managed bc we leave elements in dom, and simply move via positioning
108357 // - layout issues when changing sizes/width while hidden (layout bug)
108358
108359 /**
108360  * @class Ext.grid.RowEditor
108361  * @extends Ext.form.Panel
108362  *
108363  * Internal utility class used to provide row editing functionality. For developers, they should use
108364  * the RowEditing plugin to use this functionality with a grid.
108365  *
108366  * @ignore
108367  */
108368 Ext.define('Ext.grid.RowEditor', {
108369     extend: 'Ext.form.Panel',
108370     requires: [
108371         'Ext.tip.ToolTip',
108372         'Ext.util.HashMap',
108373         'Ext.util.KeyNav'
108374     ],
108375
108376     saveBtnText  : 'Update',
108377     cancelBtnText: 'Cancel',
108378     errorsText: 'Errors',
108379     dirtyText: 'You need to commit or cancel your changes',
108380
108381     lastScrollLeft: 0,
108382     lastScrollTop: 0,
108383
108384     border: false,
108385
108386     initComponent: function() {
108387         var me = this,
108388             form;
108389
108390         me.cls = Ext.baseCSSPrefix + 'grid-row-editor';
108391
108392         me.layout = {
108393             type: 'hbox',
108394             align: 'middle'
108395         };
108396
108397         // Maintain field-to-column mapping
108398         // It's easy to get a field from a column, but not vice versa
108399         me.columns = Ext.create('Ext.util.HashMap');
108400         me.columns.getKey = function(columnHeader) {
108401             var f;
108402             if (columnHeader.getEditor) {
108403                 f = columnHeader.getEditor();
108404                 if (f) {
108405                     return f.id;
108406                 }
108407             }
108408             return columnHeader.id;
108409         };
108410         me.mon(me.columns, {
108411             add: me.onFieldAdd,
108412             remove: me.onFieldRemove,
108413             replace: me.onFieldReplace,
108414             scope: me
108415         });
108416
108417         me.callParent(arguments);
108418
108419         if (me.fields) {
108420             me.setField(me.fields);
108421             delete me.fields;
108422         }
108423
108424         form = me.getForm();
108425         form.trackResetOnLoad = true;
108426     },
108427
108428     onFieldChange: function() {
108429         var me = this,
108430             form = me.getForm(),
108431             valid = form.isValid();
108432         if (me.errorSummary && me.isVisible()) {
108433             me[valid ? 'hideToolTip' : 'showToolTip']();
108434         }
108435         if (me.floatingButtons) {
108436             me.floatingButtons.child('#update').setDisabled(!valid);
108437         }
108438         me.isValid = valid;
108439     },
108440
108441     afterRender: function() {
108442         var me = this,
108443             plugin = me.editingPlugin;
108444
108445         me.callParent(arguments);
108446         me.mon(me.renderTo, 'scroll', me.onCtScroll, me, { buffer: 100 });
108447
108448         // Prevent from bubbling click events to the grid view
108449         me.mon(me.el, {
108450             click: Ext.emptyFn,
108451             stopPropagation: true
108452         });
108453
108454         me.el.swallowEvent([
108455             'keypress',
108456             'keydown'
108457         ]);
108458
108459         me.keyNav = Ext.create('Ext.util.KeyNav', me.el, {
108460             enter: plugin.completeEdit,
108461             esc: plugin.onEscKey,
108462             scope: plugin
108463         });
108464
108465         me.mon(plugin.view, {
108466             beforerefresh: me.onBeforeViewRefresh,
108467             refresh: me.onViewRefresh,
108468             scope: me
108469         });
108470     },
108471
108472     onBeforeViewRefresh: function(view) {
108473         var me = this,
108474             viewDom = view.el.dom;
108475
108476         if (me.el.dom.parentNode === viewDom) {
108477             viewDom.removeChild(me.el.dom);
108478         }
108479     },
108480
108481     onViewRefresh: function(view) {
108482         var me = this,
108483             viewDom = view.el.dom,
108484             context = me.context,
108485             idx;
108486
108487         viewDom.appendChild(me.el.dom);
108488
108489         // Recover our row node after a view refresh
108490         if (context && (idx = context.store.indexOf(context.record)) >= 0) {
108491             context.row = view.getNode(idx);
108492             me.reposition();
108493             if (me.tooltip && me.tooltip.isVisible()) {
108494                 me.tooltip.setTarget(context.row);
108495             }
108496         } else {
108497             me.editingPlugin.cancelEdit();
108498         }
108499     },
108500
108501     onCtScroll: function(e, target) {
108502         var me = this,
108503             scrollTop  = target.scrollTop,
108504             scrollLeft = target.scrollLeft;
108505
108506         if (scrollTop !== me.lastScrollTop) {
108507             me.lastScrollTop = scrollTop;
108508             if ((me.tooltip && me.tooltip.isVisible()) || me.hiddenTip) {
108509                 me.repositionTip();
108510             }
108511         }
108512         if (scrollLeft !== me.lastScrollLeft) {
108513             me.lastScrollLeft = scrollLeft;
108514             me.reposition();
108515         }
108516     },
108517
108518     onColumnAdd: function(column) {
108519         this.setField(column);
108520     },
108521
108522     onColumnRemove: function(column) {
108523         this.columns.remove(column);
108524     },
108525
108526     onColumnResize: function(column, width) {
108527         column.getEditor().setWidth(width - 2);
108528         if (this.isVisible()) {
108529             this.reposition();
108530         }
108531     },
108532
108533     onColumnHide: function(column) {
108534         column.getEditor().hide();
108535         if (this.isVisible()) {
108536             this.reposition();
108537         }
108538     },
108539
108540     onColumnShow: function(column) {
108541         var field = column.getEditor();
108542         field.setWidth(column.getWidth() - 2).show();
108543         if (this.isVisible()) {
108544             this.reposition();
108545         }
108546     },
108547
108548     onColumnMove: function(column, fromIdx, toIdx) {
108549         var field = column.getEditor();
108550         if (this.items.indexOf(field) != toIdx) {
108551             this.move(fromIdx, toIdx);
108552         }
108553     },
108554
108555     onFieldAdd: function(hm, fieldId, column) {
108556         var me = this,
108557             colIdx = me.editingPlugin.grid.headerCt.getHeaderIndex(column),
108558             field = column.getEditor({ xtype: 'displayfield' });
108559
108560         me.insert(colIdx, field);
108561     },
108562
108563     onFieldRemove: function(hm, fieldId, column) {
108564         var me = this,
108565             field = column.getEditor(),
108566             fieldDom = field.el.dom;
108567         me.remove(field, false);
108568         fieldDom.parentNode.removeChild(fieldDom);
108569     },
108570
108571     onFieldReplace: function(hm, fieldId, column, oldColumn) {
108572         var me = this;
108573         me.onFieldRemove(hm, fieldId, oldColumn);
108574     },
108575
108576     clearFields: function() {
108577         var me = this,
108578             hm = me.columns;
108579         hm.each(function(fieldId) {
108580             hm.removeAtKey(fieldId);
108581         });
108582     },
108583
108584     getFloatingButtons: function() {
108585         var me = this,
108586             cssPrefix = Ext.baseCSSPrefix,
108587             btnsCss = cssPrefix + 'grid-row-editor-buttons',
108588             plugin = me.editingPlugin,
108589             btns;
108590
108591         if (!me.floatingButtons) {
108592             btns = me.floatingButtons = Ext.create('Ext.Container', {
108593                 renderTpl: [
108594                     '<div class="{baseCls}-ml"></div>',
108595                     '<div class="{baseCls}-mr"></div>',
108596                     '<div class="{baseCls}-bl"></div>',
108597                     '<div class="{baseCls}-br"></div>',
108598                     '<div class="{baseCls}-bc"></div>'
108599                 ],
108600
108601                 renderTo: me.el,
108602                 baseCls: btnsCss,
108603                 layout: {
108604                     type: 'hbox',
108605                     align: 'middle'
108606                 },
108607                 defaults: {
108608                     margins: '0 1 0 1'
108609                 },
108610                 items: [{
108611                     itemId: 'update',
108612                     flex: 1,
108613                     xtype: 'button',
108614                     handler: plugin.completeEdit,
108615                     scope: plugin,
108616                     text: me.saveBtnText,
108617                     disabled: !me.isValid
108618                 }, {
108619                     flex: 1,
108620                     xtype: 'button',
108621                     handler: plugin.cancelEdit,
108622                     scope: plugin,
108623                     text: me.cancelBtnText
108624                 }]
108625             });
108626
108627             // Prevent from bubbling click events to the grid view
108628             me.mon(btns.el, {
108629                 // BrowserBug: Opera 11.01
108630                 //   causes the view to scroll when a button is focused from mousedown
108631                 mousedown: Ext.emptyFn,
108632                 click: Ext.emptyFn,
108633                 stopEvent: true
108634             });
108635         }
108636         return me.floatingButtons;
108637     },
108638
108639     reposition: function(animateConfig) {
108640         var me = this,
108641             context = me.context,
108642             row = context && Ext.get(context.row),
108643             btns = me.getFloatingButtons(),
108644             btnEl = btns.el,
108645             grid = me.editingPlugin.grid,
108646             viewEl = grid.view.el,
108647             scroller = grid.verticalScroller,
108648
108649             // always get data from ColumnModel as its what drives
108650             // the GridView's sizing
108651             mainBodyWidth = grid.headerCt.getFullWidth(),
108652             scrollerWidth = grid.getWidth(),
108653
108654             // use the minimum as the columns may not fill up the entire grid
108655             // width
108656             width = Math.min(mainBodyWidth, scrollerWidth),
108657             scrollLeft = grid.view.el.dom.scrollLeft,
108658             btnWidth = btns.getWidth(),
108659             left = (width - btnWidth) / 2 + scrollLeft,
108660             y, rowH, newHeight,
108661
108662             invalidateScroller = function() {
108663                 if (scroller) {
108664                     scroller.invalidate();
108665                     btnEl.scrollIntoView(viewEl, false);
108666                 }
108667                 if (animateConfig && animateConfig.callback) {
108668                     animateConfig.callback.call(animateConfig.scope || me);
108669                 }
108670             };
108671
108672         // need to set both top/left
108673         if (row && Ext.isElement(row.dom)) {
108674             // Bring our row into view if necessary, so a row editor that's already
108675             // visible and animated to the row will appear smooth
108676             row.scrollIntoView(viewEl, false);
108677
108678             // Get the y position of the row relative to its top-most static parent.
108679             // offsetTop will be relative to the table, and is incorrect
108680             // when mixed with certain grid features (e.g., grouping).
108681             y = row.getXY()[1] - 5;
108682             rowH = row.getHeight();
108683             newHeight = rowH + 10;
108684
108685             // IE doesn't set the height quite right.
108686             // This isn't a border-box issue, it even happens
108687             // in IE8 and IE7 quirks.
108688             // TODO: Test in IE9!
108689             if (Ext.isIE) {
108690                 newHeight += 2;
108691             }
108692
108693             // Set editor height to match the row height
108694             if (me.getHeight() != newHeight) {
108695                 me.setHeight(newHeight);
108696                 me.el.setLeft(0);
108697             }
108698
108699             if (animateConfig) {
108700                 var animObj = {
108701                     to: {
108702                         y: y
108703                     },
108704                     duration: animateConfig.duration || 125,
108705                     listeners: {
108706                         afteranimate: function() {
108707                             invalidateScroller();
108708                             y = row.getXY()[1] - 5;
108709                             me.el.setY(y);
108710                         }
108711                     }
108712                 };
108713                 me.animate(animObj);
108714             } else {
108715                 me.el.setY(y);
108716                 invalidateScroller();
108717             }
108718         }
108719         if (me.getWidth() != mainBodyWidth) {
108720             me.setWidth(mainBodyWidth);
108721         }
108722         btnEl.setLeft(left);
108723     },
108724
108725     getEditor: function(fieldInfo) {
108726         var me = this;
108727
108728         if (Ext.isNumber(fieldInfo)) {
108729             // Query only form fields. This just future-proofs us in case we add
108730             // other components to RowEditor later on.  Don't want to mess with
108731             // indices.
108732             return me.query('>[isFormField]')[fieldInfo];
108733         } else if (fieldInfo instanceof Ext.grid.column.Column) {
108734             return fieldInfo.getEditor();
108735         }
108736     },
108737
108738     removeField: function(field) {
108739         var me = this;
108740
108741         // Incase we pass a column instead, which is fine
108742         field = me.getEditor(field);
108743         me.mun(field, 'validitychange', me.onValidityChange, me);
108744
108745         // Remove field/column from our mapping, which will fire the event to
108746         // remove the field from our container
108747         me.columns.removeKey(field.id);
108748     },
108749
108750     setField: function(column) {
108751         var me = this,
108752             field;
108753
108754         if (Ext.isArray(column)) {
108755             Ext.Array.forEach(column, me.setField, me);
108756             return;
108757         }
108758
108759         // Get a default display field if necessary
108760         field = column.getEditor(null, { xtype: 'displayfield' });
108761         field.margins = '0 0 0 2';
108762         field.setWidth(column.getWidth() - 2);
108763         me.mon(field, 'change', me.onFieldChange, me);
108764
108765         // Maintain mapping of fields-to-columns
108766         // This will fire events that maintain our container items
108767         me.columns.add(field.id, column);
108768     },
108769
108770     loadRecord: function(record) {
108771         var me = this,
108772             form = me.getForm();
108773         form.loadRecord(record);
108774         if (form.isValid()) {
108775             me.hideToolTip();
108776         } else {
108777             me.showToolTip();
108778         }
108779
108780         // render display fields so they honor the column renderer/template
108781         Ext.Array.forEach(me.query('>displayfield'), function(field) {
108782             me.renderColumnData(field, record);
108783         }, me);
108784     },
108785
108786     renderColumnData: function(field, record) {
108787         var me = this,
108788             grid = me.editingPlugin.grid,
108789             headerCt = grid.headerCt,
108790             view = grid.view,
108791             store = view.store,
108792             column = me.columns.get(field.id),
108793             value = field.getRawValue();
108794
108795         // honor our column's renderer (TemplateHeader sets renderer for us!)
108796         if (column.renderer) {
108797             var metaData = { tdCls: '', style: '' },
108798                 rowIdx = store.indexOf(record),
108799                 colIdx = headerCt.getHeaderIndex(column);
108800
108801             value = column.renderer.call(
108802                 column.scope || headerCt.ownerCt,
108803                 value,
108804                 metaData,
108805                 record,
108806                 rowIdx,
108807                 colIdx,
108808                 store,
108809                 view
108810             );
108811         }
108812
108813         field.setRawValue(value);
108814         field.resetOriginalValue();
108815     },
108816
108817     beforeEdit: function() {
108818         var me = this;
108819
108820         if (me.isVisible() && !me.autoCancel && me.isDirty()) {
108821             me.showToolTip();
108822             return false;
108823         }
108824     },
108825
108826     /**
108827      * Start editing the specified grid at the specified position.
108828      * @param {Model} record The Store data record which backs the row to be edited.
108829      * @param {Model} columnHeader The Column object defining the column to be edited.
108830      */
108831     startEdit: function(record, columnHeader) {
108832         var me = this,
108833             grid = me.editingPlugin.grid,
108834             view = grid.getView(),
108835             store = grid.store,
108836             context = me.context = Ext.apply(me.editingPlugin.context, {
108837                 view: grid.getView(),
108838                 store: store
108839             });
108840
108841         // make sure our row is selected before editing
108842         context.grid.getSelectionModel().select(record);
108843
108844         // Reload the record data
108845         me.loadRecord(record);
108846
108847         if (!me.isVisible()) {
108848             me.show();
108849             me.focusContextCell();
108850         } else {
108851             me.reposition({
108852                 callback: this.focusContextCell
108853             });
108854         }
108855     },
108856
108857     // Focus the cell on start edit based upon the current context
108858     focusContextCell: function() {
108859         var field = this.getEditor(this.context.colIdx);
108860         if (field && field.focus) {
108861             field.focus();
108862         }
108863     },
108864
108865     cancelEdit: function() {
108866         var me = this,
108867             form = me.getForm();
108868
108869         me.hide();
108870         form.clearInvalid();
108871         form.reset();
108872     },
108873
108874     completeEdit: function() {
108875         var me = this,
108876             form = me.getForm();
108877
108878         if (!form.isValid()) {
108879             return;
108880         }
108881
108882         form.updateRecord(me.context.record);
108883         me.hide();
108884         return true;
108885     },
108886
108887     onShow: function() {
108888         var me = this;
108889         me.callParent(arguments);
108890         me.reposition();
108891     },
108892
108893     onHide: function() {
108894         var me = this;
108895         me.callParent(arguments);
108896         me.hideToolTip();
108897         me.invalidateScroller();
108898         if (me.context) {
108899             me.context.view.focus();
108900             me.context = null;
108901         }
108902     },
108903
108904     isDirty: function() {
108905         var me = this,
108906             form = me.getForm();
108907         return form.isDirty();
108908     },
108909
108910     getToolTip: function() {
108911         var me = this,
108912             tip;
108913
108914         if (!me.tooltip) {
108915             tip = me.tooltip = Ext.createWidget('tooltip', {
108916                 cls: Ext.baseCSSPrefix + 'grid-row-editor-errors',
108917                 title: me.errorsText,
108918                 autoHide: false,
108919                 closable: true,
108920                 closeAction: 'disable',
108921                 anchor: 'left'
108922             });
108923         }
108924         return me.tooltip;
108925     },
108926
108927     hideToolTip: function() {
108928         var me = this,
108929             tip = me.getToolTip();
108930         if (tip.rendered) {
108931             tip.disable();
108932         }
108933         me.hiddenTip = false;
108934     },
108935
108936     showToolTip: function() {
108937         var me = this,
108938             tip = me.getToolTip(),
108939             context = me.context,
108940             row = Ext.get(context.row),
108941             viewEl = context.grid.view.el;
108942
108943         tip.setTarget(row);
108944         tip.showAt([-10000, -10000]);
108945         tip.body.update(me.getErrors());
108946         tip.mouseOffset = [viewEl.getWidth() - row.getWidth() + me.lastScrollLeft + 15, 0];
108947         me.repositionTip();
108948         tip.doLayout();
108949         tip.enable();
108950     },
108951
108952     repositionTip: function() {
108953         var me = this,
108954             tip = me.getToolTip(),
108955             context = me.context,
108956             row = Ext.get(context.row),
108957             viewEl = context.grid.view.el,
108958             viewHeight = viewEl.getHeight(),
108959             viewTop = me.lastScrollTop,
108960             viewBottom = viewTop + viewHeight,
108961             rowHeight = row.getHeight(),
108962             rowTop = row.dom.offsetTop,
108963             rowBottom = rowTop + rowHeight;
108964
108965         if (rowBottom > viewTop && rowTop < viewBottom) {
108966             tip.show();
108967             me.hiddenTip = false;
108968         } else {
108969             tip.hide();
108970             me.hiddenTip = true;
108971         }
108972     },
108973
108974     getErrors: function() {
108975         var me = this,
108976             dirtyText = !me.autoCancel && me.isDirty() ? me.dirtyText + '<br />' : '',
108977             errors = [];
108978
108979         Ext.Array.forEach(me.query('>[isFormField]'), function(field) {
108980             errors = errors.concat(
108981                 Ext.Array.map(field.getErrors(), function(e) {
108982                     return '<li>' + e + '</li>';
108983                 })
108984             );
108985         }, me);
108986
108987         return dirtyText + '<ul>' + errors.join('') + '</ul>';
108988     },
108989
108990     invalidateScroller: function() {
108991         var me = this,
108992             context = me.context,
108993             scroller = context.grid.verticalScroller;
108994
108995         if (scroller) {
108996             scroller.invalidate();
108997         }
108998     }
108999 });
109000 /**
109001  * @class Ext.grid.header.Container
109002  * @extends Ext.container.Container
109003  * @private
109004  *
109005  * Container which holds headers and is docked at the top or bottom of a TablePanel.
109006  * The HeaderContainer drives resizing/moving/hiding of columns within the TableView.
109007  * As headers are hidden, moved or resized the headercontainer is responsible for
109008  * triggering changes within the view.
109009  *
109010  * @xtype headercontainer
109011  */
109012 Ext.define('Ext.grid.header.Container', {
109013     extend: 'Ext.container.Container',
109014     uses: [
109015         'Ext.grid.ColumnLayout',
109016         'Ext.grid.column.Column',
109017         'Ext.menu.Menu',
109018         'Ext.menu.CheckItem',
109019         'Ext.menu.Separator',
109020         'Ext.grid.plugin.HeaderResizer',
109021         'Ext.grid.plugin.HeaderReorderer'
109022     ],
109023     border: true,
109024
109025     alias: 'widget.headercontainer',
109026
109027     baseCls: Ext.baseCSSPrefix + 'grid-header-ct',
109028     dock: 'top',
109029
109030     /**
109031      * @cfg {Number} weight
109032      * HeaderContainer overrides the default weight of 0 for all docked items to 100.
109033      * This is so that it has more priority over things like toolbars.
109034      */
109035     weight: 100,
109036     defaultType: 'gridcolumn',
109037     /**
109038      * @cfg {Number} defaultWidth
109039      * Width of the header if no width or flex is specified. Defaults to 100.
109040      */
109041     defaultWidth: 100,
109042
109043
109044     sortAscText: 'Sort Ascending',
109045     sortDescText: 'Sort Descending',
109046     sortClearText: 'Clear Sort',
109047     columnsText: 'Columns',
109048
109049     lastHeaderCls: Ext.baseCSSPrefix + 'column-header-last',
109050     firstHeaderCls: Ext.baseCSSPrefix + 'column-header-first',
109051     headerOpenCls: Ext.baseCSSPrefix + 'column-header-open',
109052
109053     // private; will probably be removed by 4.0
109054     triStateSort: false,
109055
109056     ddLock: false,
109057
109058     dragging: false,
109059
109060     /**
109061      * <code>true</code> if this HeaderContainer is in fact a group header which contains sub headers.
109062      * @type Boolean
109063      * @property isGroupHeader
109064      */
109065
109066     /**
109067      * @cfg {Boolean} sortable
109068      * Provides the default sortable state for all Headers within this HeaderContainer.
109069      * Also turns on or off the menus in the HeaderContainer. Note that the menu is
109070      * shared across every header and therefore turning it off will remove the menu
109071      * items for every header.
109072      */
109073     sortable: true,
109074     
109075     initComponent: function() {
109076         var me = this;
109077         
109078         me.headerCounter = 0;
109079         me.plugins = me.plugins || [];
109080
109081         // TODO: Pass in configurations to turn on/off dynamic
109082         //       resizing and disable resizing all together
109083
109084         // Only set up a Resizer and Reorderer for the topmost HeaderContainer.
109085         // Nested Group Headers are themselves HeaderContainers
109086         if (!me.isHeader) {
109087             me.resizer   = Ext.create('Ext.grid.plugin.HeaderResizer');
109088             me.reorderer = Ext.create('Ext.grid.plugin.HeaderReorderer');
109089             if (!me.enableColumnResize) {
109090                 me.resizer.disable();
109091             } 
109092             if (!me.enableColumnMove) {
109093                 me.reorderer.disable();
109094             }
109095             me.plugins.push(me.reorderer, me.resizer);
109096         }
109097
109098         // Base headers do not need a box layout
109099         if (me.isHeader && !me.items) {
109100             me.layout = 'auto';
109101         }
109102         // HeaderContainer and Group header needs a gridcolumn layout.
109103         else {
109104             me.layout = {
109105                 type: 'gridcolumn',
109106                 availableSpaceOffset: me.availableSpaceOffset,
109107                 align: 'stretchmax',
109108                 resetStretch: true
109109             };
109110         }
109111         me.defaults = me.defaults || {};
109112         Ext.applyIf(me.defaults, {
109113             width: me.defaultWidth,
109114             triStateSort: me.triStateSort,
109115             sortable: me.sortable
109116         });
109117         me.callParent();
109118         me.addEvents(
109119             /**
109120              * @event columnresize
109121              * @param {Ext.grid.header.Container} ct The grid's header Container which encapsulates all column headers.
109122              * @param {Ext.grid.column.Column} column The Column header Component which provides the column definition
109123              * @param {Number} width
109124              */
109125             'columnresize',
109126
109127             /**
109128              * @event headerclick
109129              * @param {Ext.grid.header.Container} ct The grid's header Container which encapsulates all column headers.
109130              * @param {Ext.grid.column.Column} column The Column header Component which provides the column definition
109131              * @param {Ext.EventObject} e
109132              * @param {HTMLElement} t
109133              */
109134             'headerclick',
109135
109136             /**
109137              * @event headertriggerclick
109138              * @param {Ext.grid.header.Container} ct The grid's header Container which encapsulates all column headers.
109139              * @param {Ext.grid.column.Column} column The Column header Component which provides the column definition
109140              * @param {Ext.EventObject} e
109141              * @param {HTMLElement} t
109142              */
109143             'headertriggerclick',
109144
109145             /**
109146              * @event columnmove
109147              * @param {Ext.grid.header.Container} ct The grid's header Container which encapsulates all column headers.
109148              * @param {Ext.grid.column.Column} column The Column header Component which provides the column definition
109149              * @param {Number} fromIdx
109150              * @param {Number} toIdx
109151              */
109152             'columnmove',
109153             /**
109154              * @event columnhide
109155              * @param {Ext.grid.header.Container} ct The grid's header Container which encapsulates all column headers.
109156              * @param {Ext.grid.column.Column} column The Column header Component which provides the column definition
109157              */
109158             'columnhide',
109159             /**
109160              * @event columnshow
109161              * @param {Ext.grid.header.Container} ct The grid's header Container which encapsulates all column headers.
109162              * @param {Ext.grid.column.Column} column The Column header Component which provides the column definition
109163              */
109164             'columnshow',
109165             /**
109166              * @event sortchange
109167              * @param {Ext.grid.header.Container} ct The grid's header Container which encapsulates all column headers.
109168              * @param {Ext.grid.column.Column} column The Column header Component which provides the column definition
109169              * @param {String} direction
109170              */
109171             'sortchange',
109172             /**
109173              * @event menucreate
109174              * Fired immediately after the column header menu is created.
109175              * @param {Ext.grid.header.Container} ct This instance
109176              * @param {Ext.menu.Menu} menu The Menu that was created
109177              */
109178             'menucreate'
109179         );
109180     },
109181
109182     onDestroy: function() {
109183         Ext.destroy(this.resizer, this.reorderer);
109184         this.callParent();
109185     },
109186
109187     // Invalidate column cache on add
109188     // We cannot refresh the View on every add because this method is called
109189     // when the HeaderDropZone moves Headers around, that will also refresh the view
109190     onAdd: function(c) {
109191         var me = this;
109192         if (!c.headerId) {
109193             c.headerId = 'h' + (++me.headerCounter);
109194         }
109195         me.callParent(arguments);
109196         me.purgeCache();
109197     },
109198
109199     // Invalidate column cache on remove
109200     // We cannot refresh the View on every remove because this method is called
109201     // when the HeaderDropZone moves Headers around, that will also refresh the view
109202     onRemove: function(c) {
109203         var me = this;
109204         me.callParent(arguments);
109205         me.purgeCache();
109206     },
109207
109208     afterRender: function() {
109209         this.callParent();
109210         var store   = this.up('[store]').store,
109211             sorters = store.sorters,
109212             first   = sorters.first(),
109213             hd;
109214
109215         if (first) {
109216             hd = this.down('gridcolumn[dataIndex=' + first.property  +']');
109217             if (hd) {
109218                 hd.setSortState(first.direction, false, true);
109219             }
109220         }
109221     },
109222
109223     afterLayout: function() {
109224         if (!this.isHeader) {
109225             var me = this,
109226                 topHeaders = me.query('>gridcolumn:not([hidden])'),
109227                 viewEl;
109228
109229             me.callParent(arguments);
109230
109231             if (topHeaders.length) {
109232                 topHeaders[0].el.radioCls(me.firstHeaderCls);
109233                 topHeaders[topHeaders.length - 1].el.radioCls(me.lastHeaderCls);
109234             }
109235         }
109236     },
109237
109238     onHeaderShow: function(header) {
109239         // Pass up to the GridSection
109240         var me = this,
109241             gridSection = me.ownerCt,
109242             menu = me.getMenu(),
109243             topItems, topItemsVisible,
109244             colCheckItem,
109245             itemToEnable,
109246             len, i;
109247
109248         if (menu) {
109249
109250             colCheckItem = menu.down('menucheckitem[headerId=' + header.id + ']');
109251             if (colCheckItem) {
109252                 colCheckItem.setChecked(true, true);
109253             }
109254
109255             // There's more than one header visible, and we've disabled some checked items... re-enable them
109256             topItems = menu.query('#columnItem>menucheckitem[checked]');
109257             topItemsVisible = topItems.length;
109258             if ((me.getVisibleGridColumns().length > 1) && me.disabledMenuItems && me.disabledMenuItems.length) {
109259                 if (topItemsVisible == 1) {
109260                     Ext.Array.remove(me.disabledMenuItems, topItems[0]);
109261                 }
109262                 for (i = 0, len = me.disabledMenuItems.length; i < len; i++) {
109263                     itemToEnable = me.disabledMenuItems[i];
109264                     if (!itemToEnable.isDestroyed) {
109265                         itemToEnable[itemToEnable.menu ? 'enableCheckChange' : 'enable']();
109266                     }
109267                 }
109268                 if (topItemsVisible == 1) {
109269                     me.disabledMenuItems = topItems;
109270                 } else {
109271                     me.disabledMenuItems = [];
109272                 }
109273             }
109274         }
109275
109276         // Only update the grid UI when we are notified about base level Header shows;
109277         // Group header shows just cause a layout of the HeaderContainer
109278         if (!header.isGroupHeader) {
109279             if (me.view) {
109280                 me.view.onHeaderShow(me, header, true);
109281             }
109282             if (gridSection) {
109283                 gridSection.onHeaderShow(me, header);
109284             }
109285         }
109286         me.fireEvent('columnshow', me, header);
109287
109288         // The header's own hide suppresses cascading layouts, so lay the headers out now
109289         me.doLayout();
109290     },
109291
109292     onHeaderHide: function(header, suppressLayout) {
109293         // Pass up to the GridSection
109294         var me = this,
109295             gridSection = me.ownerCt,
109296             menu = me.getMenu(),
109297             colCheckItem;
109298
109299         if (menu) {
109300
109301             // If the header was hidden programmatically, sync the Menu state
109302             colCheckItem = menu.down('menucheckitem[headerId=' + header.id + ']');
109303             if (colCheckItem) {
109304                 colCheckItem.setChecked(false, true);
109305             }
109306             me.setDisabledItems();
109307         }
109308
109309         // Only update the UI when we are notified about base level Header hides;
109310         if (!header.isGroupHeader) {
109311             if (me.view) {
109312                 me.view.onHeaderHide(me, header, true);
109313             }
109314             if (gridSection) {
109315                 gridSection.onHeaderHide(me, header);
109316             }
109317
109318             // The header's own hide suppresses cascading layouts, so lay the headers out now
109319             if (!suppressLayout) {
109320                 me.doLayout();
109321             }
109322         }
109323         me.fireEvent('columnhide', me, header);
109324     },
109325
109326     setDisabledItems: function(){
109327         var me = this,
109328             menu = me.getMenu(),
109329             i = 0,
109330             len,
109331             itemsToDisable,
109332             itemToDisable;
109333
109334         // Find what to disable. If only one top level item remaining checked, we have to disable stuff.
109335         itemsToDisable = menu.query('#columnItem>menucheckitem[checked]');
109336         if ((itemsToDisable.length === 1)) {
109337             if (!me.disabledMenuItems) {
109338                 me.disabledMenuItems = [];
109339             }
109340
109341             // If down to only one column visible, also disable any descendant checkitems
109342             if ((me.getVisibleGridColumns().length === 1) && itemsToDisable[0].menu) {
109343                 itemsToDisable = itemsToDisable.concat(itemsToDisable[0].menu.query('menucheckitem[checked]'));
109344             }
109345
109346             len = itemsToDisable.length;
109347             // Disable any further unchecking at any level.
109348             for (i = 0; i < len; i++) {
109349                 itemToDisable = itemsToDisable[i];
109350                 if (!Ext.Array.contains(me.disabledMenuItems, itemToDisable)) {
109351                     itemToDisable[itemToDisable.menu ? 'disableCheckChange' : 'disable']();
109352                     me.disabledMenuItems.push(itemToDisable);
109353                 }
109354             }
109355         }
109356     },
109357
109358     /**
109359      * Temporarily lock the headerCt. This makes it so that clicking on headers
109360      * don't trigger actions like sorting or opening of the header menu. This is
109361      * done because extraneous events may be fired on the headers after interacting
109362      * with a drag drop operation.
109363      * @private
109364      */
109365     tempLock: function() {
109366         this.ddLock = true;
109367         Ext.Function.defer(function() {
109368             this.ddLock = false;
109369         }, 200, this);
109370     },
109371
109372     onHeaderResize: function(header, w, suppressFocus) {
109373         this.tempLock();
109374         if (this.view && this.view.rendered) {
109375             this.view.onHeaderResize(header, w, suppressFocus);
109376         }
109377         this.fireEvent('columnresize', this, header, w);
109378     },
109379
109380     onHeaderClick: function(header, e, t) {
109381         this.fireEvent("headerclick", this, header, e, t);
109382     },
109383
109384     onHeaderTriggerClick: function(header, e, t) {
109385         // generate and cache menu, provide ability to cancel/etc
109386         if (this.fireEvent("headertriggerclick", this, header, e, t) !== false) {
109387             this.showMenuBy(t, header);
109388         }
109389     },
109390
109391     showMenuBy: function(t, header) {
109392         var menu = this.getMenu(),
109393             ascItem  = menu.down('#ascItem'),
109394             descItem = menu.down('#descItem'),
109395             sortableMth;
109396
109397         menu.activeHeader = menu.ownerCt = header;
109398         menu.setFloatParent(header);
109399         // TODO: remove coupling to Header's titleContainer el
109400         header.titleContainer.addCls(this.headerOpenCls);
109401
109402         // enable or disable asc & desc menu items based on header being sortable
109403         sortableMth = header.sortable ? 'enable' : 'disable';
109404         if (ascItem) {
109405             ascItem[sortableMth]();
109406         }
109407         if (descItem) {
109408             descItem[sortableMth]();
109409         }
109410         menu.showBy(t);
109411     },
109412
109413     // remove the trigger open class when the menu is hidden
109414     onMenuDeactivate: function() {
109415         var menu = this.getMenu();
109416         // TODO: remove coupling to Header's titleContainer el
109417         menu.activeHeader.titleContainer.removeCls(this.headerOpenCls);
109418     },
109419
109420     moveHeader: function(fromIdx, toIdx) {
109421
109422         // An automatically expiring lock
109423         this.tempLock();
109424         this.onHeaderMoved(this.move(fromIdx, toIdx), fromIdx, toIdx);
109425     },
109426
109427     purgeCache: function() {
109428         var me = this;
109429         // Delete column cache - column order has changed.
109430         delete me.gridDataColumns;
109431
109432         // Menu changes when columns are moved. It will be recreated.
109433         if (me.menu) {
109434             me.menu.destroy();
109435             delete me.menu;
109436         }
109437     },
109438
109439     onHeaderMoved: function(header, fromIdx, toIdx) {
109440         var me = this,
109441             gridSection = me.ownerCt;
109442
109443         if (gridSection) {
109444             gridSection.onHeaderMove(me, header, fromIdx, toIdx);
109445         }
109446         me.fireEvent("columnmove", me, header, fromIdx, toIdx);
109447     },
109448
109449     /**
109450      * Gets the menu (and will create it if it doesn't already exist)
109451      * @private
109452      */
109453     getMenu: function() {
109454         var me = this;
109455
109456         if (!me.menu) {
109457             me.menu = Ext.create('Ext.menu.Menu', {
109458                 items: me.getMenuItems(),
109459                 listeners: {
109460                     deactivate: me.onMenuDeactivate,
109461                     scope: me
109462                 }
109463             });
109464             me.setDisabledItems();
109465             me.fireEvent('menucreate', me, me.menu);
109466         }
109467         return me.menu;
109468     },
109469
109470     /**
109471      * Returns an array of menu items to be placed into the shared menu
109472      * across all headers in this header container.
109473      * @returns {Array} menuItems
109474      */
109475     getMenuItems: function() {
109476         var me = this,
109477             menuItems = [{
109478                 itemId: 'columnItem',
109479                 text: me.columnsText,
109480                 cls: Ext.baseCSSPrefix + 'cols-icon',
109481                 menu: me.getColumnMenu(me)
109482             }];
109483
109484         if (me.sortable) {
109485             menuItems.unshift({
109486                 itemId: 'ascItem',
109487                 text: me.sortAscText,
109488                 cls: 'xg-hmenu-sort-asc',
109489                 handler: me.onSortAscClick,
109490                 scope: me
109491             },{
109492                 itemId: 'descItem',
109493                 text: me.sortDescText,
109494                 cls: 'xg-hmenu-sort-desc',
109495                 handler: me.onSortDescClick,
109496                 scope: me
109497             },'-');
109498         }
109499         return menuItems;
109500     },
109501
109502     // sort asc when clicking on item in menu
109503     onSortAscClick: function() {
109504         var menu = this.getMenu(),
109505             activeHeader = menu.activeHeader;
109506
109507         activeHeader.setSortState('ASC');
109508     },
109509
109510     // sort desc when clicking on item in menu
109511     onSortDescClick: function() {
109512         var menu = this.getMenu(),
109513             activeHeader = menu.activeHeader;
109514
109515         activeHeader.setSortState('DESC');
109516     },
109517
109518     /**
109519      * Returns an array of menu CheckItems corresponding to all immediate children of the passed Container which have been configured as hideable.
109520      */
109521     getColumnMenu: function(headerContainer) {
109522         var menuItems = [],
109523             i = 0,
109524             item,
109525             items = headerContainer.query('>gridcolumn[hideable]'),
109526             itemsLn = items.length,
109527             menuItem;
109528
109529         for (; i < itemsLn; i++) {
109530             item = items[i];
109531             menuItem = Ext.create('Ext.menu.CheckItem', {
109532                 text: item.text,
109533                 checked: !item.hidden,
109534                 hideOnClick: false,
109535                 headerId: item.id,
109536                 menu: item.isGroupHeader ? this.getColumnMenu(item) : undefined,
109537                 checkHandler: this.onColumnCheckChange,
109538                 scope: this
109539             });
109540             if (itemsLn === 1) {
109541                 menuItem.disabled = true;
109542             }
109543             menuItems.push(menuItem);
109544
109545             // If the header is ever destroyed - for instance by dragging out the last remaining sub header,
109546             // then the associated menu item must also be destroyed.
109547             item.on({
109548                 destroy: Ext.Function.bind(menuItem.destroy, menuItem)
109549             });
109550         }
109551         return menuItems;
109552     },
109553
109554     onColumnCheckChange: function(checkItem, checked) {
109555         var header = Ext.getCmp(checkItem.headerId);
109556         header[checked ? 'show' : 'hide']();
109557     },
109558
109559     /**
109560      * Get the columns used for generating a template via TableChunker.
109561      * Returns an array of all columns and their
109562      *  - dataIndex
109563      *  - align
109564      *  - width
109565      *  - id
109566      *  - columnId - used to create an identifying CSS class
109567      *  - cls The tdCls configuration from the Column object
109568      *  @private
109569      */
109570     getColumnsForTpl: function(flushCache) {
109571         var cols    = [],
109572             headers   = this.getGridColumns(flushCache),
109573             headersLn = headers.length,
109574             i = 0,
109575             header;
109576
109577         for (; i < headersLn; i++) {
109578             header = headers[i];
109579             cols.push({
109580                 dataIndex: header.dataIndex,
109581                 align: header.align,
109582                 width: header.hidden ? 0 : header.getDesiredWidth(),
109583                 id: header.id,
109584                 cls: header.tdCls,
109585                 columnId: header.getItemId()
109586             });
109587         }
109588         return cols;
109589     },
109590
109591     /**
109592      * Returns the number of <b>grid columns</b> descended from this HeaderContainer.
109593      * Group Columns are HeaderContainers. All grid columns are returned, including hidden ones.
109594      */
109595     getColumnCount: function() {
109596         return this.getGridColumns().length;
109597     },
109598
109599     /**
109600      * Gets the full width of all columns that are visible.
109601      */
109602     getFullWidth: function(flushCache) {
109603         var fullWidth = 0,
109604             headers     = this.getVisibleGridColumns(flushCache),
109605             headersLn   = headers.length,
109606             i         = 0;
109607
109608         for (; i < headersLn; i++) {
109609             if (!isNaN(headers[i].width)) {
109610                 // use headers getDesiredWidth if its there
109611                 if (headers[i].getDesiredWidth) {
109612                     fullWidth += headers[i].getDesiredWidth();
109613                 // if injected a diff cmp use getWidth
109614                 } else {
109615                     fullWidth += headers[i].getWidth();
109616                 }
109617             }
109618         }
109619         return fullWidth;
109620     },
109621
109622     // invoked internally by a header when not using triStateSorting
109623     clearOtherSortStates: function(activeHeader) {
109624         var headers   = this.getGridColumns(),
109625             headersLn = headers.length,
109626             i         = 0,
109627             oldSortState;
109628
109629         for (; i < headersLn; i++) {
109630             if (headers[i] !== activeHeader) {
109631                 oldSortState = headers[i].sortState;
109632                 // unset the sortstate and dont recurse
109633                 headers[i].setSortState(null, true);
109634                 //if (!silent && oldSortState !== null) {
109635                 //    this.fireEvent('sortchange', this, headers[i], null);
109636                 //}
109637             }
109638         }
109639     },
109640
109641     /**
109642      * Returns an array of the <b>visible<b> columns in the grid. This goes down to the lowest column header
109643      * level, and does not return <i>grouped</i> headers which contain sub headers.
109644      * @param {Boolean} refreshCache If omitted, the cached set of columns will be returned. Pass true to refresh the cache.
109645      * @returns {Array}
109646      */
109647     getVisibleGridColumns: function(refreshCache) {
109648         return Ext.ComponentQuery.query(':not([hidden])', this.getGridColumns(refreshCache));
109649     },
109650
109651     /**
109652      * Returns an array of all columns which map to Store fields. This goes down to the lowest column header
109653      * level, and does not return <i>grouped</i> headers which contain sub headers.
109654      * @param {Boolean} refreshCache If omitted, the cached set of columns will be returned. Pass true to refresh the cache.
109655      * @returns {Array}
109656      */
109657     getGridColumns: function(refreshCache) {
109658         var me = this,
109659             result = refreshCache ? null : me.gridDataColumns;
109660
109661         // Not already got the column cache, so collect the base columns
109662         if (!result) {
109663             me.gridDataColumns = result = [];
109664             me.cascade(function(c) {
109665                 if ((c !== me) && !c.isGroupHeader) {
109666                     result.push(c);
109667                 }
109668             });
109669         }
109670
109671         return result;
109672     },
109673
109674     /**
109675      * Get the index of a leaf level header regardless of what the nesting
109676      * structure is.
109677      */
109678     getHeaderIndex: function(header) {
109679         var columns = this.getGridColumns();
109680         return Ext.Array.indexOf(columns, header);
109681     },
109682
109683     /**
109684      * Get a leaf level header by index regardless of what the nesting
109685      * structure is.
109686      */
109687     getHeaderAtIndex: function(index) {
109688         var columns = this.getGridColumns();
109689         return columns[index];
109690     },
109691
109692     /**
109693      * Maps the record data to base it on the header id's.
109694      * This correlates to the markup/template generated by
109695      * TableChunker.
109696      */
109697     prepareData: function(data, rowIdx, record, view) {
109698         var obj       = {},
109699             headers   = this.getGridColumns(),
109700             headersLn = headers.length,
109701             colIdx    = 0,
109702             header, value,
109703             metaData,
109704             g = this.up('tablepanel'),
109705             store = g.store;
109706
109707         for (; colIdx < headersLn; colIdx++) {
109708             metaData = {
109709                 tdCls: '',
109710                 style: ''
109711             };
109712             header = headers[colIdx];
109713             value = data[header.dataIndex];
109714
109715             // When specifying a renderer as a string, it always resolves
109716             // to Ext.util.Format
109717             if (Ext.isString(header.renderer)) {
109718                 header.renderer = Ext.util.Format[header.renderer];
109719             }
109720
109721             if (Ext.isFunction(header.renderer)) {
109722                 value = header.renderer.call(
109723                     header.scope || this.ownerCt,
109724                     value,
109725                     // metadata per cell passing an obj by reference so that
109726                     // it can be manipulated inside the renderer
109727                     metaData,
109728                     record,
109729                     rowIdx,
109730                     colIdx,
109731                     store,
109732                     view
109733                 );
109734             }
109735
109736             if (metaData.css) {
109737                 // This warning attribute is used by the compat layer
109738                 obj.cssWarning = true;
109739                 metaData.tdCls = metaData.css;
109740                 delete metaData.css;
109741             }
109742             obj[header.id+'-modified'] = record.isModified(header.dataIndex) ? Ext.baseCSSPrefix + 'grid-dirty-cell' : Ext.baseCSSPrefix + 'grid-clean-cell';
109743             obj[header.id+'-tdCls'] = metaData.tdCls;
109744             obj[header.id+'-tdAttr'] = metaData.tdAttr;
109745             obj[header.id+'-style'] = metaData.style;
109746             if (value === undefined || value === null || value === '') {
109747                 value = '&#160;';
109748             }
109749             obj[header.id] = value;
109750         }
109751         return obj;
109752     },
109753
109754     expandToFit: function(header) {
109755         if (this.view) {
109756             this.view.expandToFit(header);
109757         }
109758     }
109759 });
109760
109761 /**
109762  * @class Ext.grid.column.Column
109763  * @extends Ext.grid.header.Container
109764  * 
109765  * This class specifies the definition for a column inside a {@link Ext.grid.Panel}. It encompasses
109766  * both the grid header configuration as well as displaying data within the grid itself. If the
109767  * {@link #columns} configuration is specified, this column will become a column group and can
109768  * container other columns inside. In general, this class will not be created directly, rather
109769  * an array of column configurations will be passed to the grid:
109770  * 
109771  * {@img Ext.grid.column.Column/Ext.grid.column.Column.png Ext.grid.column.Column grid column}
109772  *
109773  * ## Code
109774  *    Ext.create('Ext.data.Store', {
109775  *        storeId:'employeeStore',
109776  *        fields:['firstname', 'lastname', 'senority', 'dep', 'hired'],
109777  *        data:[
109778  *            {firstname:"Michael", lastname:"Scott", senority:7, dep:"Manangement", hired:"01/10/2004"},
109779  *            {firstname:"Dwight", lastname:"Schrute", senority:2, dep:"Sales", hired:"04/01/2004"},
109780  *            {firstname:"Jim", lastname:"Halpert", senority:3, dep:"Sales", hired:"02/22/2006"},
109781  *            {firstname:"Kevin", lastname:"Malone", senority:4, dep:"Accounting", hired:"06/10/2007"},
109782  *            {firstname:"Angela", lastname:"Martin", senority:5, dep:"Accounting", hired:"10/21/2008"}                        
109783  *        ]
109784  *    });
109785  *    
109786  *    Ext.create('Ext.grid.Panel', {
109787  *        title: 'Column Demo',
109788  *        store: Ext.data.StoreManager.lookup('employeeStore'),
109789  *        columns: [
109790  *            {text: 'First Name',  dataIndex:'firstname'},
109791  *            {text: 'Last Name',  dataIndex:'lastname'},
109792  *            {text: 'Hired Month',  dataIndex:'hired', xtype:'datecolumn', format:'M'},              
109793  *            {text: 'Deparment (Yrs)', xtype:'templatecolumn', tpl:'{dep} ({senority})'}
109794  *        ],
109795  *        width: 400,
109796  *        renderTo: Ext.getBody()
109797  *    });
109798  *     
109799  * ## Convenience Subclasses
109800  * There are several column subclasses that provide default rendering for various data types
109801  *
109802  *  - {@link Ext.grid.column.Action}: Renders icons that can respond to click events inline
109803  *  - {@link Ext.grid.column.Boolean}: Renders for boolean values 
109804  *  - {@link Ext.grid.column.Date}: Renders for date values
109805  *  - {@link Ext.grid.column.Number}: Renders for numeric values
109806  *  - {@link Ext.grid.column.Template}: Renders a value using an {@link Ext.XTemplate} using the record data 
109807  * 
109808  * ## Setting Sizes
109809  * The columns are laid out by a {@link Ext.layout.container.HBox} layout, so a column can either
109810  * be given an explicit width value or a flex configuration. If no width is specified the grid will
109811  * automatically the size the column to 100px. For column groups, the size is calculated by measuring
109812  * the width of the child columns, so a width option should not be specified in that case.
109813  * 
109814  * ## Header Options
109815  *  - {@link #text}: Sets the header text for the column
109816  *  - {@link #sortable}: Specifies whether the column can be sorted by clicking the header or using the column menu
109817  *  - {@link #hideable}: Specifies whether the column can be hidden using the column menu
109818  *  - {@link #menuDisabled}: Disables the column header menu
109819  *  - {@link #draggable}: Specifies whether the column header can be reordered by dragging
109820  *  - {@link #groupable}: Specifies whether the grid can be grouped by the column dataIndex. See also {@link Ext.grid.feature.Grouping}
109821  * 
109822  * ## Data Options
109823  *  - {@link #dataIndex}: The dataIndex is the field in the underlying {@link Ext.data.Store} to use as the value for the column.
109824  *  - {@link #renderer}: Allows the underlying store value to be transformed before being displayed in the grid
109825  * 
109826  * @xtype gridcolumn
109827  */
109828 Ext.define('Ext.grid.column.Column', {
109829     extend: 'Ext.grid.header.Container',
109830     alias: 'widget.gridcolumn',
109831     requires: ['Ext.util.KeyNav'],
109832     alternateClassName: 'Ext.grid.Column',
109833
109834     baseCls: Ext.baseCSSPrefix + 'column-header ' + Ext.baseCSSPrefix + 'unselectable',
109835
109836     // Not the standard, automatically applied overCls because we must filter out overs of child headers.
109837     hoverCls: Ext.baseCSSPrefix + 'column-header-over',
109838
109839     handleWidth: 5,
109840
109841     sortState: null,
109842
109843     possibleSortStates: ['ASC', 'DESC'],
109844
109845     renderTpl:
109846         '<div class="' + Ext.baseCSSPrefix + 'column-header-inner">' +
109847             '<span class="' + Ext.baseCSSPrefix + 'column-header-text">' +
109848                 '{text}' +
109849             '</span>' +
109850             '<tpl if="!values.menuDisabled"><div class="' + Ext.baseCSSPrefix + 'column-header-trigger"></div></tpl>' +
109851         '</div>',
109852
109853     /**
109854      * @cfg {Array} columns
109855      * <p>An optional array of sub-column definitions. This column becomes a group, and houses the columns defined in the <code>columns</code> config.</p>
109856      * <p>Group columns may not be sortable. But they may be hideable and moveable. And you may move headers into and out of a group. Note that
109857      * if all sub columns are dragged out of a group, the group is destroyed.
109858      */
109859
109860     /**
109861      * @cfg {String} dataIndex <p><b>Required</b>. The name of the field in the
109862      * grid's {@link Ext.data.Store}'s {@link Ext.data.Model} definition from
109863      * which to draw the column's value.</p>
109864      */
109865     dataIndex: null,
109866
109867     /**
109868      * @cfg {String} text Optional. The header text to be used as innerHTML
109869      * (html tags are accepted) to display in the Grid.  <b>Note</b>: to
109870      * have a clickable header with no text displayed you can use the
109871      * default of <tt>'&#160;'</tt>.
109872      */
109873     text: '&#160',
109874
109875     /**
109876      * @cfg {Boolean} sortable Optional. <tt>true</tt> if sorting is to be allowed on this column.
109877      * Whether local/remote sorting is used is specified in <code>{@link Ext.data.Store#remoteSort}</code>.
109878      */
109879     sortable: true,
109880     
109881     /**
109882      * @cfg {Boolean} groupable Optional. If the grid uses a {@link Ext.grid.feature.Grouping}, this option
109883      * may be used to disable the header menu item to group by the column selected. By default,
109884      * the header menu group option is enabled. Set to false to disable (but still show) the
109885      * group option in the header menu for the column.
109886      */
109887      
109888     /**
109889      * @cfg {Boolean} hideable Optional. Specify as <tt>false</tt> to prevent the user from hiding this column
109890      * (defaults to true).
109891      */
109892     hideable: true,
109893
109894     /**
109895      * @cfg {Boolean} menuDisabled
109896      * True to disabled the column header menu containing sort/hide options. Defaults to false.
109897      */
109898     menuDisabled: false,
109899
109900     /**
109901      * @cfg {Function} renderer
109902      * <p>A renderer is an 'interceptor' method which can be used transform data (value, appearance, etc.) before it
109903      * is rendered. Example:</p>
109904      * <pre><code>{
109905     renderer: function(value){
109906         if (value === 1) {
109907             return '1 person';
109908         }
109909         return value + ' people';
109910     }
109911 }
109912      * </code></pre>
109913      * @param {Mixed} value The data value for the current cell
109914      * @param {Object} metaData A collection of metadata about the current cell; can be used or modified by
109915      * the renderer. Recognized properties are: <tt>tdCls</tt>, <tt>tdAttr</tt>, and <tt>style</tt>.
109916      * @param {Ext.data.Model} record The record for the current row
109917      * @param {Number} rowIndex The index of the current row
109918      * @param {Number} colIndex The index of the current column
109919      * @param {Ext.data.Store} store The data store
109920      * @param {Ext.view.View} view The current view
109921      * @return {String} The HTML to be rendered
109922      */
109923     renderer: false,
109924
109925     /**
109926      * @cfg {String} align Sets the alignment of the header and rendered columns.
109927      * Defaults to 'left'.
109928      */
109929     align: 'left',
109930
109931     /**
109932      * @cfg {Boolean} draggable Indicates whether or not the header can be drag and drop re-ordered.
109933      * Defaults to true.
109934      */
109935     draggable: true,
109936
109937     // Header does not use the typical ComponentDraggable class and therefore we
109938     // override this with an emptyFn. It is controlled at the HeaderDragZone.
109939     initDraggable: Ext.emptyFn,
109940
109941     /**
109942      * @cfg {String} tdCls <p>Optional. A CSS class names to apply to the table cells for this column.</p>
109943      */
109944
109945     /**
109946      * @property {Ext.core.Element} triggerEl
109947      */
109948
109949     /**
109950      * @property {Ext.core.Element} textEl
109951      */
109952
109953     /**
109954      * @private
109955      * Set in this class to identify, at runtime, instances which are not instances of the
109956      * HeaderContainer base class, but are in fact, the subclass: Header.
109957      */
109958     isHeader: true,
109959
109960     initComponent: function() {
109961         var me = this,
109962             i,
109963             len;
109964         
109965         if (Ext.isDefined(me.header)) {
109966             me.text = me.header;
109967             delete me.header;
109968         }
109969
109970         // Flexed Headers need to have a minWidth defined so that they can never be squeezed out of existence by the
109971         // HeaderContainer's specialized Box layout, the ColumnLayout. The ColumnLayout's overridden calculateChildboxes
109972         // method extends the available layout space to accommodate the "desiredWidth" of all the columns.
109973         if (me.flex) {
109974             me.minWidth = me.minWidth || Ext.grid.plugin.HeaderResizer.prototype.minColWidth;
109975         }
109976         // Non-flexed Headers may never be squeezed in the event of a shortfall so
109977         // always set their minWidth to their current width.
109978         else {
109979             me.minWidth = me.width;
109980         }
109981
109982         if (!me.triStateSort) {
109983             me.possibleSortStates.length = 2;
109984         }
109985
109986         // A group header; It contains items which are themselves Headers
109987         if (Ext.isDefined(me.columns)) {
109988             me.isGroupHeader = true;
109989
109990             if (me.dataIndex) {
109991                 Ext.Error.raise('Ext.grid.column.Column: Group header may not accept a dataIndex');
109992             }
109993             if ((me.width && me.width !== Ext.grid.header.Container.prototype.defaultWidth) || me.flex) {
109994                 Ext.Error.raise('Ext.grid.column.Column: Group header does not support setting explicit widths or flexs. The group header width is calculated by the sum of its children.');
109995             }
109996
109997             // The headers become child items
109998             me.items = me.columns;
109999             delete me.columns;
110000             delete me.flex;
110001             me.width = 0;
110002
110003             // Acquire initial width from sub headers
110004             for (i = 0, len = me.items.length; i < len; i++) {
110005                 me.width += me.items[i].width || Ext.grid.header.Container.prototype.defaultWidth;
110006                 if (me.items[i].flex) {
110007                     Ext.Error.raise('Ext.grid.column.Column: items of a grouped header do not support flexed values. Each item must explicitly define its width.');
110008                 }
110009             }
110010             me.minWidth = me.width;
110011
110012             me.cls = (me.cls||'') + ' ' + Ext.baseCSSPrefix + 'group-header';
110013             me.sortable = false;
110014             me.fixed = true;
110015             me.align = 'center';
110016         }
110017
110018         Ext.applyIf(me.renderSelectors, {
110019             titleContainer: '.' + Ext.baseCSSPrefix + 'column-header-inner',
110020             triggerEl: '.' + Ext.baseCSSPrefix + 'column-header-trigger',
110021             textEl: '.' + Ext.baseCSSPrefix + 'column-header-text'
110022         });
110023
110024         // Initialize as a HeaderContainer
110025         me.callParent(arguments);
110026     },
110027
110028     onAdd: function(childHeader) {
110029         childHeader.isSubHeader = true;
110030         childHeader.addCls(Ext.baseCSSPrefix + 'group-sub-header');
110031     },
110032
110033     onRemove: function(childHeader) {
110034         childHeader.isSubHeader = false;
110035         childHeader.removeCls(Ext.baseCSSPrefix + 'group-sub-header');
110036     },
110037
110038     initRenderData: function() {
110039         var me = this;
110040         
110041         Ext.applyIf(me.renderData, {
110042             text: me.text,
110043             menuDisabled: me.menuDisabled
110044         });
110045         return me.callParent(arguments);
110046     },
110047
110048     // note that this should invalidate the menu cache
110049     setText: function(text) {
110050         this.text = text;
110051         if (this.rendered) {
110052             this.textEl.update(text);
110053         } 
110054     },
110055
110056     // Find the topmost HeaderContainer: An ancestor which is NOT a Header.
110057     // Group Headers are themselves HeaderContainers
110058     getOwnerHeaderCt: function() {
110059         return this.up(':not([isHeader])');
110060     },
110061
110062     /**
110063      * Returns the true grid column index assiciated with this Column only if this column is a base level Column.
110064      * If it is a group column, it returns <code>false</code>
110065      */
110066     getIndex: function() {
110067         return this.isGroupColumn ? false : this.getOwnerHeaderCt().getHeaderIndex(this);
110068     },
110069
110070     afterRender: function() {
110071         var me = this,
110072             el = me.el;
110073
110074         me.callParent(arguments);
110075
110076         el.addCls(Ext.baseCSSPrefix + 'column-header-align-' + me.align).addClsOnOver(me.overCls);
110077
110078         me.mon(el, {
110079             click:     me.onElClick,
110080             dblclick:  me.onElDblClick,
110081             scope:     me
110082         });
110083         
110084         // BrowserBug: Ie8 Strict Mode, this will break the focus for this browser,
110085         // must be fixed when focus management will be implemented.
110086         if (!Ext.isIE8 || !Ext.isStrict) {
110087             me.mon(me.getFocusEl(), {
110088                 focus: me.onTitleMouseOver,
110089                 blur: me.onTitleMouseOut,
110090                 scope: me
110091             });
110092         }
110093
110094         me.mon(me.titleContainer, {
110095             mouseenter:  me.onTitleMouseOver,
110096             mouseleave:  me.onTitleMouseOut,
110097             scope:      me
110098         });
110099
110100         me.keyNav = Ext.create('Ext.util.KeyNav', el, {
110101             enter: me.onEnterKey,
110102             down: me.onDownKey,
110103             scope: me
110104         });
110105     },
110106
110107     setSize: function(width, height) {
110108         var me = this,
110109             headerCt = me.ownerCt,
110110             ownerHeaderCt = me.getOwnerHeaderCt(),
110111             siblings,
110112             len, i,
110113             oldWidth = me.getWidth(),
110114             newWidth = 0;
110115
110116         if (width !== oldWidth) {
110117
110118             // Bubble size changes upwards to group headers
110119             if (headerCt.isGroupHeader) {
110120
110121                 siblings = headerCt.items.items;
110122                 len = siblings.length;
110123
110124                 // Size the owning group to the size of its sub headers 
110125                 if (siblings[len - 1].rendered) {
110126
110127                     for (i = 0; i < len; i++) {
110128                         newWidth += (siblings[i] === me) ? width : siblings[i].getWidth();
110129                     }
110130                     headerCt.minWidth = newWidth;
110131                     headerCt.setWidth(newWidth);
110132                 }
110133             }
110134             me.callParent(arguments);
110135         }
110136     },
110137
110138     afterComponentLayout: function(width, height) {
110139         var me = this,
110140             ownerHeaderCt = this.getOwnerHeaderCt();
110141
110142         me.callParent(arguments);
110143
110144         // Only changes at the base level inform the grid's HeaderContainer which will update the View
110145         // Skip this if the width is null or undefined which will be the Box layout's initial pass  through the child Components
110146         // Skip this if it's the initial size setting in which case there is no ownerheaderCt yet - that is set afterRender
110147         if (width && !me.isGroupHeader && ownerHeaderCt) {
110148             ownerHeaderCt.onHeaderResize(me, width, true);
110149         }
110150     },
110151
110152     // private
110153     // After the container has laid out and stretched, it calls this to correctly pad the inner to center the text vertically
110154     setPadding: function() {
110155         var me = this,
110156             headerHeight,
110157             lineHeight = parseInt(me.textEl.getStyle('line-height'), 10);
110158
110159         // Top title containing element must stretch to match height of sibling group headers
110160         if (!me.isGroupHeader) {
110161             headerHeight = me.el.getViewSize().height;
110162             if (me.titleContainer.getHeight() < headerHeight) {
110163                 me.titleContainer.dom.style.height = headerHeight + 'px';
110164             }
110165         }
110166         headerHeight = me.titleContainer.getViewSize().height;
110167
110168         // Vertically center the header text in potentially vertically stretched header
110169         if (lineHeight) {
110170             me.titleContainer.setStyle({
110171                 paddingTop: Math.max(((headerHeight - lineHeight) / 2), 0) + 'px'
110172             });
110173         }
110174
110175         // Only IE needs this
110176         if (Ext.isIE && me.triggerEl) {
110177             me.triggerEl.setHeight(headerHeight);
110178         }
110179     },
110180
110181     onDestroy: function() {
110182         var me = this;
110183         Ext.destroy(me.keyNav);
110184         delete me.keyNav;
110185         me.callParent(arguments);
110186     },
110187
110188     onTitleMouseOver: function() {
110189         this.titleContainer.addCls(this.hoverCls);
110190     },
110191
110192     onTitleMouseOut: function() {
110193         this.titleContainer.removeCls(this.hoverCls);
110194     },
110195
110196     onDownKey: function(e) {
110197         if (this.triggerEl) {
110198             this.onElClick(e, this.triggerEl.dom || this.el.dom);
110199         }
110200     },
110201
110202     onEnterKey: function(e) {
110203         this.onElClick(e, this.el.dom);
110204     },
110205
110206     /**
110207      * @private
110208      * Double click 
110209      * @param e
110210      * @param t
110211      */
110212     onElDblClick: function(e, t) {
110213         var me = this,
110214             ownerCt = me.ownerCt;
110215         if (ownerCt && Ext.Array.indexOf(ownerCt.items, me) !== 0 && me.isOnLeftEdge(e) ) {
110216             ownerCt.expandToFit(me.previousSibling('gridcolumn'));
110217         }
110218     },
110219
110220     onElClick: function(e, t) {
110221
110222         // The grid's docked HeaderContainer.
110223         var me = this,
110224             ownerHeaderCt = me.getOwnerHeaderCt();
110225
110226         if (ownerHeaderCt && !ownerHeaderCt.ddLock) {
110227             // Firefox doesn't check the current target in a within check.
110228             // Therefore we check the target directly and then within (ancestors)
110229             if (me.triggerEl && (e.target === me.triggerEl.dom || t === me.triggerEl.dom || e.within(me.triggerEl))) {
110230                 ownerHeaderCt.onHeaderTriggerClick(me, e, t);
110231             // if its not on the left hand edge, sort
110232             } else if (e.getKey() || (!me.isOnLeftEdge(e) && !me.isOnRightEdge(e))) {
110233                 me.toggleSortState();
110234                 ownerHeaderCt.onHeaderClick(me, e, t);
110235             }
110236         }
110237     },
110238
110239     /**
110240      * @private
110241      * Process UI events from the view. The owning TablePanel calls this method, relaying events from the TableView
110242      * @param {String} type Event type, eg 'click'
110243      * @param {TableView} view TableView Component
110244      * @param {HtmlElement} cell Cell HtmlElement the event took place within
110245      * @param {Number} recordIndex Index of the associated Store Model (-1 if none)
110246      * @param {Number} cellIndex Cell index within the row
110247      * @param {EventObject} e Original event
110248      */
110249     processEvent: function(type, view, cell, recordIndex, cellIndex, e) {
110250         return this.fireEvent.apply(this, arguments);
110251     },
110252
110253     toggleSortState: function() {
110254         var me = this,
110255             idx,
110256             nextIdx;
110257             
110258         if (me.sortable) {
110259             idx = Ext.Array.indexOf(me.possibleSortStates, me.sortState);
110260
110261             nextIdx = (idx + 1) % me.possibleSortStates.length;
110262             me.setSortState(me.possibleSortStates[nextIdx]);
110263         }
110264     },
110265
110266     doSort: function(state) {
110267         var ds = this.up('tablepanel').store;
110268         ds.sort({
110269             property: this.getSortParam(),
110270             direction: state
110271         });
110272     },
110273
110274     /**
110275      * Returns the parameter to sort upon when sorting this header. By default
110276      * this returns the dataIndex and will not need to be overriden in most cases.
110277      */
110278     getSortParam: function() {
110279         return this.dataIndex;
110280     },
110281
110282     //setSortState: function(state, updateUI) {
110283     //setSortState: function(state, doSort) {
110284     setSortState: function(state, skipClear, initial) {
110285         var me = this,
110286             colSortClsPrefix = Ext.baseCSSPrefix + 'column-header-sort-',
110287             ascCls = colSortClsPrefix + 'ASC',
110288             descCls = colSortClsPrefix + 'DESC',
110289             nullCls = colSortClsPrefix + 'null',
110290             ownerHeaderCt = me.getOwnerHeaderCt(),
110291             oldSortState = me.sortState;
110292
110293         if (oldSortState !== state && me.getSortParam()) {
110294             me.addCls(colSortClsPrefix + state);
110295             // don't trigger a sort on the first time, we just want to update the UI
110296             if (state && !initial) {
110297                 me.doSort(state);
110298             }
110299             switch (state) {
110300                 case 'DESC':
110301                     me.removeCls([ascCls, nullCls]);
110302                     break;
110303                 case 'ASC':
110304                     me.removeCls([descCls, nullCls]);
110305                     break;
110306                 case null:
110307                     me.removeCls([ascCls, descCls]);
110308                     break;
110309             }
110310             if (ownerHeaderCt && !me.triStateSort && !skipClear) {
110311                 ownerHeaderCt.clearOtherSortStates(me);
110312             }
110313             me.sortState = state;
110314             ownerHeaderCt.fireEvent('sortchange', ownerHeaderCt, me, state);
110315         }
110316     },
110317
110318     hide: function() {
110319         var me = this,
110320             items,
110321             len, i,
110322             lb,
110323             newWidth = 0,
110324             ownerHeaderCt = me.getOwnerHeaderCt();
110325
110326         // Hiding means setting to zero width, so cache the width
110327         me.oldWidth = me.getWidth();
110328
110329         // Hiding a group header hides itself, and then informs the HeaderContainer about its sub headers (Suppressing header layout)
110330         if (me.isGroupHeader) {
110331             items = me.items.items;
110332             me.callParent(arguments);
110333             ownerHeaderCt.onHeaderHide(me);
110334             for (i = 0, len = items.length; i < len; i++) {
110335                 items[i].hidden = true;
110336                 ownerHeaderCt.onHeaderHide(items[i], true);
110337             }
110338             return;
110339         }
110340
110341         // TODO: Work with Jamie to produce a scheme where we can show/hide/resize without triggering a layout cascade
110342         lb = me.ownerCt.componentLayout.layoutBusy;
110343         me.ownerCt.componentLayout.layoutBusy = true;
110344         me.callParent(arguments);
110345         me.ownerCt.componentLayout.layoutBusy = lb;
110346
110347         // Notify owning HeaderContainer
110348         ownerHeaderCt.onHeaderHide(me);
110349
110350         if (me.ownerCt.isGroupHeader) {
110351             // If we've just hidden the last header in a group, then hide the group
110352             items = me.ownerCt.query('>:not([hidden])');
110353             if (!items.length) {
110354                 me.ownerCt.hide();
110355             }
110356             // Size the group down to accommodate fewer sub headers
110357             else {
110358                 for (i = 0, len = items.length; i < len; i++) {
110359                     newWidth += items[i].getWidth();
110360                 }
110361                 me.ownerCt.minWidth = newWidth;
110362                 me.ownerCt.setWidth(newWidth);
110363             }
110364         }
110365     },
110366
110367     show: function() {
110368         var me = this,
110369             ownerCt = me.getOwnerHeaderCt(),
110370             lb,
110371             items,
110372             len, i,
110373             newWidth = 0;
110374
110375         // TODO: Work with Jamie to produce a scheme where we can show/hide/resize without triggering a layout cascade
110376         lb = me.ownerCt.componentLayout.layoutBusy;
110377         me.ownerCt.componentLayout.layoutBusy = true;
110378         me.callParent(arguments);
110379         me.ownerCt.componentLayout.layoutBusy = lb;
110380
110381         // If a sub header, ensure that the group header is visible
110382         if (me.isSubHeader) {
110383             if (!me.ownerCt.isVisible()) {
110384                 me.ownerCt.show();
110385             }
110386         }
110387
110388         // If we've just shown a group with all its sub headers hidden, then show all its sub headers
110389         if (me.isGroupHeader && !me.query(':not([hidden])').length) {
110390             items = me.query('>*');
110391             for (i = 0, len = items.length; i < len; i++) {
110392                 items[i].show();
110393             }
110394         }
110395
110396         // Resize the owning group to accommodate
110397         if (me.ownerCt.isGroupHeader) {
110398             items = me.ownerCt.query('>:not([hidden])');
110399             for (i = 0, len = items.length; i < len; i++) {
110400                 newWidth += items[i].getWidth();
110401             }
110402             me.ownerCt.minWidth = newWidth;
110403             me.ownerCt.setWidth(newWidth);
110404         }
110405
110406         // Notify owning HeaderContainer
110407         if (ownerCt) {
110408             ownerCt.onHeaderShow(me);
110409         }
110410     },
110411
110412     getDesiredWidth: function() {
110413         var me = this;
110414         if (me.rendered && me.componentLayout && me.componentLayout.lastComponentSize) {
110415             // headers always have either a width or a flex
110416             // because HeaderContainer sets a defaults width
110417             // therefore we can ignore the natural width
110418             // we use the componentLayout's tracked width so that
110419             // we can calculate the desired width when rendered
110420             // but not visible because its being obscured by a layout
110421             return me.componentLayout.lastComponentSize.width;
110422         // Flexed but yet to be rendered this could be the case
110423         // where a HeaderContainer and Headers are simply used as data
110424         // structures and not rendered.
110425         }
110426         else if (me.flex) {
110427             // this is going to be wrong, the defaultWidth
110428             return me.width;
110429         }
110430         else {
110431             return me.width;
110432         }
110433     },
110434
110435     getCellSelector: function() {
110436         return '.' + Ext.baseCSSPrefix + 'grid-cell-' + this.getItemId();
110437     },
110438
110439     getCellInnerSelector: function() {
110440         return this.getCellSelector() + ' .' + Ext.baseCSSPrefix + 'grid-cell-inner';
110441     },
110442
110443     isOnLeftEdge: function(e) {
110444         return (e.getXY()[0] - this.el.getLeft() <= this.handleWidth);
110445     },
110446
110447     isOnRightEdge: function(e) {
110448         return (this.el.getRight() - e.getXY()[0] <= this.handleWidth);
110449     }
110450     
110451     /**
110452      * Retrieves the editing field for editing associated with this header. Returns false if there
110453      * is no field associated with the Header the method will return false. If the
110454      * field has not been instantiated it will be created. Note: These methods only has an implementation
110455      * if a Editing plugin has been enabled on the grid.
110456      * @param record The {@link Ext.data.Model Model} instance being edited.
110457      * @param {Mixed} defaultField An object representing a default field to be created
110458      * @returns {Ext.form.field.Field} field
110459      * @method getEditor
110460      */
110461     // intentionally omit getEditor and setEditor definitions bc we applyIf into columns
110462     // when the editing plugin is injected
110463     
110464     
110465     /**
110466      * Sets the form field to be used for editing. Note: This method only has an implementation
110467      * if an Editing plugin has been enabled on the grid.
110468      * @param {Mixed} field An object representing a field to be created. If no xtype is specified a 'textfield' is assumed.
110469      * @method setEditor
110470      */
110471 });
110472 /**
110473  * @class Ext.grid.RowNumberer
110474  * @extends Ext.grid.column.Column
110475  * This is a utility class that can be passed into a {@link Ext.grid.column.Column} as a column config that provides
110476  * an automatic row numbering column.
110477  * <br>Usage:<br><pre><code>
110478 columns: [
110479     Ext.create('Ext.grid.RowNumberer'),
110480     {text: "Company", flex: 1, sortable: true, dataIndex: 'company'},
110481     {text: "Price", width: 120, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'},
110482     {text: "Change", width: 120, sortable: true, dataIndex: 'change'},
110483     {text: "% Change", width: 120, sortable: true, dataIndex: 'pctChange'},
110484     {text: "Last Updated", width: 120, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
110485 ]
110486  *</code></pre>
110487  * @constructor
110488  * @param {Object} config The configuration options
110489  */
110490 Ext.define('Ext.grid.RowNumberer', {
110491     extend: 'Ext.grid.column.Column',
110492     alias: 'widget.rownumberer',
110493     /**
110494      * @cfg {String} text Any valid text or HTML fragment to display in the header cell for the row
110495      * number column (defaults to '&#160').
110496      */
110497     text: "&#160",
110498
110499     /**
110500      * @cfg {Number} width The default width in pixels of the row number column (defaults to 23).
110501      */
110502     width: 23,
110503
110504     /**
110505      * @cfg {Boolean} sortable True if the row number column is sortable (defaults to false).
110506      * @hide
110507      */
110508     sortable: false,
110509
110510     align: 'right',
110511
110512     constructor : function(config){
110513         this.callParent(arguments);
110514         if (this.rowspan) {
110515             this.renderer = Ext.Function.bind(this.renderer, this);
110516         }
110517     },
110518
110519     // private
110520     fixed: true,
110521     hideable: false,
110522     menuDisabled: true,
110523     dataIndex: '',
110524     cls: Ext.baseCSSPrefix + 'row-numberer',
110525     rowspan: undefined,
110526
110527     // private
110528     renderer: function(value, metaData, record, rowIdx, colIdx, store) {
110529         if (this.rowspan){
110530             metaData.cellAttr = 'rowspan="'+this.rowspan+'"';
110531         }
110532
110533         metaData.tdCls = Ext.baseCSSPrefix + 'grid-cell-special';
110534         return store.indexOfTotal(record) + 1;
110535     }
110536 });
110537
110538 /**
110539  * @class Ext.view.DropZone
110540  * @extends Ext.dd.DropZone
110541  * @private
110542  */
110543 Ext.define('Ext.view.DropZone', {
110544     extend: 'Ext.dd.DropZone',
110545
110546     indicatorHtml: '<div class="x-grid-drop-indicator-left"></div><div class="x-grid-drop-indicator-right"></div>',
110547     indicatorCls: 'x-grid-drop-indicator',
110548
110549     constructor: function(config) {
110550         var me = this;
110551         Ext.apply(me, config);
110552
110553         // Create a ddGroup unless one has been configured.
110554         // User configuration of ddGroups allows users to specify which
110555         // DD instances can interact with each other. Using one
110556         // based on the id of the View would isolate it and mean it can only
110557         // interact with a DragZone on the same View also using a generated ID.
110558         if (!me.ddGroup) {
110559             me.ddGroup = 'view-dd-zone-' + me.view.id;
110560         }
110561
110562         // The DropZone's encapsulating element is the View's main element. It must be this because drop gestures
110563         // may require scrolling on hover near a scrolling boundary. In Ext 4.x two DD instances may not use the
110564         // same element, so a DragZone on this same View must use the View's parent element as its element.
110565         me.callParent([me.view.el]);
110566     },
110567
110568 //  Fire an event through the client DataView. Lock this DropZone during the event processing so that
110569 //  its data does not become corrupted by processing mouse events.
110570     fireViewEvent: function() {
110571         this.lock();
110572         var result = this.view.fireEvent.apply(this.view, arguments);
110573         this.unlock();
110574         return result;
110575     },
110576
110577     getTargetFromEvent : function(e) {
110578         var node = e.getTarget(this.view.getItemSelector()),
110579             mouseY, nodeList, testNode, i, len, box;
110580
110581 //      Not over a row node: The content may be narrower than the View's encapsulating element, so return the closest.
110582 //      If we fall through because the mouse is below the nodes (or there are no nodes), we'll get an onContainerOver call.
110583         if (!node) {
110584             mouseY = e.getPageY();
110585             for (i = 0, nodeList = this.view.getNodes(), len = nodeList.length; i < len; i++) {
110586                 testNode = nodeList[i];
110587                 box = Ext.fly(testNode).getBox();
110588                 if (mouseY <= box.bottom) {
110589                     return testNode;
110590                 }
110591             }
110592         }
110593         return node;
110594     },
110595
110596     getIndicator: function() {
110597         var me = this;
110598
110599         if (!me.indicator) {
110600             me.indicator = Ext.createWidget('component', {
110601                 html: me.indicatorHtml,
110602                 cls: me.indicatorCls,
110603                 ownerCt: me.view,
110604                 floating: true,
110605                 shadow: false
110606             });
110607         }
110608         return me.indicator;
110609     },
110610
110611     getPosition: function(e, node) {
110612         var y      = e.getXY()[1],
110613             region = Ext.fly(node).getRegion(),
110614             pos;
110615
110616         if ((region.bottom - y) >= (region.bottom - region.top) / 2) {
110617             pos = "before";
110618         } else {
110619             pos = "after";
110620         }
110621         return pos;
110622     },
110623
110624     /**
110625      * @private Determines whether the record at the specified offset from the passed record
110626      * is in the drag payload.
110627      * @param records
110628      * @param record
110629      * @param offset
110630      * @returns {Boolean} True if the targeted record is in the drag payload
110631      */
110632     containsRecordAtOffset: function(records, record, offset) {
110633         if (!record) {
110634             return false;
110635         }
110636         var view = this.view,
110637             recordIndex = view.indexOf(record),
110638             nodeBefore = view.getNode(recordIndex + offset),
110639             recordBefore = nodeBefore ? view.getRecord(nodeBefore) : null;
110640
110641         return recordBefore && Ext.Array.contains(records, recordBefore);
110642     },
110643
110644     positionIndicator: function(node, data, e) {
110645         var me = this,
110646             view = me.view,
110647             pos = me.getPosition(e, node),
110648             overRecord = view.getRecord(node),
110649             draggingRecords = data.records,
110650             indicator, indicatorY;
110651
110652         if (!Ext.Array.contains(draggingRecords, overRecord) && (
110653             pos == 'before' && !me.containsRecordAtOffset(draggingRecords, overRecord, -1) ||
110654             pos == 'after' && !me.containsRecordAtOffset(draggingRecords, overRecord, 1)
110655         )) {
110656             me.valid = true;
110657
110658             if (me.overRecord != overRecord || me.currentPosition != pos) {
110659
110660                 indicatorY = Ext.fly(node).getY() - view.el.getY() - 1;
110661                 if (pos == 'after') {
110662                     indicatorY += Ext.fly(node).getHeight();
110663                 }
110664                 me.getIndicator().setWidth(Ext.fly(view.el).getWidth()).showAt(0, indicatorY);
110665
110666                 // Cache the overRecord and the 'before' or 'after' indicator.
110667                 me.overRecord = overRecord;
110668                 me.currentPosition = pos;
110669             }
110670         } else {
110671             me.invalidateDrop();
110672         }
110673     },
110674
110675     invalidateDrop: function() {
110676         if (this.valid) {
110677             this.valid = false;
110678             this.getIndicator().hide();
110679         }
110680     },
110681
110682     // The mouse is over a View node
110683     onNodeOver: function(node, dragZone, e, data) {
110684         if (!Ext.Array.contains(data.records, this.view.getRecord(node))) {
110685             this.positionIndicator(node, data, e);
110686         }
110687         return this.valid ? this.dropAllowed : this.dropNotAllowed;
110688     },
110689
110690     // Moved out of the DropZone without dropping.
110691     // Remove drop position indicator
110692     notifyOut: function(node, dragZone, e, data) {
110693         this.callParent(arguments);
110694         delete this.overRecord;
110695         delete this.currentPosition;
110696         if (this.indicator) {
110697             this.indicator.hide();
110698         }
110699     },
110700
110701     // The mouse is past the end of all nodes (or there are no nodes)
110702     onContainerOver : function(dd, e, data) {
110703         var v = this.view,
110704             c = v.store.getCount();
110705
110706         // There are records, so position after the last one
110707         if (c) {
110708             this.positionIndicator(v.getNode(c - 1), data, e);
110709         }
110710
110711         // No records, position the indicator at the top
110712         else {
110713             delete this.overRecord;
110714             delete this.currentPosition;
110715             this.getIndicator().setWidth(Ext.fly(v.el).getWidth()).showAt(0, 0);
110716             this.valid = true;
110717         }
110718         return this.dropAllowed;
110719     },
110720
110721     onContainerDrop : function(dd, e, data) {
110722         return this.onNodeDrop(dd, null, e, data);
110723     },
110724
110725     onNodeDrop: function(node, dragZone, e, data) {
110726         var me = this,
110727             dropped = false,
110728
110729             // Create a closure to perform the operation which the event handler may use.
110730             // Users may now return <code>0</code> from the beforedrop handler, and perform any kind
110731             // of asynchronous processing such as an Ext.Msg.confirm, or an Ajax request,
110732             // and complete the drop gesture at some point in the future by calling this function.
110733             processDrop = function () {
110734                 me.invalidateDrop();
110735                 me.handleNodeDrop(data, me.overRecord, me.currentPosition);
110736                 dropped = true;
110737                 me.fireViewEvent('drop', node, data, me.overRecord, me.currentPosition);
110738             },
110739             performOperation;
110740
110741         if (me.valid) {
110742             performOperation = me.fireViewEvent('beforedrop', node, data, me.overRecord, me.currentPosition, processDrop);
110743             if (performOperation === 0) {
110744                 return;
110745             } else if (performOperation !== false) {
110746                 // If the processDrop function was called in the event handler, do not do it again.
110747                 if (!dropped) {
110748                     processDrop();
110749                 }
110750             } else {
110751                 return false;
110752             }
110753         } else {
110754             return false;
110755         }
110756     }
110757 });
110758
110759 Ext.define('Ext.grid.ViewDropZone', {
110760     extend: 'Ext.view.DropZone',
110761
110762     indicatorHtml: '<div class="x-grid-drop-indicator-left"></div><div class="x-grid-drop-indicator-right"></div>',
110763     indicatorCls: 'x-grid-drop-indicator',
110764
110765     handleNodeDrop : function(data, record, position) {
110766         var view = this.view,
110767             store = view.getStore(),
110768             index, records, i, len;
110769
110770         // If the copy flag is set, create a copy of the Models with the same IDs
110771         if (data.copy) {
110772             records = data.records;
110773             data.records = [];
110774             for (i = 0, len = records.length; i < len; i++) {
110775                 data.records.push(records[i].copy(records[i].getId()));
110776             }
110777         } else {
110778             /*
110779              * Remove from the source store. We do this regardless of whether the store
110780              * is the same bacsue the store currently doesn't handle moving records
110781              * within the store. In the future it should be possible to do this.
110782              * Here was pass the isMove parameter if we're moving to the same view.
110783              */
110784             data.view.store.remove(data.records, data.view === view);
110785         }
110786
110787         index = store.indexOf(record);
110788         if (position == 'after') {
110789             index++;
110790         }
110791         store.insert(index, data.records);
110792         view.getSelectionModel().select(data.records);
110793     }
110794 });
110795 /**
110796  * @class Ext.grid.column.Action
110797  * @extends Ext.grid.column.Column
110798  * <p>A Grid header type which renders an icon, or a series of icons in a grid cell, and offers a scoped click
110799  * handler for each icon.</p>
110800  *
110801  * {@img Ext.grid.column.Action/Ext.grid.column.Action.png Ext.grid.column.Action grid column}
110802  *  
110803  * ## Code
110804  *     Ext.create('Ext.data.Store', {
110805  *         storeId:'employeeStore',
110806  *         fields:['firstname', 'lastname', 'senority', 'dep', 'hired'],
110807  *         data:[
110808  *             {firstname:"Michael", lastname:"Scott"},
110809  *             {firstname:"Dwight", lastname:"Schrute"},
110810  *             {firstname:"Jim", lastname:"Halpert"},
110811  *             {firstname:"Kevin", lastname:"Malone"},
110812  *             {firstname:"Angela", lastname:"Martin"}                        
110813  *         ]
110814  *     });
110815  *     
110816  *     Ext.create('Ext.grid.Panel', {
110817  *         title: 'Action Column Demo',
110818  *         store: Ext.data.StoreManager.lookup('employeeStore'),
110819  *         columns: [
110820  *             {text: 'First Name',  dataIndex:'firstname'},
110821  *             {text: 'Last Name',  dataIndex:'lastname'},
110822  *             {
110823  *                 xtype:'actioncolumn', 
110824  *                 width:50,
110825  *                 items: [{
110826  *                     icon: 'images/edit.png',  // Use a URL in the icon config
110827  *                     tooltip: 'Edit',
110828  *                     handler: function(grid, rowIndex, colIndex) {
110829  *                         var rec = grid.getStore().getAt(rowIndex);
110830  *                         alert("Edit " + rec.get('firstname'));
110831  *                     }
110832  *                 },{
110833  *                     icon: 'images/delete.png',
110834  *                     tooltip: 'Delete',
110835  *                     handler: function(grid, rowIndex, colIndex) {
110836  *                         var rec = grid.getStore().getAt(rowIndex);
110837  *                         alert("Terminate " + rec.get('firstname'));
110838  *                     }                
110839  *                 }]
110840  *             }
110841  *         ],
110842  *         width: 250,
110843  *         renderTo: Ext.getBody()
110844  *     });
110845  * <p>The action column can be at any index in the columns array, and a grid can have any number of
110846  * action columns. </p>
110847  * @xtype actioncolumn
110848  */
110849 Ext.define('Ext.grid.column.Action', {
110850     extend: 'Ext.grid.column.Column',
110851     alias: ['widget.actioncolumn'],
110852     alternateClassName: 'Ext.grid.ActionColumn',
110853
110854     /**
110855      * @cfg {String} icon
110856      * The URL of an image to display as the clickable element in the column. 
110857      * Optional - defaults to <code>{@link Ext#BLANK_IMAGE_URL Ext.BLANK_IMAGE_URL}</code>.
110858      */
110859     /**
110860      * @cfg {String} iconCls
110861      * A CSS class to apply to the icon image. To determine the class dynamically, configure the Column with a <code>{@link #getClass}</code> function.
110862      */
110863     /**
110864      * @cfg {Function} handler A function called when the icon is clicked.
110865      * The handler is passed the following parameters:<div class="mdetail-params"><ul>
110866      * <li><code>view</code> : TableView<div class="sub-desc">The owning TableView.</div></li>
110867      * <li><code>rowIndex</code> : Number<div class="sub-desc">The row index clicked on.</div></li>
110868      * <li><code>colIndex</code> : Number<div class="sub-desc">The column index clicked on.</div></li>
110869      * <li><code>item</code> : Object<div class="sub-desc">The clicked item (or this Column if multiple 
110870      * {@link #items} were not configured).</div></li>
110871      * <li><code>e</code> : Event<div class="sub-desc">The click event.</div></li>
110872      * </ul></div>
110873      */
110874     /**
110875      * @cfg {Object} scope The scope (<tt><b>this</b></tt> reference) in which the <code>{@link #handler}</code>
110876      * and <code>{@link #getClass}</code> fuctions are executed. Defaults to this Column.
110877      */
110878     /**
110879      * @cfg {String} tooltip A tooltip message to be displayed on hover. {@link Ext.tip.QuickTipManager#init Ext.tip.QuickTipManager} must have 
110880      * been initialized.
110881      */
110882     /**
110883      * @cfg {Boolean} stopSelection Defaults to <code>true</code>. Prevent grid <i>row</i> selection upon mousedown.
110884      */
110885     /**
110886      * @cfg {Function} getClass A function which returns the CSS class to apply to the icon image.
110887      * The function is passed the following parameters:<ul>
110888      *     <li><b>v</b> : Object<p class="sub-desc">The value of the column's configured field (if any).</p></li>
110889      *     <li><b>metadata</b> : Object<p class="sub-desc">An object in which you may set the following attributes:<ul>
110890      *         <li><b>css</b> : String<p class="sub-desc">A CSS class name to add to the cell's TD element.</p></li>
110891      *         <li><b>attr</b> : String<p class="sub-desc">An HTML attribute definition string to apply to the data container element <i>within</i> the table cell
110892      *         (e.g. 'style="color:red;"').</p></li>
110893      *     </ul></p></li>
110894      *     <li><b>r</b> : Ext.data.Record<p class="sub-desc">The Record providing the data.</p></li>
110895      *     <li><b>rowIndex</b> : Number<p class="sub-desc">The row index..</p></li>
110896      *     <li><b>colIndex</b> : Number<p class="sub-desc">The column index.</p></li>
110897      *     <li><b>store</b> : Ext.data.Store<p class="sub-desc">The Store which is providing the data Model.</p></li>
110898      * </ul>
110899      */
110900     /**
110901      * @cfg {Array} items An Array which may contain multiple icon definitions, each element of which may contain:
110902      * <div class="mdetail-params"><ul>
110903      * <li><code>icon</code> : String<div class="sub-desc">The url of an image to display as the clickable element 
110904      * in the column.</div></li>
110905      * <li><code>iconCls</code> : String<div class="sub-desc">A CSS class to apply to the icon image.
110906      * To determine the class dynamically, configure the item with a <code>getClass</code> function.</div></li>
110907      * <li><code>getClass</code> : Function<div class="sub-desc">A function which returns the CSS class to apply to the icon image.
110908      * The function is passed the following parameters:<ul>
110909      *     <li><b>v</b> : Object<p class="sub-desc">The value of the column's configured field (if any).</p></li>
110910      *     <li><b>metadata</b> : Object<p class="sub-desc">An object in which you may set the following attributes:<ul>
110911      *         <li><b>css</b> : String<p class="sub-desc">A CSS class name to add to the cell's TD element.</p></li>
110912      *         <li><b>attr</b> : String<p class="sub-desc">An HTML attribute definition string to apply to the data container element <i>within</i> the table cell
110913      *         (e.g. 'style="color:red;"').</p></li>
110914      *     </ul></p></li>
110915      *     <li><b>r</b> : Ext.data.Record<p class="sub-desc">The Record providing the data.</p></li>
110916      *     <li><b>rowIndex</b> : Number<p class="sub-desc">The row index..</p></li>
110917      *     <li><b>colIndex</b> : Number<p class="sub-desc">The column index.</p></li>
110918      *     <li><b>store</b> : Ext.data.Store<p class="sub-desc">The Store which is providing the data Model.</p></li>
110919      * </ul></div></li>
110920      * <li><code>handler</code> : Function<div class="sub-desc">A function called when the icon is clicked.</div></li>
110921      * <li><code>scope</code> : Scope<div class="sub-desc">The scope (<code><b>this</b></code> reference) in which the 
110922      * <code>handler</code> and <code>getClass</code> functions are executed. Fallback defaults are this Column's
110923      * configured scope, then this Column.</div></li>
110924      * <li><code>tooltip</code> : String<div class="sub-desc">A tooltip message to be displayed on hover. 
110925      * {@link Ext.tip.QuickTipManager#init Ext.tip.QuickTipManager} must have been initialized.</div></li>
110926      * </ul></div>
110927      */
110928     header: '&#160;',
110929
110930     actionIdRe: /x-action-col-(\d+)/,
110931
110932     /**
110933      * @cfg {String} altText The alt text to use for the image element. Defaults to <tt>''</tt>.
110934      */
110935     altText: '',
110936     
110937     sortable: false,
110938
110939     constructor: function(config) {
110940         var me = this,
110941             cfg = Ext.apply({}, config),
110942             items = cfg.items || [me],
110943             l = items.length,
110944             i,
110945             item;
110946
110947         // This is a Container. Delete the items config to be reinstated after construction.
110948         delete cfg.items;
110949         this.callParent([cfg]);
110950
110951         // Items is an array property of ActionColumns
110952         me.items = items;
110953
110954 //      Renderer closure iterates through items creating an <img> element for each and tagging with an identifying 
110955 //      class name x-action-col-{n}
110956         me.renderer = function(v, meta) {
110957 //          Allow a configured renderer to create initial value (And set the other values in the "metadata" argument!)
110958             v = Ext.isFunction(cfg.renderer) ? cfg.renderer.apply(this, arguments)||'' : '';
110959
110960             meta.tdCls += ' ' + Ext.baseCSSPrefix + 'action-col-cell';
110961             for (i = 0; i < l; i++) {
110962                 item = items[i];
110963                 v += '<img alt="' + me.altText + '" src="' + (item.icon || Ext.BLANK_IMAGE_URL) +
110964                     '" class="' + Ext.baseCSSPrefix + 'action-col-icon ' + Ext.baseCSSPrefix + 'action-col-' + String(i) + ' ' +  (item.iconCls || '') + 
110965                     ' ' + (Ext.isFunction(item.getClass) ? item.getClass.apply(item.scope||me.scope||me, arguments) : (me.iconCls || '')) + '"' +
110966                     ((item.tooltip) ? ' data-qtip="' + item.tooltip + '"' : '') + ' />';
110967             }
110968             return v;
110969         };
110970     },
110971
110972     destroy: function() {
110973         delete this.items;
110974         delete this.renderer;
110975         return this.callParent(arguments);
110976     },
110977
110978     /**
110979      * @private
110980      * Process and refire events routed from the GridView's processEvent method.
110981      * Also fires any configured click handlers. By default, cancels the mousedown event to prevent selection.
110982      * Returns the event handler's status to allow canceling of GridView's bubbling process.
110983      */
110984     processEvent : function(type, view, cell, recordIndex, cellIndex, e){
110985         var m = e.getTarget().className.match(this.actionIdRe),
110986             item, fn;
110987         if (m && (item = this.items[parseInt(m[1], 10)])) {
110988             if (type == 'click') {
110989                 fn = item.handler;
110990                 if (fn || this.handler) {
110991                     fn.call(item.scope||this.scope||this, view, recordIndex, cellIndex, item, e);
110992                 }
110993             } else if ((type == 'mousedown') && (item.stopSelection !== false)) {
110994                 return false;
110995             }
110996         }
110997         return this.callParent(arguments);
110998     },
110999
111000     cascade: function(fn, scope) {
111001         fn.call(scope||this, this);
111002     },
111003
111004     // Private override because this cannot function as a Container, and it has an items property which is an Array, NOT a MixedCollection.
111005     getRefItems: function() {
111006         return [];
111007     }
111008 });
111009 /**
111010  * @class Ext.grid.column.Boolean
111011  * @extends Ext.grid.column.Column
111012  * <p>A Column definition class which renders boolean data fields.  See the {@link Ext.grid.column.Column#xtype xtype}
111013  * config option of {@link Ext.grid.column.Column} for more details.</p>
111014  *
111015  * {@img Ext.grid.column.Boolean/Ext.grid.column.Boolean.png Ext.grid.column.Boolean grid column}
111016  *
111017  *  ## Code
111018  *     Ext.create('Ext.data.Store', {
111019  *        storeId:'sampleStore',
111020  *        fields:[
111021  *            {name: 'framework', type: 'string'},
111022  *            {name: 'rocks', type: 'boolean'}
111023  *        ],
111024  *        data:{'items':[
111025  *            {"framework":"Ext JS 4", "rocks":true},
111026  *            {"framework":"Sencha Touch", "rocks":true},
111027  *            {"framework":"Ext GWT", "rocks":true},            
111028  *            {"framework":"Other Guys", "rocks":false}            
111029  *        ]},
111030  *        proxy: {
111031  *            type: 'memory',
111032  *            reader: {
111033  *                type: 'json',
111034  *                root: 'items'
111035  *            }
111036  *        }
111037  *    });
111038  *    
111039  *    Ext.create('Ext.grid.Panel', {
111040  *        title: 'Boolean Column Demo',
111041  *        store: Ext.data.StoreManager.lookup('sampleStore'),
111042  *        columns: [
111043  *            {text: 'Framework',  dataIndex: 'framework', flex: 1},
111044  *            {
111045  *                xtype: 'booleancolumn', 
111046  *                text: 'Rocks',
111047  *                trueText: 'Yes',
111048  *                falseText: 'No', 
111049  *                dataIndex: 'rocks'}
111050  *        ],
111051  *        height: 200,
111052  *        width: 400,
111053  *        renderTo: Ext.getBody()
111054  *    });
111055  * 
111056  * @xtype booleancolumn
111057  */
111058 Ext.define('Ext.grid.column.Boolean', {
111059     extend: 'Ext.grid.column.Column',
111060     alias: ['widget.booleancolumn'],
111061     alternateClassName: 'Ext.grid.BooleanColumn',
111062
111063     /**
111064      * @cfg {String} trueText
111065      * The string returned by the renderer when the column value is not falsey (defaults to <tt>'true'</tt>).
111066      */
111067     trueText: 'true',
111068
111069     /**
111070      * @cfg {String} falseText
111071      * The string returned by the renderer when the column value is falsey (but not undefined) (defaults to
111072      * <tt>'false'</tt>).
111073      */
111074     falseText: 'false',
111075
111076     /**
111077      * @cfg {String} undefinedText
111078      * The string returned by the renderer when the column value is undefined (defaults to <tt>'&#160;'</tt>).
111079      */
111080     undefinedText: '&#160;',
111081
111082     constructor: function(cfg){
111083         this.callParent(arguments);
111084         var trueText      = this.trueText,
111085             falseText     = this.falseText,
111086             undefinedText = this.undefinedText;
111087
111088         this.renderer = function(value){
111089             if(value === undefined){
111090                 return undefinedText;
111091             }
111092             if(!value || value === 'false'){
111093                 return falseText;
111094             }
111095             return trueText;
111096         };
111097     }
111098 });
111099 /**
111100  * @class Ext.grid.column.Date
111101  * @extends Ext.grid.column.Column
111102  * <p>A Column definition class which renders a passed date according to the default locale, or a configured
111103  * {@link #format}.</p>
111104  *
111105  * {@img Ext.grid.column.Date/Ext.grid.column.Date.png Ext.grid.column.Date grid column}
111106  *
111107  * ## Code
111108  *    Ext.create('Ext.data.Store', {
111109  *        storeId:'sampleStore',
111110  *        fields:[
111111  *            {name: 'symbol', type: 'string'},
111112  *            {name: 'date', type: 'date'},
111113  *            {name: 'change', type: 'number'},
111114  *            {name: 'volume', type: 'number'},
111115  *            {name: 'topday', type: 'date'}                        
111116  *        ],
111117  *        data:[
111118  *            {symbol:"msft", date:'2011/04/22', change:2.43, volume:61606325, topday:'04/01/2010'},
111119  *            {symbol:"goog", date:'2011/04/22', change:0.81, volume:3053782, topday:'04/11/2010'},
111120  *            {symbol:"apple", date:'2011/04/22', change:1.35, volume:24484858, topday:'04/28/2010'},            
111121  *            {symbol:"sencha", date:'2011/04/22', change:8.85, volume:5556351, topday:'04/22/2010'}            
111122  *        ]
111123  *    });
111124  *    
111125  *    Ext.create('Ext.grid.Panel', {
111126  *        title: 'Date Column Demo',
111127  *        store: Ext.data.StoreManager.lookup('sampleStore'),
111128  *        columns: [
111129  *            {text: 'Symbol',  dataIndex: 'symbol', flex: 1},
111130  *            {text: 'Date',  dataIndex: 'date', xtype: 'datecolumn', format:'Y-m-d'},
111131  *            {text: 'Change',  dataIndex: 'change', xtype: 'numbercolumn', format:'0.00'},
111132  *            {text: 'Volume',  dataIndex: 'volume', xtype: 'numbercolumn', format:'0,000'},
111133  *            {text: 'Top Day',  dataIndex: 'topday', xtype: 'datecolumn', format:'l'}            
111134  *        ],
111135  *        height: 200,
111136  *        width: 450,
111137  *        renderTo: Ext.getBody()
111138  *    });
111139  *    
111140  * @xtype datecolumn
111141  */
111142 Ext.define('Ext.grid.column.Date', {
111143     extend: 'Ext.grid.column.Column',
111144     alias: ['widget.datecolumn'],
111145     requires: ['Ext.Date'],
111146     alternateClassName: 'Ext.grid.DateColumn',
111147
111148     /**
111149      * @cfg {String} format
111150      * A formatting string as used by {@link Date#format Date.format} to format a Date for this Column.
111151      * This defaults to the default date from {@link Ext.Date#defaultFormat} which itself my be overridden
111152      * in a locale file.
111153      */
111154     format : Ext.Date.defaultFormat,
111155
111156     constructor: function(cfg){
111157         this.callParent(arguments);
111158         this.renderer = Ext.util.Format.dateRenderer(this.format);
111159     }
111160 });
111161 /**
111162  * @class Ext.grid.column.Number
111163  * @extends Ext.grid.column.Column
111164  * <p>A Column definition class which renders a numeric data field according to a {@link #format} string.</p>
111165  *
111166  * {@img Ext.grid.column.Number/Ext.grid.column.Number.png Ext.grid.column.Number cell editing}
111167  *
111168  * ## Code
111169  *     Ext.create('Ext.data.Store', {
111170  *        storeId:'sampleStore',
111171  *        fields:[
111172  *            {name: 'symbol', type: 'string'},
111173  *            {name: 'price', type: 'number'},
111174  *            {name: 'change', type: 'number'},
111175  *            {name: 'volume', type: 'number'},            
111176  *        ],
111177  *        data:[
111178  *            {symbol:"msft", price:25.76, change:2.43, volume:61606325},
111179  *            {symbol:"goog", price:525.73, change:0.81, volume:3053782},
111180  *            {symbol:"apple", price:342.41, change:1.35, volume:24484858},            
111181  *            {symbol:"sencha", price:142.08, change:8.85, volume:5556351}            
111182  *        ]
111183  *    });
111184  *    
111185  *    Ext.create('Ext.grid.Panel', {
111186  *        title: 'Number Column Demo',
111187  *        store: Ext.data.StoreManager.lookup('sampleStore'),
111188  *        columns: [
111189  *            {text: 'Symbol',  dataIndex: 'symbol', flex: 1},
111190  *            {text: 'Current Price',  dataIndex: 'price', renderer: Ext.util.Format.usMoney},
111191  *            {text: 'Change',  dataIndex: 'change', xtype: 'numbercolumn', format:'0.00'},
111192  *            {text: 'Volume',  dataIndex: 'volume', xtype: 'numbercolumn', format:'0,000'}
111193  *        ],
111194  *        height: 200,
111195  *        width: 400,
111196  *        renderTo: Ext.getBody()
111197  *    });
111198  * 
111199  * @xtype numbercolumn
111200  */
111201 Ext.define('Ext.grid.column.Number', {
111202     extend: 'Ext.grid.column.Column',
111203     alias: ['widget.numbercolumn'],
111204     requires: ['Ext.util.Format'],
111205     alternateClassName: 'Ext.grid.NumberColumn',
111206
111207     /**
111208      * @cfg {String} format
111209      * A formatting string as used by {@link Ext.util.Format#number} to format a numeric value for this Column
111210      * (defaults to <code>'0,000.00'</code>).
111211      */
111212     format : '0,000.00',
111213     constructor: function(cfg) {
111214         this.callParent(arguments);
111215         this.renderer = Ext.util.Format.numberRenderer(this.format);
111216     }
111217 });
111218 /**
111219  * @class Ext.grid.column.Template
111220  * @extends Ext.grid.column.Column
111221  * 
111222  * A Column definition class which renders a value by processing a {@link Ext.data.Model Model}'s
111223  * {@link Ext.data.Model#data data} using a {@link #tpl configured} {@link Ext.XTemplate XTemplate}.
111224  * 
111225  *  {@img Ext.grid.column.Template/Ext.grid.column.Template.png Ext.grid.column.Template grid column}
111226  * 
111227  * ## Code
111228  *     Ext.create('Ext.data.Store', {
111229  *         storeId:'employeeStore',
111230  *         fields:['firstname', 'lastname', 'senority', 'department'],
111231  *         groupField: 'department',
111232  *         data:[
111233  *             {firstname:"Michael", lastname:"Scott", senority:7, department:"Manangement"},
111234  *             {firstname:"Dwight", lastname:"Schrute", senority:2, department:"Sales"},
111235  *             {firstname:"Jim", lastname:"Halpert", senority:3, department:"Sales"},
111236  *             {firstname:"Kevin", lastname:"Malone", senority:4, department:"Accounting"},
111237  *             {firstname:"Angela", lastname:"Martin", senority:5, department:"Accounting"}                        
111238  *         ]
111239  *     });
111240  *     
111241  *     Ext.create('Ext.grid.Panel', {
111242  *         title: 'Column Template Demo',
111243  *         store: Ext.data.StoreManager.lookup('employeeStore'),
111244  *         columns: [
111245  *             {text: 'Full Name',  xtype:'templatecolumn', tpl:'{firstname} {lastname}', flex:1},
111246  *             {text: 'Deparment (Yrs)', xtype:'templatecolumn', tpl:'{department} ({senority})'}
111247  *         ],
111248  *         height: 200,
111249  *         width: 300,
111250  *         renderTo: Ext.getBody()
111251  *     });
111252  * 
111253  * @markdown
111254  * @xtype templatecolumn
111255  */
111256 Ext.define('Ext.grid.column.Template', {
111257     extend: 'Ext.grid.column.Column',
111258     alias: ['widget.templatecolumn'],
111259     requires: ['Ext.XTemplate'],
111260     alternateClassName: 'Ext.grid.TemplateColumn',
111261
111262     /**
111263      * @cfg {String/XTemplate} tpl
111264      * An {@link Ext.XTemplate XTemplate}, or an XTemplate <i>definition string</i> to use to process a
111265      * {@link Ext.data.Model Model}'s {@link Ext.data.Model#data data} to produce a column's rendered value.
111266      */
111267     constructor: function(cfg){
111268         var me = this,
111269             tpl;
111270             
111271         me.callParent(arguments);
111272         tpl = me.tpl = (!Ext.isPrimitive(me.tpl) && me.tpl.compile) ? me.tpl : Ext.create('Ext.XTemplate', me.tpl);
111273
111274         me.renderer = function(value, p, record) {
111275             var data = Ext.apply({}, record.data, record.getAssociatedData());
111276             return tpl.apply(data);
111277         };
111278     }
111279 });
111280
111281 /**
111282  * @class Ext.grid.feature.Feature
111283  * @extends Ext.util.Observable
111284  * 
111285  * A feature is a type of plugin that is specific to the {@link Ext.grid.Panel}. It provides several
111286  * hooks that allows the developer to inject additional functionality at certain points throughout the 
111287  * grid creation cycle. This class provides the base template methods that are available to the developer,
111288  * it should be extended.
111289  * 
111290  * There are several built in features that extend this class, for example:
111291  *
111292  *  - {@link Ext.grid.feature.Grouping} - Shows grid rows in groups as specified by the {@link Ext.data.Store}
111293  *  - {@link Ext.grid.feature.RowBody} - Adds a body section for each grid row that can contain markup.
111294  *  - {@link Ext.grid.feature.Summary} - Adds a summary row at the bottom of the grid with aggregate totals for a column.
111295  * 
111296  * ## Using Features
111297  * A feature is added to the grid by specifying it an array of features in the configuration:
111298  * 
111299  *     var groupingFeature = Ext.create('Ext.grid.feature.Grouping');
111300  *     Ext.create('Ext.grid.Panel', {
111301  *         // other options
111302  *         features: [groupingFeature]
111303  *     });
111304  * 
111305  * @abstract
111306  */
111307 Ext.define('Ext.grid.feature.Feature', {
111308     extend: 'Ext.util.Observable',
111309     alias: 'feature.feature',
111310     
111311     isFeature: true,
111312     disabled: false,
111313     
111314     /**
111315      * @property {Boolean}
111316      * Most features will expose additional events, some may not and will
111317      * need to change this to false.
111318      */
111319     hasFeatureEvent: true,
111320     
111321     /**
111322      * @property {String}
111323      * Prefix to use when firing events on the view.
111324      * For example a prefix of group would expose "groupclick", "groupcontextmenu", "groupdblclick".
111325      */
111326     eventPrefix: null,
111327     
111328     /**
111329      * @property {String}
111330      * Selector used to determine when to fire the event with the eventPrefix.
111331      */
111332     eventSelector: null,
111333     
111334     /**
111335      * @property {Ext.view.Table}
111336      * Reference to the TableView.
111337      */
111338     view: null,
111339     
111340     /**
111341      * @property {Ext.grid.Panel}
111342      * Reference to the grid panel
111343      */
111344     grid: null,
111345     
111346     /**
111347      * Most features will not modify the data returned to the view.
111348      * This is limited to one feature that manipulates the data per grid view.
111349      */
111350     collectData: false,
111351         
111352     getFeatureTpl: function() {
111353         return '';
111354     },
111355     
111356     /**
111357      * Abstract method to be overriden when a feature should add additional
111358      * arguments to its event signature. By default the event will fire:
111359      * - view - The underlying Ext.view.Table
111360      * - featureTarget - The matched element by the defined {@link eventSelector}
111361      *
111362      * The method must also return the eventName as the first index of the array
111363      * to be passed to fireEvent.
111364      */
111365     getFireEventArgs: function(eventName, view, featureTarget) {
111366         return [eventName, view, featureTarget];
111367     },
111368     
111369     /**
111370      * Approriate place to attach events to the view, selectionmodel, headerCt, etc
111371      */
111372     attachEvents: function() {
111373         
111374     },
111375     
111376     getFragmentTpl: function() {
111377         return;
111378     },
111379     
111380     /**
111381      * Allows a feature to mutate the metaRowTpl.
111382      * The array received as a single argument can be manipulated to add things
111383      * on the end/begining of a particular row.
111384      */
111385     mutateMetaRowTpl: function(metaRowTplArray) {
111386         
111387     },
111388     
111389     /**
111390      * Allows a feature to inject member methods into the metaRowTpl. This is
111391      * important for embedding functionality which will become part of the proper
111392      * row tpl.
111393      */
111394     getMetaRowTplFragments: function() {
111395         return {};
111396     },
111397
111398     getTableFragments: function() {
111399         return {};
111400     },
111401     
111402     /**
111403      * Provide additional data to the prepareData call within the grid view.
111404      * @param {Object} data The data for this particular record.
111405      * @param {Number} idx The row index for this record.
111406      * @param {Ext.data.Model} record The record instance
111407      * @param {Object} orig The original result from the prepareData call to massage.
111408      */
111409     getAdditionalData: function(data, idx, record, orig) {
111410         return {};
111411     },
111412     
111413     /**
111414      * Enable a feature
111415      */
111416     enable: function() {
111417         this.disabled = false;
111418     },
111419     
111420     /**
111421      * Disable a feature
111422      */
111423     disable: function() {
111424         this.disabled = true;
111425     }
111426     
111427 });
111428 /**
111429  * A small abstract class that contains the shared behaviour for any summary
111430  * calculations to be used in the grid.
111431  * @class Ext.grid.feature.AbstractSummary
111432  * @extends Ext.grid.feature.Feature
111433  * @ignore
111434  */
111435 Ext.define('Ext.grid.feature.AbstractSummary', {
111436     
111437     /* Begin Definitions */
111438    
111439     extend: 'Ext.grid.feature.Feature',
111440     
111441     alias: 'feature.abstractsummary',
111442    
111443     /* End Definitions */
111444    
111445    /**
111446     * @cfg {Boolean} showSummaryRow True to show the summary row. Defaults to <tt>true</tt>.
111447     */
111448     showSummaryRow: true,
111449     
111450     // @private
111451     nestedIdRe: /\{\{id\}([\w\-]*)\}/g,
111452     
111453     /**
111454      * Toggle whether or not to show the summary row.
111455      * @param {Boolan} visible True to show the summary row
111456      */
111457     toggleSummaryRow: function(visible){
111458         this.showSummaryRow = !!visible;
111459     },
111460     
111461     /**
111462      * Gets any fragments to be used in the tpl
111463      * @private
111464      * @return {Object} The fragments
111465      */
111466     getSummaryFragments: function(){
111467         var fragments = {};
111468         if (this.showSummaryRow) {
111469             Ext.apply(fragments, {
111470                 printSummaryRow: Ext.bind(this.printSummaryRow, this)
111471             });
111472         }
111473         return fragments;
111474     },
111475     
111476     /**
111477      * Prints a summary row
111478      * @private
111479      * @param {Object} index The index in the template
111480      * @return {String} The value of the summary row
111481      */
111482     printSummaryRow: function(index){
111483         var inner = this.view.getTableChunker().metaRowTpl.join('');
111484         
111485         inner = inner.replace('x-grid-row', 'x-grid-row-summary');
111486         inner = inner.replace('{{id}}', '{gridSummaryValue}');
111487         inner = inner.replace(this.nestedIdRe, '{id$1}');  
111488         inner = inner.replace('{[this.embedRowCls()]}', '{rowCls}');
111489         inner = inner.replace('{[this.embedRowAttr()]}', '{rowAttr}');
111490         inner = Ext.create('Ext.XTemplate', inner, {
111491             firstOrLastCls: Ext.view.TableChunker.firstOrLastCls
111492         });
111493         
111494         return inner.applyTemplate({
111495             columns: this.getPrintData(index)
111496         });
111497     },
111498     
111499     /**
111500      * Gets the value for the column from the attached data.
111501      * @param {Ext.grid.column.Column} column The header
111502      * @param {Object} data The current data
111503      * @return {String} The value to be rendered
111504      */
111505     getColumnValue: function(column, data){
111506         var comp = Ext.getCmp(column.id),
111507             value = data[column.dataIndex],
111508             renderer = comp.summaryRenderer || comp.renderer;
111509             
111510         if (renderer) {
111511             value = renderer.call(comp.scope || this, value, data, column.dataIndex);
111512         }
111513         return value;
111514     },
111515     
111516     /**
111517      * Get the summary data for a field.
111518      * @private
111519      * @param {Ext.data.Store} store The store to get the data from
111520      * @param {String/Function} type The type of aggregation. If a function is specified it will
111521      * be passed to the stores aggregate function.
111522      * @param {String} field The field to aggregate on
111523      * @param {Boolean} group True to aggregate in grouped mode 
111524      * @return {Mixed} See the return type for the store functions.
111525      */
111526     getSummary: function(store, type, field, group){
111527         if (type) {
111528             if (Ext.isFunction(type)) {
111529                 return store.aggregate(type, null, group);
111530             }
111531             
111532             switch (type) {
111533                 case 'count':
111534                     return store.count(group);
111535                 case 'min':
111536                     return store.min(field, group);
111537                 case 'max':
111538                     return store.max(field, group);
111539                 case 'sum':
111540                     return store.sum(field, group);
111541                 case 'average':
111542                     return store.average(field, group);
111543                 default:
111544                     return group ? {} : '';
111545                     
111546             }
111547         }
111548     }
111549     
111550 });
111551
111552 /**
111553  * @class Ext.grid.feature.Chunking
111554  * @extends Ext.grid.feature.Feature
111555  */
111556 Ext.define('Ext.grid.feature.Chunking', {
111557     extend: 'Ext.grid.feature.Feature',
111558     alias: 'feature.chunking',
111559     
111560     chunkSize: 20,
111561     rowHeight: Ext.isIE ? 27 : 26,
111562     visibleChunk: 0,
111563     hasFeatureEvent: false,
111564     attachEvents: function() {
111565         var grid = this.view.up('gridpanel'),
111566             scroller = grid.down('gridscroller[dock=right]');
111567         scroller.el.on('scroll', this.onBodyScroll, this, {buffer: 300});
111568         //this.view.on('bodyscroll', this.onBodyScroll, this, {buffer: 300});
111569     },
111570     
111571     onBodyScroll: function(e, t) {
111572         var view = this.view,
111573             top  = t.scrollTop,
111574             nextChunk = Math.floor(top / this.rowHeight / this.chunkSize);
111575         if (nextChunk !== this.visibleChunk) {
111576         
111577             this.visibleChunk = nextChunk;
111578             view.refresh();
111579             view.el.dom.scrollTop = top;
111580             //BrowserBug: IE6,7,8 quirks mode takes setting scrollTop 2x.
111581             view.el.dom.scrollTop = top;
111582         }
111583     },
111584     
111585     collectData: function(records, preppedRecords, startIndex, fullWidth, orig) {
111586         var o = {
111587             fullWidth: orig.fullWidth,
111588             chunks: []
111589         },
111590         //headerCt = this.view.headerCt,
111591         //colums = headerCt.getColumnsForTpl(),
111592         recordCount = orig.rows.length,
111593         start = 0,
111594         i = 0,
111595         visibleChunk = this.visibleChunk,
111596         chunk,
111597         rows,
111598         chunkLength;
111599
111600         for (; start < recordCount; start+=this.chunkSize, i++) {
111601             if (start+this.chunkSize > recordCount) {
111602                 chunkLength = recordCount - start;
111603             } else {
111604                 chunkLength = this.chunkSize;
111605             }
111606             
111607             if (i >= visibleChunk - 1 && i <= visibleChunk + 1) {
111608                 rows = orig.rows.slice(start, start+this.chunkSize);
111609             } else {
111610                 rows = [];
111611             }
111612             o.chunks.push({
111613                 rows: rows,
111614                 fullWidth: fullWidth,
111615                 chunkHeight: chunkLength * this.rowHeight
111616             });
111617         }
111618         
111619         
111620         return o;
111621     },
111622     
111623     getTableFragments: function() {
111624         return {
111625             openTableWrap: function() {
111626                 return '<tpl for="chunks"><div class="' + Ext.baseCSSPrefix + 'grid-chunk" style="height: {chunkHeight}px;">';
111627             },
111628             closeTableWrap: function() {
111629                 return '</div></tpl>';
111630             }
111631         };
111632     }
111633 });
111634
111635 /**
111636  * @class Ext.grid.feature.Grouping
111637  * @extends Ext.grid.feature.Feature
111638  * 
111639  * This feature allows to display the grid rows aggregated into groups as specified by the {@link Ext.data.Store#groupers}
111640  * specified on the Store. The group will show the title for the group name and then the appropriate records for the group
111641  * underneath. The groups can also be expanded and collapsed.
111642  * 
111643  * ## Extra Events
111644  * This feature adds several extra events that will be fired on the grid to interact with the groups:
111645  *
111646  *  - {@link #groupclick}
111647  *  - {@link #groupdblclick}
111648  *  - {@link #groupcontextmenu}
111649  *  - {@link #groupexpand}
111650  *  - {@link #groupcollapse}
111651  * 
111652  * ## Menu Augmentation
111653  * This feature adds extra options to the grid column menu to provide the user with functionality to modify the grouping.
111654  * This can be disabled by setting the {@link #enableGroupingMenu} option. The option to disallow grouping from being turned off
111655  * by thew user is {@link #enableNoGroups}.
111656  * 
111657  * ## Controlling Group Text
111658  * The {@link #groupHeaderTpl} is used to control the rendered title for each group. It can modified to customized
111659  * the default display.
111660  * 
111661  * ## Example Usage
111662  * 
111663  *     var groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
111664  *         groupHeaderTpl: 'Group: {name} ({rows.length})', //print the number of items in the group
111665  *         startCollapsed: true // start all groups collapsed
111666  *     });
111667  * 
111668  * @ftype grouping
111669  * @author Nicolas Ferrero
111670  */
111671 Ext.define('Ext.grid.feature.Grouping', {
111672     extend: 'Ext.grid.feature.Feature',
111673     alias: 'feature.grouping',
111674
111675     eventPrefix: 'group',
111676     eventSelector: '.' + Ext.baseCSSPrefix + 'grid-group-hd',
111677
111678     constructor: function() {
111679         this.collapsedState = {};
111680         this.callParent(arguments);
111681     },
111682     
111683     /**
111684      * @event groupclick
111685      * @param {Ext.view.Table} view
111686      * @param {HTMLElement} node
111687      * @param {Number} unused
111688      * @param {Number} unused
111689      * @param {Ext.EventObject} e
111690      */
111691
111692     /**
111693      * @event groupdblclick
111694      * @param {Ext.view.Table} view
111695      * @param {HTMLElement} node
111696      * @param {Number} unused
111697      * @param {Number} unused
111698      * @param {Ext.EventObject} e
111699      */
111700
111701     /**
111702      * @event groupcontextmenu
111703      * @param {Ext.view.Table} view
111704      * @param {HTMLElement} node
111705      * @param {Number} unused
111706      * @param {Number} unused
111707      * @param {Ext.EventObject} e
111708      */
111709
111710     /**
111711      * @event groupcollapse
111712      * @param {Ext.view.Table} view
111713      * @param {HTMLElement} node
111714      * @param {Number} unused
111715      * @param {Number} unused
111716      * @param {Ext.EventObject} e
111717      */
111718
111719     /**
111720      * @event groupexpand
111721      * @param {Ext.view.Table} view
111722      * @param {HTMLElement} node
111723      * @param {Number} unused
111724      * @param {Number} unused
111725      * @param {Ext.EventObject} e
111726      */
111727
111728     /**
111729      * @cfg {String} groupHeaderTpl
111730      * Template snippet, this cannot be an actual template. {name} will be replaced with the current group.
111731      * Defaults to 'Group: {name}'
111732      */
111733     groupHeaderTpl: 'Group: {name}',
111734
111735     /**
111736      * @cfg {Number} depthToIndent
111737      * Number of pixels to indent per grouping level
111738      */
111739     depthToIndent: 17,
111740
111741     collapsedCls: Ext.baseCSSPrefix + 'grid-group-collapsed',
111742     hdCollapsedCls: Ext.baseCSSPrefix + 'grid-group-hd-collapsed',
111743
111744     /**
111745      * @cfg {String} groupByText Text displayed in the grid header menu for grouping by header
111746      * (defaults to 'Group By This Field').
111747      */
111748     groupByText : 'Group By This Field',
111749     /**
111750      * @cfg {String} showGroupsText Text displayed in the grid header for enabling/disabling grouping
111751      * (defaults to 'Show in Groups').
111752      */
111753     showGroupsText : 'Show in Groups',
111754
111755     /**
111756      * @cfg {Boolean} hideGroupedHeader<tt>true</tt> to hide the header that is currently grouped (defaults to <tt>false</tt>)
111757      */
111758     hideGroupedHeader : false,
111759
111760     /**
111761      * @cfg {Boolean} startCollapsed <tt>true</tt> to start all groups collapsed (defaults to <tt>false</tt>)
111762      */
111763     startCollapsed : false,
111764
111765     /**
111766      * @cfg {Boolean} enableGroupingMenu <tt>true</tt> to enable the grouping control in the header menu (defaults to <tt>true</tt>)
111767      */
111768     enableGroupingMenu : true,
111769
111770     /**
111771      * @cfg {Boolean} enableNoGroups <tt>true</tt> to allow the user to turn off grouping (defaults to <tt>true</tt>)
111772      */
111773     enableNoGroups : true,
111774     
111775     enable: function() {
111776         var me    = this,
111777             view  = me.view,
111778             store = view.store,
111779             groupToggleMenuItem;
111780             
111781         if (me.lastGroupIndex) {
111782             store.group(me.lastGroupIndex);
111783         }
111784         me.callParent();
111785         groupToggleMenuItem = me.view.headerCt.getMenu().down('#groupToggleMenuItem');
111786         groupToggleMenuItem.setChecked(true, true);
111787         view.refresh();
111788     },
111789
111790     disable: function() {
111791         var me    = this,
111792             view  = me.view,
111793             store = view.store,
111794             groupToggleMenuItem,
111795             lastGroup;
111796             
111797         lastGroup = store.groupers.first();
111798         if (lastGroup) {
111799             me.lastGroupIndex = lastGroup.property;
111800             store.groupers.clear();
111801         }
111802         
111803         me.callParent();
111804         groupToggleMenuItem = me.view.headerCt.getMenu().down('#groupToggleMenuItem');
111805         groupToggleMenuItem.setChecked(true, true);
111806         groupToggleMenuItem.setChecked(false, true);
111807         view.refresh();
111808     },
111809
111810     getFeatureTpl: function(values, parent, x, xcount) {
111811         var me = this;
111812         
111813         return [
111814             '<tpl if="typeof rows !== \'undefined\'">',
111815                 // group row tpl
111816                 '<tr class="' + Ext.baseCSSPrefix + 'grid-group-hd ' + (me.startCollapsed ? me.hdCollapsedCls : '') + ' {hdCollapsedCls}"><td class="' + Ext.baseCSSPrefix + 'grid-cell" colspan="' + parent.columns.length + '" {[this.indentByDepth(values)]}><div class="' + Ext.baseCSSPrefix + 'grid-cell-inner"><div class="' + Ext.baseCSSPrefix + 'grid-group-title">{collapsed}' + me.groupHeaderTpl + '</div></div></td></tr>',
111817                 // this is the rowbody
111818                 '<tr id="{viewId}-gp-{name}" class="' + Ext.baseCSSPrefix + 'grid-group-body ' + (me.startCollapsed ? me.collapsedCls : '') + ' {collapsedCls}"><td colspan="' + parent.columns.length + '">{[this.recurse(values)]}</td></tr>',
111819             '</tpl>'
111820         ].join('');
111821     },
111822
111823     getFragmentTpl: function() {
111824         return {
111825             indentByDepth: this.indentByDepth,
111826             depthToIndent: this.depthToIndent
111827         };
111828     },
111829
111830     indentByDepth: function(values) {
111831         var depth = values.depth || 0;
111832         return 'style="padding-left:'+ depth * this.depthToIndent + 'px;"';
111833     },
111834
111835     // Containers holding these components are responsible for
111836     // destroying them, we are just deleting references.
111837     destroy: function() {
111838         var me = this;
111839         
111840         delete me.view;
111841         delete me.prunedHeader;
111842     },
111843
111844     // perhaps rename to afterViewRender
111845     attachEvents: function() {
111846         var me = this,
111847             view = me.view,
111848             header, headerId, menu, menuItem;
111849
111850         view.on({
111851             scope: me,
111852             groupclick: me.onGroupClick,
111853             rowfocus: me.onRowFocus
111854         });
111855         view.store.on('groupchange', me.onGroupChange, me);
111856
111857         me.pruneGroupedHeader();
111858
111859         if (me.enableGroupingMenu) {
111860             me.injectGroupingMenu();
111861         }
111862
111863         if (me.hideGroupedHeader) {
111864             header = view.headerCt.down('gridcolumn[dataIndex=' + me.getGroupField() + ']');
111865             headerId = header.id;
111866             menu = view.headerCt.getMenu();
111867             menuItem = menu.down('menuitem[headerId='+ headerId +']');
111868             if (menuItem) {
111869                 menuItem.setChecked(false);
111870             }
111871         }
111872     },
111873     
111874     injectGroupingMenu: function() {
111875         var me       = this,
111876             view     = me.view,
111877             headerCt = view.headerCt;
111878         headerCt.showMenuBy = me.showMenuBy;
111879         headerCt.getMenuItems = me.getMenuItems();
111880     },
111881     
111882     showMenuBy: function(t, header) {
111883         var menu = this.getMenu(),
111884             groupMenuItem  = menu.down('#groupMenuItem'),
111885             groupableMth = header.groupable === false ?  'disable' : 'enable';
111886             
111887         groupMenuItem[groupableMth]();
111888         Ext.grid.header.Container.prototype.showMenuBy.apply(this, arguments);
111889     },
111890     
111891     getMenuItems: function() {
111892         var me                 = this,
111893             groupByText        = me.groupByText,
111894             disabled           = me.disabled,
111895             showGroupsText     = me.showGroupsText,
111896             enableNoGroups     = me.enableNoGroups,
111897             groupMenuItemClick = Ext.Function.bind(me.onGroupMenuItemClick, me),
111898             groupToggleMenuItemClick = Ext.Function.bind(me.onGroupToggleMenuItemClick, me)
111899         
111900         // runs in the scope of headerCt
111901         return function() {
111902             var o = Ext.grid.header.Container.prototype.getMenuItems.call(this);
111903             o.push('-', {
111904                 itemId: 'groupMenuItem',
111905                 text: groupByText,
111906                 handler: groupMenuItemClick
111907             });
111908             if (enableNoGroups) {
111909                 o.push({
111910                     itemId: 'groupToggleMenuItem',
111911                     text: showGroupsText,
111912                     checked: !disabled,
111913                     checkHandler: groupToggleMenuItemClick
111914                 });
111915             }
111916             return o;
111917         };
111918     },
111919
111920
111921     /**
111922      * Group by the header the user has clicked on.
111923      * @private
111924      */
111925     onGroupMenuItemClick: function(menuItem, e) {
111926         var menu = menuItem.parentMenu,
111927             hdr  = menu.activeHeader,
111928             view = this.view;
111929
111930         delete this.lastGroupIndex;
111931         this.enable();
111932         view.store.group(hdr.dataIndex);
111933         this.pruneGroupedHeader();
111934         
111935     },
111936
111937     /**
111938      * Turn on and off grouping via the menu
111939      * @private
111940      */
111941     onGroupToggleMenuItemClick: function(menuItem, checked) {
111942         this[checked ? 'enable' : 'disable']();
111943     },
111944
111945     /**
111946      * Prunes the grouped header from the header container
111947      * @private
111948      */
111949     pruneGroupedHeader: function() {
111950         var me         = this,
111951             view       = me.view,
111952             store      = view.store,
111953             groupField = me.getGroupField(),
111954             headerCt   = view.headerCt,
111955             header     = headerCt.down('header[dataIndex=' + groupField + ']');
111956
111957         if (header) {
111958             if (me.prunedHeader) {
111959                 me.prunedHeader.show();
111960             }
111961             me.prunedHeader = header;
111962             header.hide();
111963         }
111964     },
111965
111966     getGroupField: function(){
111967         var group = this.view.store.groupers.first();
111968         if (group) {
111969             return group.property;    
111970         }
111971         return ''; 
111972     },
111973
111974     /**
111975      * When a row gains focus, expand the groups above it
111976      * @private
111977      */
111978     onRowFocus: function(rowIdx) {
111979         var node    = this.view.getNode(rowIdx),
111980             groupBd = Ext.fly(node).up('.' + this.collapsedCls);
111981
111982         if (groupBd) {
111983             // for multiple level groups, should expand every groupBd
111984             // above
111985             this.expand(groupBd);
111986         }
111987     },
111988
111989     /**
111990      * Expand a group by the groupBody
111991      * @param {Ext.core.Element} groupBd
111992      * @private
111993      */
111994     expand: function(groupBd) {
111995         var me = this,
111996             view = me.view,
111997             grid = view.up('gridpanel'),
111998             groupBdDom = Ext.getDom(groupBd);
111999             
112000         me.collapsedState[groupBdDom.id] = false;
112001
112002         groupBd.removeCls(me.collapsedCls);
112003         groupBd.prev().removeCls(me.hdCollapsedCls);
112004
112005         grid.determineScrollbars();
112006         grid.invalidateScroller();
112007         view.fireEvent('groupexpand');
112008     },
112009
112010     /**
112011      * Collapse a group by the groupBody
112012      * @param {Ext.core.Element} groupBd
112013      * @private
112014      */
112015     collapse: function(groupBd) {
112016         var me = this,
112017             view = me.view,
112018             grid = view.up('gridpanel'),
112019             groupBdDom = Ext.getDom(groupBd);
112020             
112021         me.collapsedState[groupBdDom.id] = true;
112022
112023         groupBd.addCls(me.collapsedCls);
112024         groupBd.prev().addCls(me.hdCollapsedCls);
112025
112026         grid.determineScrollbars();
112027         grid.invalidateScroller();
112028         view.fireEvent('groupcollapse');
112029     },
112030     
112031     onGroupChange: function(){
112032         this.view.refresh();
112033     },
112034
112035     /**
112036      * Toggle between expanded/collapsed state when clicking on
112037      * the group.
112038      * @private
112039      */
112040     onGroupClick: function(view, group, idx, foo, e) {
112041         var me = this,
112042             toggleCls = me.toggleCls,
112043             groupBd = Ext.fly(group.nextSibling, '_grouping');
112044
112045         if (groupBd.hasCls(me.collapsedCls)) {
112046             me.expand(groupBd);
112047         } else {
112048             me.collapse(groupBd);
112049         }
112050     },
112051
112052     // Injects isRow and closeRow into the metaRowTpl.
112053     getMetaRowTplFragments: function() {
112054         return {
112055             isRow: this.isRow,
112056             closeRow: this.closeRow
112057         };
112058     },
112059
112060     // injected into rowtpl and wrapped around metaRowTpl
112061     // becomes part of the standard tpl
112062     isRow: function() {
112063         return '<tpl if="typeof rows === \'undefined\'">';
112064     },
112065
112066     // injected into rowtpl and wrapped around metaRowTpl
112067     // becomes part of the standard tpl
112068     closeRow: function() {
112069         return '</tpl>';
112070     },
112071
112072     // isRow and closeRow are injected via getMetaRowTplFragments
112073     mutateMetaRowTpl: function(metaRowTpl) {
112074         metaRowTpl.unshift('{[this.isRow()]}');
112075         metaRowTpl.push('{[this.closeRow()]}');
112076     },
112077
112078     // injects an additional style attribute via tdAttrKey with the proper
112079     // amount of padding
112080     getAdditionalData: function(data, idx, record, orig) {
112081         var view = this.view,
112082             hCt  = view.headerCt,
112083             col  = hCt.items.getAt(0),
112084             o = {},
112085             tdAttrKey = col.id + '-tdAttr';
112086
112087         // maintain the current tdAttr that a user may ahve set.
112088         o[tdAttrKey] = this.indentByDepth(data) + " " + (orig[tdAttrKey] ? orig[tdAttrKey] : '');
112089         o.collapsed = 'true';
112090         return o;
112091     },
112092
112093     // return matching preppedRecords
112094     getGroupRows: function(group, records, preppedRecords, fullWidth) {
112095         var me = this,
112096             children = group.children,
112097             rows = group.rows = [],
112098             view = me.view;
112099         group.viewId = view.id;
112100
112101         Ext.Array.each(records, function(record, idx) {
112102             if (Ext.Array.indexOf(children, record) != -1) {
112103                 rows.push(Ext.apply(preppedRecords[idx], {
112104                     depth: 1
112105                 }));
112106             }
112107         });
112108         delete group.children;
112109         group.fullWidth = fullWidth;
112110         if (me.collapsedState[view.id + '-gp-' + group.name]) {
112111             group.collapsedCls = me.collapsedCls;
112112             group.hdCollapsedCls = me.hdCollapsedCls;
112113         }
112114
112115         return group;
112116     },
112117
112118     // return the data in a grouped format.
112119     collectData: function(records, preppedRecords, startIndex, fullWidth, o) {
112120         var me    = this,
112121             store = me.view.store,
112122             groups;
112123             
112124         if (!me.disabled && store.isGrouped()) {
112125             groups = store.getGroups();
112126             Ext.Array.each(groups, function(group, idx){
112127                 me.getGroupRows(group, records, preppedRecords, fullWidth);
112128             }, me);
112129             return {
112130                 rows: groups,
112131                 fullWidth: fullWidth
112132             };
112133         }
112134         return o;
112135     },
112136     
112137     // adds the groupName to the groupclick, groupdblclick, groupcontextmenu
112138     // events that are fired on the view. Chose not to return the actual
112139     // group itself because of its expense and because developers can simply
112140     // grab the group via store.getGroups(groupName)
112141     getFireEventArgs: function(type, view, featureTarget) {
112142         var returnArray = [type, view, featureTarget],
112143             groupBd     = Ext.fly(featureTarget.nextSibling, '_grouping'),
112144             groupBdId   = Ext.getDom(groupBd).id,
112145             prefix      = view.id + '-gp-',
112146             groupName   = groupBdId.substr(prefix.length);
112147         
112148         returnArray.push(groupName);
112149         
112150         return returnArray;
112151     }
112152 });
112153
112154 /**
112155  * @class Ext.grid.feature.GroupingSummary
112156  * @extends Ext.grid.feature.Grouping
112157  * 
112158  * This feature adds an aggregate summary row at the bottom of each group that is provided
112159  * by the {@link Ext.grid.feature.Grouping} feature. There are 2 aspects to the summary:
112160  * 
112161  * ## Calculation
112162  * 
112163  * The summary value needs to be calculated for each column in the grid. This is controlled
112164  * by the summaryType option specified on the column. There are several built in summary types,
112165  * which can be specified as a string on the column configuration. These call underlying methods
112166  * on the store:
112167  *
112168  *  - {@link Ext.data.Store#count count}
112169  *  - {@link Ext.data.Store#sum sum}
112170  *  - {@link Ext.data.Store#min min}
112171  *  - {@link Ext.data.Store#max max}
112172  *  - {@link Ext.data.Store#average average}
112173  *
112174  * Alternatively, the summaryType can be a function definition. If this is the case,
112175  * the function is called with an array of records to calculate the summary value.
112176  * 
112177  * ## Rendering
112178  * 
112179  * Similar to a column, the summary also supports a summaryRenderer function. This
112180  * summaryRenderer is called before displaying a value. The function is optional, if
112181  * not specified the default calculated value is shown. The summaryRenderer is called with:
112182  *
112183  *  - value {Object} - The calculated value.
112184  *  - data {Object} - Contains all raw summary values for the row.
112185  *  - field {String} - The name of the field we are calculating
112186  * 
112187  * ## Example Usage
112188  *
112189  *     Ext.define('TestResult', {
112190  *         extend: 'Ext.data.Model',
112191  *         fields: ['student', 'subject', {
112192  *             name: 'mark',
112193  *             type: 'int'
112194  *         }]
112195  *     });
112196  *     
112197  *     Ext.create('Ext.grid.Panel', {
112198  *         width: 200,
112199  *         height: 240,
112200  *         renderTo: document.body,
112201  *         features: [{
112202  *             groupHeaderTpl: 'Subject: {name}',
112203  *             ftype: 'groupingsummary'
112204  *         }],
112205  *         store: {
112206  *             model: 'TestResult',
112207  *             groupField: 'subject',
112208  *             data: [{
112209  *                 student: 'Student 1',
112210  *                 subject: 'Math',
112211  *                 mark: 84
112212  *             },{
112213  *                 student: 'Student 1',
112214  *                 subject: 'Science',
112215  *                 mark: 72
112216  *             },{
112217  *                 student: 'Student 2',
112218  *                 subject: 'Math',
112219  *                 mark: 96
112220  *             },{
112221  *                 student: 'Student 2',
112222  *                 subject: 'Science',
112223  *                 mark: 68
112224  *             }]
112225  *         },
112226  *         columns: [{
112227  *             dataIndex: 'student',
112228  *             text: 'Name',
112229  *             summaryType: 'count',
112230  *             summaryRenderer: function(value){
112231  *                 return Ext.String.format('{0} student{1}', value, value !== 1 ? 's' : ''); 
112232  *             }
112233  *         }, {
112234  *             dataIndex: 'mark',
112235  *             text: 'Mark',
112236  *             summaryType: 'average'
112237  *         }]
112238  *     });
112239  */
112240 Ext.define('Ext.grid.feature.GroupingSummary', {
112241     
112242     /* Begin Definitions */
112243     
112244     extend: 'Ext.grid.feature.Grouping',
112245     
112246     alias: 'feature.groupingsummary',
112247     
112248     mixins: {
112249         summary: 'Ext.grid.feature.AbstractSummary'
112250     },
112251     
112252     /* End Definitions */
112253
112254      
112255    /**
112256     * Modifies the row template to include the summary row.
112257     * @private
112258     * @return {String} The modified template
112259     */
112260    getFeatureTpl: function() {
112261         var tpl = this.callParent(arguments);
112262             
112263         if (this.showSummaryRow) {
112264             // lop off the end </tpl> so we can attach it
112265             tpl = tpl.replace('</tpl>', '');
112266             tpl += '{[this.printSummaryRow(xindex)]}</tpl>';
112267         }
112268         return tpl;
112269     },
112270     
112271     /**
112272      * Gets any fragments needed for the template.
112273      * @private
112274      * @return {Object} The fragments
112275      */
112276     getFragmentTpl: function() {
112277         var me = this,
112278             fragments = me.callParent();
112279             
112280         Ext.apply(fragments, me.getSummaryFragments());
112281         if (me.showSummaryRow) {
112282             // this gets called before render, so we'll setup the data here.
112283             me.summaryGroups = me.view.store.getGroups();
112284             me.summaryData = me.generateSummaryData();
112285         }
112286         return fragments;
112287     },
112288     
112289     /**
112290      * Gets the data for printing a template row
112291      * @private
112292      * @param {Number} index The index in the template
112293      * @return {Array} The template values
112294      */
112295     getPrintData: function(index){
112296         var me = this,
112297             columns = me.view.headerCt.getColumnsForTpl(),
112298             i = 0,
112299             length = columns.length,
112300             data = [],
112301             name = me.summaryGroups[index - 1].name,
112302             active = me.summaryData[name],
112303             column;
112304             
112305         for (; i < length; ++i) {
112306             column = columns[i];
112307             column.gridSummaryValue = this.getColumnValue(column, active);
112308             data.push(column);
112309         }
112310         return data;
112311     },
112312     
112313     /**
112314      * Generates all of the summary data to be used when processing the template
112315      * @private
112316      * @return {Object} The summary data
112317      */
112318     generateSummaryData: function(){
112319         var me = this,
112320             data = {},
112321             remoteData = {},
112322             store = me.view.store,
112323             groupField = this.getGroupField(),
112324             reader = store.proxy.reader,
112325             groups = me.summaryGroups,
112326             columns = me.view.headerCt.getColumnsForTpl(),
112327             i,
112328             length,
112329             fieldData,
112330             root,
112331             key,
112332             comp;
112333             
112334         for (i = 0, length = groups.length; i < length; ++i) {
112335             data[groups[i].name] = {};
112336         }
112337         
112338     /**
112339      * @cfg {String} remoteRoot.  The name of the property
112340      * which contains the Array of summary objects.  Defaults to <tt>undefined</tt>.
112341      * It allows to use server-side calculated summaries.
112342      */
112343         if (me.remoteRoot && reader.rawData) {
112344             // reset reader root and rebuild extractors to extract summaries data
112345             root = reader.root;
112346             reader.root = me.remoteRoot;
112347             reader.buildExtractors(true);
112348             Ext.Array.each(reader.getRoot(reader.rawData), function(value) {
112349                  data[value[groupField]] = value;
112350                  data[value[groupField]]._remote = true;
112351             });
112352             // restore initial reader configuration
112353             reader.root = root;
112354             reader.buildExtractors(true);
112355         }
112356         
112357         for (i = 0, length = columns.length; i < length; ++i) {
112358             comp = Ext.getCmp(columns[i].id);
112359             fieldData = me.getSummary(store, comp.summaryType, comp.dataIndex, true);
112360             
112361             for (key in fieldData) {
112362                 if (fieldData.hasOwnProperty(key)) {
112363                     if (!data[key]._remote) {
112364                         data[key][comp.dataIndex] = fieldData[key];
112365                     }
112366                 }
112367             }
112368         }
112369         return data;
112370     }
112371 });
112372
112373 /**
112374  * @class Ext.grid.feature.RowBody
112375  * @extends Ext.grid.feature.Feature
112376  *
112377  * The rowbody feature enhances the grid's markup to have an additional
112378  * tr -> td -> div which spans the entire width of the original row.
112379  *
112380  * This is useful to to associate additional information with a particular
112381  * record in a grid.
112382  *
112383  * Rowbodies are initially hidden unless you override getAdditionalData.
112384  *
112385  * Will expose additional events on the gridview with the prefix of 'rowbody'.
112386  * For example: 'rowbodyclick', 'rowbodydblclick', 'rowbodycontextmenu'.
112387  *
112388  * @ftype rowbody
112389  */
112390 Ext.define('Ext.grid.feature.RowBody', {
112391     extend: 'Ext.grid.feature.Feature',
112392     alias: 'feature.rowbody',
112393     rowBodyHiddenCls: Ext.baseCSSPrefix + 'grid-row-body-hidden',
112394     rowBodyTrCls: Ext.baseCSSPrefix + 'grid-rowbody-tr',
112395     rowBodyTdCls: Ext.baseCSSPrefix + 'grid-cell-rowbody',
112396     rowBodyDivCls: Ext.baseCSSPrefix + 'grid-rowbody',
112397
112398     eventPrefix: 'rowbody',
112399     eventSelector: '.' + Ext.baseCSSPrefix + 'grid-rowbody-tr',
112400     
112401     getRowBody: function(values) {
112402         return [
112403             '<tr class="' + this.rowBodyTrCls + ' {rowBodyCls}">',
112404                 '<td class="' + this.rowBodyTdCls + '" colspan="{rowBodyColspan}">',
112405                     '<div class="' + this.rowBodyDivCls + '">{rowBody}</div>',
112406                 '</td>',
112407             '</tr>'
112408         ].join('');
112409     },
112410     
112411     // injects getRowBody into the metaRowTpl.
112412     getMetaRowTplFragments: function() {
112413         return {
112414             getRowBody: this.getRowBody,
112415             rowBodyTrCls: this.rowBodyTrCls,
112416             rowBodyTdCls: this.rowBodyTdCls,
112417             rowBodyDivCls: this.rowBodyDivCls
112418         };
112419     },
112420
112421     mutateMetaRowTpl: function(metaRowTpl) {
112422         metaRowTpl.push('{[this.getRowBody(values)]}');
112423     },
112424
112425     /**
112426      * Provide additional data to the prepareData call within the grid view.
112427      * The rowbody feature adds 3 additional variables into the grid view's template.
112428      * These are rowBodyCls, rowBodyColspan, and rowBody.
112429      * @param {Object} data The data for this particular record.
112430      * @param {Number} idx The row index for this record.
112431      * @param {Ext.data.Model} record The record instance
112432      * @param {Object} orig The original result from the prepareData call to massage.
112433      */
112434     getAdditionalData: function(data, idx, record, orig) {
112435         var headerCt = this.view.headerCt,
112436             colspan  = headerCt.getColumnCount();
112437
112438         return {
112439             rowBody: "",
112440             rowBodyCls: this.rowBodyCls,
112441             rowBodyColspan: colspan
112442         };
112443     }
112444 });
112445 /**
112446  * @class Ext.grid.feature.RowWrap
112447  * @extends Ext.grid.feature.Feature
112448  * @private
112449  */
112450 Ext.define('Ext.grid.feature.RowWrap', {
112451     extend: 'Ext.grid.feature.Feature',
112452     alias: 'feature.rowwrap',
112453
112454     // turn off feature events.
112455     hasFeatureEvent: false,
112456     
112457     mutateMetaRowTpl: function(metaRowTpl) {        
112458         // Remove "x-grid-row" from the first row, note this could be wrong
112459         // if some other feature unshifted things in front.
112460         metaRowTpl[0] = metaRowTpl[0].replace(Ext.baseCSSPrefix + 'grid-row', '');
112461         metaRowTpl[0] = metaRowTpl[0].replace("{[this.embedRowCls()]}", "");
112462         // 2
112463         metaRowTpl.unshift('<table class="' + Ext.baseCSSPrefix + 'grid-table ' + Ext.baseCSSPrefix + 'grid-table-resizer" style="width: {[this.embedFullWidth()]}px;">');
112464         // 1
112465         metaRowTpl.unshift('<tr class="' + Ext.baseCSSPrefix + 'grid-row {[this.embedRowCls()]}"><td colspan="{[this.embedColSpan()]}"><div class="' + Ext.baseCSSPrefix + 'grid-rowwrap-div">');
112466         
112467         // 3
112468         metaRowTpl.push('</table>');
112469         // 4
112470         metaRowTpl.push('</div></td></tr>');
112471     },
112472     
112473     embedColSpan: function() {
112474         return '{colspan}';
112475     },
112476     
112477     embedFullWidth: function() {
112478         return '{fullWidth}';
112479     },
112480     
112481     getAdditionalData: function(data, idx, record, orig) {
112482         var headerCt = this.view.headerCt,
112483             colspan  = headerCt.getColumnCount(),
112484             fullWidth = headerCt.getFullWidth(),
112485             items    = headerCt.query('gridcolumn'),
112486             itemsLn  = items.length,
112487             i = 0,
112488             o = {
112489                 colspan: colspan,
112490                 fullWidth: fullWidth
112491             },
112492             id,
112493             tdClsKey,
112494             colResizerCls;
112495
112496         for (; i < itemsLn; i++) {
112497             id = items[i].id;
112498             tdClsKey = id + '-tdCls';
112499             colResizerCls = Ext.baseCSSPrefix + 'grid-col-resizer-'+id;
112500             // give the inner td's the resizer class
112501             // while maintaining anything a user may have injected via a custom
112502             // renderer
112503             o[tdClsKey] = colResizerCls + " " + (orig[tdClsKey] ? orig[tdClsKey] : '');
112504             // TODO: Unhackify the initial rendering width's
112505             o[id+'-tdAttr'] = " style=\"width: " + (items[i].hidden ? 0 : items[i].getDesiredWidth()) + "px;\" "/* + (i === 0 ? " rowspan=\"2\"" : "")*/;
112506             if (orig[id+'-tdAttr']) {
112507                 o[id+'-tdAttr'] += orig[id+'-tdAttr'];
112508             }
112509             
112510         }
112511
112512         return o;
112513     },
112514     
112515     getMetaRowTplFragments: function() {
112516         return {
112517             embedFullWidth: this.embedFullWidth,
112518             embedColSpan: this.embedColSpan
112519         };
112520     }
112521     
112522 });
112523 /**
112524  * @class Ext.grid.feature.Summary
112525  * @extends Ext.grid.feature.AbstractSummary
112526  * 
112527  * This feature is used to place a summary row at the bottom of the grid. If using a grouping, 
112528  * see {@link Ext.grid.feature.GroupingSummary}. There are 2 aspects to calculating the summaries, 
112529  * calculation and rendering.
112530  * 
112531  * ## Calculation
112532  * The summary value needs to be calculated for each column in the grid. This is controlled
112533  * by the summaryType option specified on the column. There are several built in summary types,
112534  * which can be specified as a string on the column configuration. These call underlying methods
112535  * on the store:
112536  *
112537  *  - {@link Ext.data.Store#count count}
112538  *  - {@link Ext.data.Store#sum sum}
112539  *  - {@link Ext.data.Store#min min}
112540  *  - {@link Ext.data.Store#max max}
112541  *  - {@link Ext.data.Store#average average}
112542  *
112543  * Alternatively, the summaryType can be a function definition. If this is the case,
112544  * the function is called with an array of records to calculate the summary value.
112545  * 
112546  * ## Rendering
112547  * Similar to a column, the summary also supports a summaryRenderer function. This
112548  * summaryRenderer is called before displaying a value. The function is optional, if
112549  * not specified the default calculated value is shown. The summaryRenderer is called with:
112550  *
112551  *  - value {Object} - The calculated value.
112552  *  - data {Object} - Contains all raw summary values for the row.
112553  *  - field {String} - The name of the field we are calculating
112554  * 
112555  * ## Example Usage
112556  *
112557  *     Ext.define('TestResult', {
112558  *         extend: 'Ext.data.Model',
112559  *         fields: ['student', {
112560  *             name: 'mark',
112561  *             type: 'int'
112562  *         }]
112563  *     });
112564  *     
112565  *     Ext.create('Ext.grid.Panel', {
112566  *         width: 200,
112567  *         height: 140,
112568  *         renderTo: document.body,
112569  *         features: [{
112570  *             ftype: 'summary'
112571  *         }],
112572  *         store: {
112573  *             model: 'TestResult',
112574  *             data: [{
112575  *                 student: 'Student 1',
112576  *                 mark: 84
112577  *             },{
112578  *                 student: 'Student 2',
112579  *                 mark: 72
112580  *             },{
112581  *                 student: 'Student 3',
112582  *                 mark: 96
112583  *             },{
112584  *                 student: 'Student 4',
112585  *                 mark: 68
112586  *             }]
112587  *         },
112588  *         columns: [{
112589  *             dataIndex: 'student',
112590  *             text: 'Name',
112591  *             summaryType: 'count',
112592  *             summaryRenderer: function(value){
112593  *                 return Ext.String.format('{0} student{1}', value, value !== 1 ? 's' : ''); 
112594  *             }
112595  *         }, {
112596  *             dataIndex: 'mark',
112597  *             text: 'Mark',
112598  *             summaryType: 'average'
112599  *         }]
112600  *     });
112601  */
112602 Ext.define('Ext.grid.feature.Summary', {
112603     
112604     /* Begin Definitions */
112605     
112606     extend: 'Ext.grid.feature.AbstractSummary',
112607     
112608     alias: 'feature.summary',
112609     
112610     /* End Definitions */
112611     
112612     /**
112613      * Gets any fragments needed for the template.
112614      * @private
112615      * @return {Object} The fragments
112616      */
112617     getFragmentTpl: function() {
112618         // this gets called before render, so we'll setup the data here.
112619         this.summaryData = this.generateSummaryData(); 
112620         return this.getSummaryFragments();
112621     },
112622     
112623     /**
112624      * Overrides the closeRows method on the template so we can include our own custom
112625      * footer.
112626      * @private
112627      * @return {Object} The custom fragments
112628      */
112629     getTableFragments: function(){
112630         if (this.showSummaryRow) {
112631             return {
112632                 closeRows: this.closeRows
112633             };
112634         }
112635     },
112636     
112637     /**
112638      * Provide our own custom footer for the grid.
112639      * @private
112640      * @return {String} The custom footer
112641      */
112642     closeRows: function() {
112643         return '</tpl>{[this.printSummaryRow()]}';
112644     },
112645     
112646     /**
112647      * Gets the data for printing a template row
112648      * @private
112649      * @param {Number} index The index in the template
112650      * @return {Array} The template values
112651      */
112652     getPrintData: function(index){
112653         var me = this,
112654             columns = me.view.headerCt.getColumnsForTpl(),
112655             i = 0,
112656             length = columns.length,
112657             data = [],
112658             active = me.summaryData,
112659             column;
112660             
112661         for (; i < length; ++i) {
112662             column = columns[i];
112663             column.gridSummaryValue = this.getColumnValue(column, active);
112664             data.push(column);
112665         }
112666         return data;
112667     },
112668     
112669     /**
112670      * Generates all of the summary data to be used when processing the template
112671      * @private
112672      * @return {Object} The summary data
112673      */
112674     generateSummaryData: function(){
112675         var me = this,
112676             data = {},
112677             store = me.view.store,
112678             columns = me.view.headerCt.getColumnsForTpl(),
112679             i = 0,
112680             length = columns.length,
112681             fieldData,
112682             key,
112683             comp;
112684             
112685         for (i = 0, length = columns.length; i < length; ++i) {
112686             comp = Ext.getCmp(columns[i].id);
112687             data[comp.dataIndex] = me.getSummary(store, comp.summaryType, comp.dataIndex, false);
112688         }
112689         return data;
112690     }
112691 });
112692 /**
112693  * @class Ext.grid.header.DragZone
112694  * @extends Ext.dd.DragZone
112695  * @private
112696  */
112697 Ext.define('Ext.grid.header.DragZone', {
112698     extend: 'Ext.dd.DragZone',
112699     colHeaderCls: Ext.baseCSSPrefix + 'column-header',
112700     maxProxyWidth: 120,
112701
112702     constructor: function(headerCt) {
112703         this.headerCt = headerCt;
112704         this.ddGroup =  this.getDDGroup();
112705         this.callParent([headerCt.el]);
112706         this.proxy.el.addCls(Ext.baseCSSPrefix + 'grid-col-dd');
112707     },
112708
112709     getDDGroup: function() {
112710         return 'header-dd-zone-' + this.headerCt.up('[scrollerOwner]').id;
112711     },
112712
112713     getDragData: function(e) {
112714         var header = e.getTarget('.'+this.colHeaderCls),
112715             headerCmp;
112716
112717         if (header) {
112718             headerCmp = Ext.getCmp(header.id);
112719             if (!this.headerCt.dragging && headerCmp.draggable && !(headerCmp.isOnLeftEdge(e) || headerCmp.isOnRightEdge(e))) {
112720                 var ddel = document.createElement('div');
112721                 ddel.innerHTML = Ext.getCmp(header.id).text;
112722                 return {
112723                     ddel: ddel,
112724                     header: headerCmp
112725                 };
112726             }
112727         }
112728         return false;
112729     },
112730
112731     onBeforeDrag: function() {
112732         return !(this.headerCt.dragging || this.disabled);
112733     },
112734
112735     onInitDrag: function() {
112736         this.headerCt.dragging = true;
112737         this.callParent(arguments);
112738     },
112739
112740     onDragDrop: function() {
112741         this.headerCt.dragging = false;
112742         this.callParent(arguments);
112743     },
112744
112745     afterRepair: function() {
112746         this.callParent();
112747         this.headerCt.dragging = false;
112748     },
112749
112750     getRepairXY: function() {
112751         return this.dragData.header.el.getXY();
112752     },
112753     
112754     disable: function() {
112755         this.disabled = true;
112756     },
112757     
112758     enable: function() {
112759         this.disabled = false;
112760     }
112761 });
112762
112763 /**
112764  * @class Ext.grid.header.DropZone
112765  * @extends Ext.dd.DropZone
112766  * @private
112767  */
112768 Ext.define('Ext.grid.header.DropZone', {
112769     extend: 'Ext.dd.DropZone',
112770     colHeaderCls: Ext.baseCSSPrefix + 'column-header',
112771     proxyOffsets: [-4, -9],
112772
112773     constructor: function(headerCt){
112774         this.headerCt = headerCt;
112775         this.ddGroup = this.getDDGroup();
112776         this.callParent([headerCt.el]);
112777     },
112778
112779     getDDGroup: function() {
112780         return 'header-dd-zone-' + this.headerCt.up('[scrollerOwner]').id;
112781     },
112782
112783     getTargetFromEvent : function(e){
112784         return e.getTarget('.' + this.colHeaderCls);
112785     },
112786
112787     getTopIndicator: function() {
112788         if (!this.topIndicator) {
112789             this.topIndicator = Ext.core.DomHelper.append(Ext.getBody(), {
112790                 cls: "col-move-top",
112791                 html: "&#160;"
112792             }, true);
112793         }
112794         return this.topIndicator;
112795     },
112796
112797     getBottomIndicator: function() {
112798         if (!this.bottomIndicator) {
112799             this.bottomIndicator = Ext.core.DomHelper.append(Ext.getBody(), {
112800                 cls: "col-move-bottom",
112801                 html: "&#160;"
112802             }, true);
112803         }
112804         return this.bottomIndicator;
112805     },
112806
112807     getLocation: function(e, t) {
112808         var x      = e.getXY()[0],
112809             region = Ext.fly(t).getRegion(),
112810             pos, header;
112811
112812         if ((region.right - x) <= (region.right - region.left) / 2) {
112813             pos = "after";
112814         } else {
112815             pos = "before";
112816         }
112817         return {
112818             pos: pos,
112819             header: Ext.getCmp(t.id),
112820             node: t
112821         };
112822     },
112823
112824     positionIndicator: function(draggedHeader, node, e){
112825         var location = this.getLocation(e, node),
112826             header = location.header,
112827             pos    = location.pos,
112828             nextHd = draggedHeader.nextSibling('gridcolumn:not([hidden])'),
112829             prevHd = draggedHeader.previousSibling('gridcolumn:not([hidden])'),
112830             region, topIndicator, bottomIndicator, topAnchor, bottomAnchor,
112831             topXY, bottomXY, headerCtEl, minX, maxX;
112832
112833         // Cannot drag beyond non-draggable start column
112834         if (!header.draggable && header.getIndex() == 0) {
112835             return false;
112836         }
112837
112838         this.lastLocation = location;
112839
112840         if ((draggedHeader !== header) &&
112841             ((pos === "before" && nextHd !== header) ||
112842             (pos === "after" && prevHd !== header)) &&
112843             !header.isDescendantOf(draggedHeader)) {
112844
112845             // As we move in between different DropZones that are in the same
112846             // group (such as the case when in a locked grid), invalidateDrop
112847             // on the other dropZones.
112848             var allDropZones = Ext.dd.DragDropManager.getRelated(this),
112849                 ln = allDropZones.length,
112850                 i  = 0,
112851                 dropZone;
112852
112853             for (; i < ln; i++) {
112854                 dropZone = allDropZones[i];
112855                 if (dropZone !== this && dropZone.invalidateDrop) {
112856                     dropZone.invalidateDrop();
112857                 }
112858             }
112859
112860
112861             this.valid = true;
112862             topIndicator = this.getTopIndicator();
112863             bottomIndicator = this.getBottomIndicator();
112864             if (pos === 'before') {
112865                 topAnchor = 'tl';
112866                 bottomAnchor = 'bl';
112867             } else {
112868                 topAnchor = 'tr';
112869                 bottomAnchor = 'br';
112870             }
112871             topXY = header.el.getAnchorXY(topAnchor);
112872             bottomXY = header.el.getAnchorXY(bottomAnchor);
112873
112874             // constrain the indicators to the viewable section
112875             headerCtEl = this.headerCt.el;
112876             minX = headerCtEl.getLeft();
112877             maxX = headerCtEl.getRight();
112878
112879             topXY[0] = Ext.Number.constrain(topXY[0], minX, maxX);
112880             bottomXY[0] = Ext.Number.constrain(bottomXY[0], minX, maxX);
112881
112882             // adjust by offsets, this is to center the arrows so that they point
112883             // at the split point
112884             topXY[0] -= 4;
112885             topXY[1] -= 9;
112886             bottomXY[0] -= 4;
112887
112888             // position and show indicators
112889             topIndicator.setXY(topXY);
112890             bottomIndicator.setXY(bottomXY);
112891             topIndicator.show();
112892             bottomIndicator.show();
112893         // invalidate drop operation and hide indicators
112894         } else {
112895             this.invalidateDrop();
112896         }
112897     },
112898
112899     invalidateDrop: function() {
112900         this.valid = false;
112901         this.hideIndicators();
112902     },
112903
112904     onNodeOver: function(node, dragZone, e, data) {
112905         if (data.header.el.dom !== node) {
112906             this.positionIndicator(data.header, node, e);
112907         }
112908         return this.valid ? this.dropAllowed : this.dropNotAllowed;
112909     },
112910
112911     hideIndicators: function() {
112912         this.getTopIndicator().hide();
112913         this.getBottomIndicator().hide();
112914     },
112915
112916     onNodeOut: function() {
112917         this.hideIndicators();
112918     },
112919
112920     onNodeDrop: function(node, dragZone, e, data) {
112921         if (this.valid) {
112922             this.invalidateDrop();
112923             var hd = data.header,
112924                 lastLocation = this.lastLocation,
112925                 fromCt  = hd.ownerCt,
112926                 fromIdx = fromCt.items.indexOf(hd), // Container.items is a MixedCollection
112927                 toCt    = lastLocation.header.ownerCt,
112928                 toIdx   = toCt.items.indexOf(lastLocation.header),
112929                 headerCt = this.headerCt,
112930                 groupCt,
112931                 scrollerOwner;
112932
112933             if (lastLocation.pos === 'after') {
112934                 toIdx++;
112935             }
112936
112937             // If we are dragging in between two HeaderContainers that have had the lockable
112938             // mixin injected we will lock/unlock headers in between sections. Note that lockable
112939             // does NOT currently support grouped headers.
112940             if (fromCt !== toCt && fromCt.lockableInjected && toCt.lockableInjected && toCt.lockedCt) {
112941                 scrollerOwner = fromCt.up('[scrollerOwner]');
112942                 scrollerOwner.lock(hd, toIdx);
112943             } else if (fromCt !== toCt && fromCt.lockableInjected && toCt.lockableInjected && fromCt.lockedCt) {
112944                 scrollerOwner = fromCt.up('[scrollerOwner]');
112945                 scrollerOwner.unlock(hd, toIdx);
112946             } else {
112947                 // If dragging rightwards, then after removal, the insertion index will be one less when moving
112948                 // in between the same container.
112949                 if ((fromCt === toCt) && (toIdx > fromCt.items.indexOf(hd))) {
112950                     toIdx--;
112951                 }
112952
112953                 // Remove dragged header from where it was without destroying it or relaying its Container
112954                 if (fromCt !== toCt) {
112955                     fromCt.suspendLayout = true;
112956                     fromCt.remove(hd, false);
112957                     fromCt.suspendLayout = false;
112958                 }
112959
112960                 // Dragged the last header out of the fromCt group... The fromCt group must die
112961                 if (fromCt.isGroupHeader) {
112962                     if (!fromCt.items.getCount()) {
112963                         groupCt = fromCt.ownerCt;
112964                         groupCt.suspendLayout = true;
112965                         groupCt.remove(fromCt, false);
112966                         fromCt.el.dom.parentNode.removeChild(fromCt.el.dom);
112967                         groupCt.suspendLayout = false;
112968                     } else {
112969                         fromCt.minWidth = fromCt.getWidth() - hd.getWidth();
112970                         fromCt.setWidth(fromCt.minWidth);
112971                     }
112972                 }
112973
112974                 // Move dragged header into its drop position
112975                 toCt.suspendLayout = true;
112976                 if (fromCt === toCt) {
112977                     toCt.move(fromIdx, toIdx);
112978                 } else {
112979                     toCt.insert(toIdx, hd);
112980                 }
112981                 toCt.suspendLayout = false;
112982
112983                 // Group headers acquire the aggregate width of their child headers
112984                 // Therefore a child header may not flex; it must contribute a fixed width.
112985                 // But we restore the flex value when moving back into the main header container
112986                 if (toCt.isGroupHeader) {
112987                     hd.savedFlex = hd.flex;
112988                     delete hd.flex;
112989                     hd.width = hd.getWidth();
112990                     // When there was previously a flex, we need to ensure we don't count for the
112991                     // border twice.
112992                     toCt.minWidth = toCt.getWidth() + hd.getWidth() - (hd.savedFlex ? 1 : 0);
112993                     toCt.setWidth(toCt.minWidth);
112994                 } else {
112995                     if (hd.savedFlex) {
112996                         hd.flex = hd.savedFlex;
112997                         delete hd.width;
112998                     }
112999                 }
113000
113001
113002                 // Refresh columns cache in case we remove an emptied group column
113003                 headerCt.purgeCache();
113004                 headerCt.doLayout();
113005                 headerCt.onHeaderMoved(hd, fromIdx, toIdx);
113006                 // Emptied group header can only be destroyed after the header and grid have been refreshed
113007                 if (!fromCt.items.getCount()) {
113008                     fromCt.destroy();
113009                 }
113010             }
113011         }
113012     }
113013 });
113014
113015
113016 /**
113017  * @class Ext.grid.plugin.Editing
113018
113019 This class provides an abstract grid editing plugin on selected {@link Ext.grid.column.Column columns}.
113020 The editable columns are specified by providing an {@link Ext.grid.column.Column#editor editor}
113021 in the {@link Ext.grid.column.Column column configuration}.
113022
113023 *Note:* This class should not be used directly. See {@link Ext.grid.plugin.CellEditing} and
113024 {@link Ext.grid.plugin.RowEditing}.
113025
113026  * @markdown
113027  */
113028 Ext.define('Ext.grid.plugin.Editing', {
113029     alias: 'editing.editing',
113030
113031     requires: [
113032         'Ext.grid.column.Column',
113033         'Ext.util.KeyNav'
113034     ],
113035
113036     mixins: {
113037         observable: 'Ext.util.Observable'
113038     },
113039
113040     /**
113041      * @cfg {Number} clicksToEdit
113042      * The number of clicks on a grid required to display the editor (defaults to 2).
113043      */
113044     clicksToEdit: 2,
113045
113046     // private
113047     defaultFieldXType: 'textfield',
113048
113049     // cell, row, form
113050     editStyle: '',
113051
113052     constructor: function(config) {
113053         var me = this;
113054         Ext.apply(me, config);
113055
113056         me.addEvents(
113057             // Doc'ed in separate editing plugins
113058             'beforeedit',
113059
113060             // Doc'ed in separate editing plugins
113061             'edit',
113062
113063             // Doc'ed in separate editing plugins
113064             'validateedit'
113065         );
113066         me.mixins.observable.constructor.call(me);
113067         // TODO: Deprecated, remove in 5.0
113068         me.relayEvents(me, ['afteredit'], 'after');
113069     },
113070
113071     // private
113072     init: function(grid) {
113073         var me = this;
113074
113075         me.grid = grid;
113076         me.view = grid.view;
113077         me.initEvents();
113078         me.initFieldAccessors(me.view.getGridColumns());
113079
113080         grid.relayEvents(me, ['beforeedit', 'edit', 'validateedit']);
113081         // Marks the grid as editable, so that the SelectionModel
113082         // can make appropriate decisions during navigation
113083         grid.isEditable = true;
113084         grid.editingPlugin = grid.view.editingPlugin = me;
113085     },
113086
113087     /**
113088      * @private
113089      * AbstractComponent calls destroy on all its plugins at destroy time.
113090      */
113091     destroy: function() {
113092         var me = this,
113093             grid = me.grid,
113094             headerCt = grid.headerCt,
113095             events = grid.events;
113096
113097         Ext.destroy(me.keyNav);
113098         me.removeFieldAccessors(grid.getView().getGridColumns());
113099
113100         // Clear all listeners from all our events, clear all managed listeners we added to other Observables
113101         me.clearListeners();
113102
113103         delete me.grid.editingPlugin;
113104         delete me.grid.view.editingPlugin;
113105         delete me.grid;
113106         delete me.view;
113107         delete me.editor;
113108         delete me.keyNav;
113109     },
113110
113111     // private
113112     getEditStyle: function() {
113113         return this.editStyle;
113114     },
113115
113116     // private
113117     initFieldAccessors: function(column) {
113118         var me = this;
113119
113120         if (Ext.isArray(column)) {
113121             Ext.Array.forEach(column, me.initFieldAccessors, me);
113122             return;
113123         }
113124
113125         // Augment the Header class to have a getEditor and setEditor method
113126         // Important: Only if the header does not have its own implementation.
113127         Ext.applyIf(column, {
113128             getEditor: function(record, defaultField) {
113129                 return me.getColumnField(this, defaultField);
113130             },
113131
113132             setEditor: function(field) {
113133                 me.setColumnField(this, field);
113134             }
113135         });
113136     },
113137
113138     // private
113139     removeFieldAccessors: function(column) {
113140         var me = this;
113141
113142         if (Ext.isArray(column)) {
113143             Ext.Array.forEach(column, me.removeFieldAccessors, me);
113144             return;
113145         }
113146
113147         delete column.getEditor;
113148         delete column.setEditor;
113149     },
113150
113151     // private
113152     // remaps to the public API of Ext.grid.column.Column.getEditor
113153     getColumnField: function(columnHeader, defaultField) {
113154         var field = columnHeader.field;
113155
113156         if (!field && columnHeader.editor) {
113157             field = columnHeader.editor;
113158             delete columnHeader.editor;
113159         }
113160
113161         if (!field && defaultField) {
113162             field = defaultField;
113163         }
113164
113165         if (field) {
113166             if (Ext.isString(field)) {
113167                 field = { xtype: field };
113168             }
113169             if (Ext.isObject(field) && !field.isFormField) {
113170                 field = Ext.ComponentManager.create(field, this.defaultFieldXType);
113171                 columnHeader.field = field;
113172             }
113173
113174             Ext.apply(field, {
113175                 name: columnHeader.dataIndex
113176             });
113177
113178             return field;
113179         }
113180     },
113181
113182     // private
113183     // remaps to the public API of Ext.grid.column.Column.setEditor
113184     setColumnField: function(column, field) {
113185         if (Ext.isObject(field) && !field.isFormField) {
113186             field = Ext.ComponentManager.create(field, this.defaultFieldXType);
113187         }
113188         column.field = field;
113189     },
113190
113191     // private
113192     initEvents: function() {
113193         var me = this;
113194         me.initEditTriggers();
113195         me.initCancelTriggers();
113196     },
113197
113198     // @abstract
113199     initCancelTriggers: Ext.emptyFn,
113200
113201     // private
113202     initEditTriggers: function() {
113203         var me = this,
113204             view = me.view,
113205             clickEvent = me.clicksToEdit === 1 ? 'click' : 'dblclick';
113206
113207         // Start editing
113208         me.mon(view, 'cell' + clickEvent, me.startEditByClick, me);
113209         view.on('render', function() {
113210             me.keyNav = Ext.create('Ext.util.KeyNav', view.el, {
113211                 enter: me.onEnterKey,
113212                 esc: me.onEscKey,
113213                 scope: me
113214             });
113215         }, me, { single: true });
113216     },
113217
113218     // private
113219     onEnterKey: function(e) {
113220         var me = this,
113221             grid = me.grid,
113222             selModel = grid.getSelectionModel(),
113223             record,
113224             columnHeader = grid.headerCt.getHeaderAtIndex(0);
113225
113226         // Calculate editing start position from SelectionModel
113227         // CellSelectionModel
113228         if (selModel.getCurrentPosition) {
113229             pos = selModel.getCurrentPosition();
113230             record = grid.store.getAt(pos.row);
113231             columnHeader = grid.headerCt.getHeaderAtIndex(pos.column);
113232         }
113233         // RowSelectionModel
113234         else {
113235             record = selModel.getLastSelected();
113236         }
113237         me.startEdit(record, columnHeader);
113238     },
113239
113240     // private
113241     onEscKey: function(e) {
113242         this.cancelEdit();
113243     },
113244
113245     // private
113246     startEditByClick: function(view, cell, colIdx, record, row, rowIdx, e) {
113247         this.startEdit(record, view.getHeaderAtIndex(colIdx));
113248     },
113249
113250     /**
113251      * @private
113252      * @abstract. Template method called before editing begins.
113253      * @param {Object} context The current editing context
113254      * @return {Boolean} Return false to cancel the editing process
113255      */
113256     beforeEdit: Ext.emptyFn,
113257
113258     /**
113259      * Start editing the specified record, using the specified Column definition to define which field is being edited.
113260      * @param {Model} record The Store data record which backs the row to be edited.
113261      * @param {Model} columnHeader The Column object defining the column to be edited.
113262      */
113263     startEdit: function(record, columnHeader) {
113264         var me = this,
113265             context = me.getEditingContext(record, columnHeader);
113266
113267         if (me.beforeEdit(context) === false || me.fireEvent('beforeedit', context) === false || context.cancel) {
113268             return false;
113269         }
113270
113271         me.context = context;
113272         me.editing = true;
113273     },
113274
113275     /**
113276      * @private Collects all information necessary for any subclasses to perform their editing functions.
113277      * @param record
113278      * @param columnHeader
113279      * @returns {Object} The editing context based upon the passed record and column
113280      */
113281     getEditingContext: function(record, columnHeader) {
113282         var me = this,
113283             grid = me.grid,
113284             store = grid.store,
113285             rowIdx,
113286             colIdx,
113287             view = grid.getView(),
113288             value;
113289
113290         // If they'd passed numeric row, column indices, look them up.
113291         if (Ext.isNumber(record)) {
113292             rowIdx = record;
113293             record = store.getAt(rowIdx);
113294         } else {
113295             rowIdx = store.indexOf(record);
113296         }
113297         if (Ext.isNumber(columnHeader)) {
113298             colIdx = columnHeader;
113299             columnHeader = grid.headerCt.getHeaderAtIndex(colIdx);
113300         } else {
113301             colIdx = columnHeader.getIndex();
113302         }
113303
113304         value = record.get(columnHeader.dataIndex);
113305         return {
113306             grid: grid,
113307             record: record,
113308             field: columnHeader.dataIndex,
113309             value: value,
113310             row: view.getNode(rowIdx),
113311             column: columnHeader,
113312             rowIdx: rowIdx,
113313             colIdx: colIdx
113314         };
113315     },
113316
113317     /**
113318      * Cancel any active edit that is in progress.
113319      */
113320     cancelEdit: function() {
113321         this.editing = false;
113322     },
113323
113324     /**
113325      * Complete the edit if there is an active edit in progress.
113326      */
113327     completeEdit: function() {
113328         var me = this;
113329
113330         if (me.editing && me.validateEdit()) {
113331             me.fireEvent('edit', me.context);
113332         }
113333
113334         delete me.context;
113335         me.editing = false;
113336     },
113337
113338     // @abstract
113339     validateEdit: function() {
113340         var me = this,
113341             context = me.context;
113342
113343         return me.fireEvent('validateedit', me, context) !== false && !context.cancel;
113344     }
113345 });
113346 /**
113347  * @class Ext.grid.plugin.CellEditing
113348  * @extends Ext.grid.plugin.Editing
113349  *
113350  * The Ext.grid.plugin.CellEditing plugin injects editing at a cell level for a Grid. Only a single
113351  * cell will be editable at a time. The field that will be used for the editor is defined at the
113352  * {@link Ext.grid.column.Column#field field}. The editor can be a field instance or a field configuration.
113353  *
113354  * If an editor is not specified for a particular column then that cell will not be editable and it will
113355  * be skipped when activated via the mouse or the keyboard.
113356  *
113357  * The editor may be shared for each column in the grid, or a different one may be specified for each column.
113358  * An appropriate field type should be chosen to match the data structure that it will be editing. For example,
113359  * to edit a date, it would be useful to specify {@link Ext.form.field.Date} as the editor.
113360  *
113361  * {@img Ext.grid.plugin.CellEditing/Ext.grid.plugin.CellEditing.png Ext.grid.plugin.CellEditing plugin}
113362  *
113363  * ## Example Usage
113364  *    Ext.create('Ext.data.Store', {
113365  *        storeId:'simpsonsStore',
113366  *        fields:['name', 'email', 'phone'],
113367  *        data:{'items':[
113368  *            {"name":"Lisa", "email":"lisa@simpsons.com", "phone":"555-111-1224"},
113369  *            {"name":"Bart", "email":"bart@simpsons.com", "phone":"555--222-1234"},
113370  *            {"name":"Homer", "email":"home@simpsons.com", "phone":"555-222-1244"},
113371  *            {"name":"Marge", "email":"marge@simpsons.com", "phone":"555-222-1254"}
113372  *        ]},
113373  *        proxy: {
113374  *            type: 'memory',
113375  *            reader: {
113376  *                type: 'json',
113377  *                root: 'items'
113378  *            }
113379  *        }
113380  *    });
113381  *
113382  *    Ext.create('Ext.grid.Panel', {
113383  *        title: 'Simpsons',
113384  *        store: Ext.data.StoreManager.lookup('simpsonsStore'),
113385  *        columns: [
113386  *            {header: 'Name',  dataIndex: 'name', field: 'textfield'},
113387  *            {header: 'Email', dataIndex: 'email', flex:1,
113388  *                editor: {
113389  *                    xtype:'textfield',
113390  *                    allowBlank:false
113391  *                }
113392  *            },
113393  *            {header: 'Phone', dataIndex: 'phone'}
113394  *        ],
113395  *        selType: 'cellmodel',
113396  *        plugins: [
113397  *            Ext.create('Ext.grid.plugin.CellEditing', {
113398  *                clicksToEdit: 1
113399  *            })
113400  *        ],
113401  *        height: 200,
113402  *        width: 400,
113403  *        renderTo: Ext.getBody()
113404  *    });
113405  *
113406  */
113407 Ext.define('Ext.grid.plugin.CellEditing', {
113408     alias: 'plugin.cellediting',
113409     extend: 'Ext.grid.plugin.Editing',
113410     requires: ['Ext.grid.CellEditor'],
113411
113412     constructor: function() {
113413         /**
113414          * @event beforeedit
113415          * Fires before cell editing is triggered. The edit event object has the following properties <br />
113416          * <ul style="padding:5px;padding-left:16px;">
113417          * <li>grid - The grid</li>
113418          * <li>record - The record being edited</li>
113419          * <li>field - The field name being edited</li>
113420          * <li>value - The value for the field being edited.</li>
113421          * <li>row - The grid table row</li>
113422          * <li>column - The grid {@link Ext.grid.column.Column Column} defining the column that is being edited.</li>
113423          * <li>rowIdx - The row index that is being edited</li>
113424          * <li>colIdx - The column index that is being edited</li>
113425          * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
113426          * </ul>
113427          * @param {Ext.grid.plugin.Editing} editor
113428          * @param {Object} e An edit event (see above for description)
113429          */
113430         /**
113431          * @event edit
113432          * Fires after a cell is edited. The edit event object has the following properties <br />
113433          * <ul style="padding:5px;padding-left:16px;">
113434          * <li>grid - The grid</li>
113435          * <li>record - The record that was edited</li>
113436          * <li>field - The field name that was edited</li>
113437          * <li>value - The value being set</li>
113438          * <li>originalValue - The original value for the field, before the edit.</li>
113439          * <li>row - The grid table row</li>
113440          * <li>column - The grid {@link Ext.grid.column.Column Column} defining the column that was edited.</li>
113441          * <li>rowIdx - The row index that was edited</li>
113442          * <li>colIdx - The column index that was edited</li>
113443          * </ul>
113444          *
113445          * <pre><code>
113446 grid.on('edit', onEdit, this);
113447
113448 function onEdit(e) {
113449     // execute an XHR to send/commit data to the server, in callback do (if successful):
113450     e.record.commit();
113451 };
113452          * </code></pre>
113453          * @param {Ext.grid.plugin.Editing} editor
113454          * @param {Object} e An edit event (see above for description)
113455          */
113456         /**
113457          * @event validateedit
113458          * Fires after a cell is edited, but before the value is set in the record. Return false
113459          * to cancel the change. The edit event object has the following properties <br />
113460          * <ul style="padding:5px;padding-left:16px;">
113461          * <li>grid - The grid</li>
113462          * <li>record - The record being edited</li>
113463          * <li>field - The field name being edited</li>
113464          * <li>value - The value being set</li>
113465          * <li>originalValue - The original value for the field, before the edit.</li>
113466          * <li>row - The grid table row</li>
113467          * <li>column - The grid {@link Ext.grid.column.Column Column} defining the column that is being edited.</li>
113468          * <li>rowIdx - The row index that is being edited</li>
113469          * <li>colIdx - The column index that is being edited</li>
113470          * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
113471          * </ul>
113472          * Usage example showing how to remove the red triangle (dirty record indicator) from some
113473          * records (not all).  By observing the grid's validateedit event, it can be cancelled if
113474          * the edit occurs on a targeted row (for example) and then setting the field's new value
113475          * in the Record directly:
113476          * <pre><code>
113477 grid.on('validateedit', function(e) {
113478   var myTargetRow = 6;
113479
113480   if (e.row == myTargetRow) {
113481     e.cancel = true;
113482     e.record.data[e.field] = e.value;
113483   }
113484 });
113485          * </code></pre>
113486          * @param {Ext.grid.plugin.Editing} editor
113487          * @param {Object} e An edit event (see above for description)
113488          */
113489         this.callParent(arguments);
113490         this.editors = Ext.create('Ext.util.MixedCollection', false, function(editor) {
113491             return editor.editorId;
113492         });
113493     },
113494
113495     /**
113496      * @private
113497      * AbstractComponent calls destroy on all its plugins at destroy time.
113498      */
113499     destroy: function() {
113500         var me = this;
113501         me.editors.each(Ext.destroy, Ext);
113502         me.editors.clear();
113503         me.callParent(arguments);
113504     },
113505
113506     // private
113507     // Template method called from base class's initEvents
113508     initCancelTriggers: function() {
113509         var me   = this;
113510             grid = me.grid,
113511             view   = grid.view;
113512
113513         me.mon(view, {
113514             mousewheel: {
113515                 element: 'el',
113516                 fn: me.cancelEdit,
113517                 scope: me
113518             }
113519         });
113520         me.mon(grid, {
113521             columnresize: me.cancelEdit,
113522             columnmove: me.cancelEdit,
113523             scope: me
113524         });
113525     },
113526
113527     /**
113528      * Start editing the specified record, using the specified Column definition to define which field is being edited.
113529      * @param {Model} record The Store data record which backs the row to be edited.
113530      * @param {Model} columnHeader The Column object defining the column to be edited.
113531      * @override
113532      */
113533     startEdit: function(record, columnHeader) {
113534         var me = this,
113535             ed   = me.getEditor(record, columnHeader),
113536             value = record.get(columnHeader.dataIndex),
113537             context = me.getEditingContext(record, columnHeader);
113538
113539         record = context.record;
113540         columnHeader = context.column;
113541
113542         // Complete the edit now, before getting the editor's target
113543         // cell DOM element. Completing the edit causes a view refresh.
113544         me.completeEdit();
113545
113546         // See if the field is editable for the requested record
113547         if (columnHeader && !columnHeader.getEditor(record)) {
113548             return false;
113549         }
113550
113551         if (ed) {
113552             context.originalValue = context.value = value;
113553             if (me.beforeEdit(context) === false || me.fireEvent('beforeedit', context) === false || context.cancel) {
113554                 return false;
113555             }
113556
113557             me.context = context;
113558             me.setActiveEditor(ed);
113559             me.setActiveRecord(record);
113560             me.setActiveColumn(columnHeader);
113561
113562             // Defer, so we have some time between view scroll to sync up the editor
113563             Ext.defer(ed.startEdit, 15, ed, [me.getCell(record, columnHeader), value]);
113564         } else {
113565             // BrowserBug: WebKit & IE refuse to focus the element, rather
113566             // it will focus it and then immediately focus the body. This
113567             // temporary hack works for Webkit and IE6. IE7 and 8 are still
113568             // broken
113569             me.grid.getView().el.focus((Ext.isWebKit || Ext.isIE) ? 10 : false);
113570         }
113571     },
113572
113573     completeEdit: function() {
113574         var activeEd = this.getActiveEditor();
113575         if (activeEd) {
113576             activeEd.completeEdit();
113577         }
113578     },
113579
113580     // internal getters/setters
113581     setActiveEditor: function(ed) {
113582         this.activeEditor = ed;
113583     },
113584
113585     getActiveEditor: function() {
113586         return this.activeEditor;
113587     },
113588
113589     setActiveColumn: function(column) {
113590         this.activeColumn = column;
113591     },
113592
113593     getActiveColumn: function() {
113594         return this.activeColumn;
113595     },
113596
113597     setActiveRecord: function(record) {
113598         this.activeRecord = record;
113599     },
113600
113601     getActiveRecord: function() {
113602         return this.activeRecord;
113603     },
113604
113605     getEditor: function(record, column) {
113606         var editors = this.editors,
113607             editorId = column.itemId || column.id,
113608             editor = editors.getByKey(editorId);
113609
113610         if (editor) {
113611             return editor;
113612         } else {
113613             editor = column.getEditor(record);
113614             if (!editor) {
113615                 return false;
113616             }
113617
113618             // Allow them to specify a CellEditor in the Column
113619             if (!(editor instanceof Ext.grid.CellEditor)) {
113620                 editor = Ext.create('Ext.grid.CellEditor', {
113621                     editorId: editorId,
113622                     field: editor
113623                 });
113624             }
113625             editor.parentEl = this.grid.getEditorParent();
113626             // editor.parentEl should be set here.
113627             editor.on({
113628                 scope: this,
113629                 specialkey: this.onSpecialKey,
113630                 complete: this.onEditComplete,
113631                 canceledit: this.cancelEdit
113632             });
113633             editors.add(editor);
113634             return editor;
113635         }
113636     },
113637
113638     /**
113639      * Get the cell (td) for a particular record and column.
113640      * @param {Ext.data.Model} record
113641      * @param {Ext.grid.column.Colunm} column
113642      * @private
113643      */
113644     getCell: function(record, column) {
113645         return this.grid.getView().getCell(record, column);
113646     },
113647
113648     onSpecialKey: function(ed, field, e) {
113649         var grid = this.grid,
113650             sm;
113651         if (e.getKey() === e.TAB) {
113652             e.stopEvent();
113653             sm = grid.getSelectionModel();
113654             if (sm.onEditorTab) {
113655                 sm.onEditorTab(this, e);
113656             }
113657         }
113658     },
113659
113660     onEditComplete : function(ed, value, startValue) {
113661         var me = this,
113662             grid = me.grid,
113663             sm = grid.getSelectionModel(),
113664             dataIndex = me.getActiveColumn().dataIndex;
113665
113666         me.setActiveEditor(null);
113667         me.setActiveColumn(null);
113668         me.setActiveRecord(null);
113669         delete sm.wasEditing;
113670
113671         if (!me.validateEdit()) {
113672             return;
113673         }
113674         me.context.record.set(dataIndex, value);
113675         me.fireEvent('edit', me, me.context);
113676     },
113677
113678     /**
113679      * Cancel any active editing.
113680      */
113681     cancelEdit: function() {
113682         var me = this,
113683             activeEd = me.getActiveEditor(),
113684             viewEl = me.grid.getView().el;
113685
113686         me.setActiveEditor(null);
113687         me.setActiveColumn(null);
113688         me.setActiveRecord(null);
113689         if (activeEd) {
113690             activeEd.cancelEdit();
113691             viewEl.focus();
113692         }
113693     },
113694
113695     /**
113696      * Starts editing by position (row/column)
113697      * @param {Object} position A position with keys of row and column.
113698      */
113699     startEditByPosition: function(position) {
113700         var me = this,
113701             grid = me.grid,
113702             sm = grid.getSelectionModel(),
113703             editRecord = grid.store.getAt(position.row),
113704             editColumnHeader = grid.headerCt.getHeaderAtIndex(position.column);
113705
113706         if (sm.selectByPosition) {
113707             sm.selectByPosition(position);
113708         }
113709         me.startEdit(editRecord, editColumnHeader);
113710     }
113711 });
113712 /**
113713  * @class Ext.grid.plugin.DragDrop
113714  * <p>This plugin provides drag and/or drop functionality for a GridView.</p>
113715  * <p>It creates a specialized instance of {@link Ext.dd.DragZone DragZone} which knows how to drag out of a {@link Ext.grid.View GridView}
113716  * and loads the data object which is passed to a cooperating {@link Ext.dd.DragZone DragZone}'s methods with the following properties:<ul>
113717  * <li>copy : Boolean
113718  *  <div class="sub-desc">The value of the GridView's <code>copy</code> property, or <code>true</code> if the GridView was configured
113719  *  with <code>allowCopy: true</code> <u>and</u> the control key was pressed when the drag operation was begun.</div></li>
113720  * <li>view : GridView
113721  *  <div class="sub-desc">The source GridView from which the drag originated.</div></li>
113722  * <li>ddel : HtmlElement
113723  *  <div class="sub-desc">The drag proxy element which moves with the mouse</div></li>
113724  * <li>item : HtmlElement
113725  *  <div class="sub-desc">The GridView node upon which the mousedown event was registered.</div></li>
113726  * <li>records : Array
113727  *  <div class="sub-desc">An Array of {@link Ext.data.Model Model}s representing the selected data being dragged from the source GridView.</div></li>
113728  * </ul></p>
113729  * <p>It also creates a specialized instance of {@link Ext.dd.DropZone} which cooperates with other DropZones which are members of the same
113730  * ddGroup which processes such data objects.</p>
113731  * <p>Adding this plugin to a view means that two new events may be fired from the client GridView, <code>{@link #event-beforedrop beforedrop}</code> and
113732  * <code>{@link #event-drop drop}</code></p>
113733  */
113734 Ext.define('Ext.grid.plugin.DragDrop', {
113735     extend: 'Ext.AbstractPlugin',
113736     alias: 'plugin.gridviewdragdrop',
113737
113738     uses: [
113739         'Ext.view.DragZone',
113740         'Ext.grid.ViewDropZone'
113741     ],
113742
113743     /**
113744      * @event beforedrop
113745      * <p><b>This event is fired through the GridView. Add listeners to the GridView object</b></p>
113746      * <p>Fired when a drop gesture has been triggered by a mouseup event in a valid drop position in the GridView.
113747      * @param {HtmlElement} node The GridView node <b>if any</b> over which the mouse was positioned.</p>
113748      * <p>Returning <code>false</code> to this event signals that the drop gesture was invalid, and if the drag proxy
113749      * will animate back to the point from which the drag began.</p>
113750      * <p>Returning <code>0</code> To this event signals that the data transfer operation should not take place, but
113751      * that the gesture was valid, and that the repair operation should not take place.</p>
113752      * <p>Any other return value continues with the data transfer operation.</p>
113753      * @param {Object} data The data object gathered at mousedown time by the cooperating {@link Ext.dd.DragZone DragZone}'s
113754      * {@link Ext.dd.DragZone#getDragData getDragData} method it contains the following properties:<ul>
113755      * <li>copy : Boolean
113756      *  <div class="sub-desc">The value of the GridView's <code>copy</code> property, or <code>true</code> if the GridView was configured
113757      *  with <code>allowCopy: true</code> and the control key was pressed when the drag operation was begun</div></li>
113758      * <li>view : GridView
113759      *  <div class="sub-desc">The source GridView from which the drag originated.</div></li>
113760      * <li>ddel : HtmlElement
113761      *  <div class="sub-desc">The drag proxy element which moves with the mouse</div></li>
113762      * <li>item : HtmlElement
113763      *  <div class="sub-desc">The GridView node upon which the mousedown event was registered.</div></li>
113764      * <li>records : Array
113765      *  <div class="sub-desc">An Array of {@link Ext.data.Model Model}s representing the selected data being dragged from the source GridView.</div></li>
113766      * </ul>
113767      * @param {Ext.data.Model} overModel The Model over which the drop gesture took place.
113768      * @param {String} dropPosition <code>"before"</code> or <code>"after"</code> depending on whether the mouse is above or below the midline of the node.
113769      * @param {Function} dropFunction <p>A function to call to complete the data transfer operation and either move or copy Model instances from the source
113770      * View's Store to the destination View's Store.</p>
113771      * <p>This is useful when you want to perform some kind of asynchronous processing before confirming
113772      * the drop, such as an {@link Ext.window.MessageBox#confirm confirm} call, or an Ajax request.</p>
113773      * <p>Return <code>0</code> from this event handler, and call the <code>dropFunction</code> at any time to perform the data transfer.</p>
113774      */
113775
113776     /**
113777      * @event drop
113778      * <b>This event is fired through the GridView. Add listeners to the GridView object</b>
113779      * Fired when a drop operation has been completed and the data has been moved or copied.
113780      * @param {HtmlElement} node The GridView node <b>if any</b> over which the mouse was positioned.
113781      * @param {Object} data The data object gathered at mousedown time by the cooperating {@link Ext.dd.DragZone DragZone}'s
113782      * {@link Ext.dd.DragZone#getDragData getDragData} method it contains the following properties:<ul>
113783      * <li>copy : Boolean
113784      *  <div class="sub-desc">The value of the GridView's <code>copy</code> property, or <code>true</code> if the GridView was configured
113785      *  with <code>allowCopy: true</code> and the control key was pressed when the drag operation was begun</div></li>
113786      * <li>view : GridView
113787      *  <div class="sub-desc">The source GridView from which the drag originated.</div></li>
113788      * <li>ddel : HtmlElement
113789      *  <div class="sub-desc">The drag proxy element which moves with the mouse</div></li>
113790      * <li>item : HtmlElement
113791      *  <div class="sub-desc">The GridView node upon which the mousedown event was registered.</div></li>
113792      * <li>records : Array
113793      *  <div class="sub-desc">An Array of {@link Ext.data.Model Model}s representing the selected data being dragged from the source GridView.</div></li>
113794      * </ul>
113795      * @param {Ext.data.Model} overModel The Model over which the drop gesture took place.
113796      * @param {String} dropPosition <code>"before"</code> or <code>"after"</code> depending on whether the mouse is above or below the midline of the node.
113797      */
113798
113799     dragText : '{0} selected row{1}',
113800
113801     /**
113802      * @cfg {String} ddGroup
113803      * A named drag drop group to which this object belongs.  If a group is specified, then both the DragZones and DropZone
113804      * used by this plugin will only interact with other drag drop objects in the same group (defaults to 'TreeDD').
113805      */
113806     ddGroup : "GridDD",
113807
113808     /**
113809      * @cfg {String} dragGroup
113810      * <p>The ddGroup to which the DragZone will belong.</p>
113811      * <p>This defines which other DropZones the DragZone will interact with. Drag/DropZones only interact with other Drag/DropZones
113812      * which are members of the same ddGroup.</p>
113813      */
113814
113815     /**
113816      * @cfg {String} dropGroup
113817      * <p>The ddGroup to which the DropZone will belong.</p>
113818      * <p>This defines which other DragZones the DropZone will interact with. Drag/DropZones only interact with other Drag/DropZones
113819      * which are members of the same ddGroup.</p>
113820      */
113821
113822     /**
113823      * @cfg {Boolean} enableDrop
113824      * <p>Defaults to <code>true</code></p>
113825      * <p>Set to <code>false</code> to disallow the View from accepting drop gestures</p>
113826      */
113827     enableDrop: true,
113828
113829     /**
113830      * @cfg {Boolean} enableDrag
113831      * <p>Defaults to <code>true</code></p>
113832      * <p>Set to <code>false</code> to disallow dragging items from the View </p>
113833      */
113834     enableDrag: true,
113835
113836     init : function(view) {
113837         view.on('render', this.onViewRender, this, {single: true});
113838     },
113839
113840     /**
113841      * @private
113842      * AbstractComponent calls destroy on all its plugins at destroy time.
113843      */
113844     destroy: function() {
113845         Ext.destroy(this.dragZone, this.dropZone);
113846     },
113847
113848     onViewRender : function(view) {
113849         var me = this;
113850
113851         if (me.enableDrag) {
113852             me.dragZone = Ext.create('Ext.view.DragZone', {
113853                 view: view,
113854                 ddGroup: me.dragGroup || me.ddGroup,
113855                 dragText: me.dragText
113856             });
113857         }
113858
113859         if (me.enableDrop) {
113860             me.dropZone = Ext.create('Ext.grid.ViewDropZone', {
113861                 view: view,
113862                 ddGroup: me.dropGroup || me.ddGroup
113863             });
113864         }
113865     }
113866 });
113867 /**
113868  * @class Ext.grid.plugin.HeaderReorderer
113869  * @extends Ext.util.Observable
113870  * @private
113871  */
113872 Ext.define('Ext.grid.plugin.HeaderReorderer', {
113873     extend: 'Ext.util.Observable',
113874     requires: ['Ext.grid.header.DragZone', 'Ext.grid.header.DropZone'],
113875     alias: 'plugin.gridheaderreorderer',
113876
113877     init: function(headerCt) {
113878         this.headerCt = headerCt;
113879         headerCt.on('render', this.onHeaderCtRender, this);
113880     },
113881
113882     /**
113883      * @private
113884      * AbstractComponent calls destroy on all its plugins at destroy time.
113885      */
113886     destroy: function() {
113887         Ext.destroy(this.dragZone, this.dropZone);
113888     },
113889
113890     onHeaderCtRender: function() {
113891         this.dragZone = Ext.create('Ext.grid.header.DragZone', this.headerCt);
113892         this.dropZone = Ext.create('Ext.grid.header.DropZone', this.headerCt);
113893         if (this.disabled) {
113894             this.dragZone.disable();
113895         }
113896     },
113897     
113898     enable: function() {
113899         this.disabled = false;
113900         if (this.dragZone) {
113901             this.dragZone.enable();
113902         }
113903     },
113904     
113905     disable: function() {
113906         this.disabled = true;
113907         if (this.dragZone) {
113908             this.dragZone.disable();
113909         }
113910     }
113911 });
113912 /**
113913  * @class Ext.grid.plugin.HeaderResizer
113914  * @extends Ext.util.Observable
113915  * 
113916  * Plugin to add header resizing functionality to a HeaderContainer.
113917  * Always resizing header to the left of the splitter you are resizing.
113918  * 
113919  * Todo: Consider RTL support, columns would always calculate to the right of
113920  *    the splitter instead of to the left.
113921  */
113922 Ext.define('Ext.grid.plugin.HeaderResizer', {
113923     extend: 'Ext.util.Observable',
113924     requires: ['Ext.dd.DragTracker', 'Ext.util.Region'],
113925     alias: 'plugin.gridheaderresizer',
113926     
113927     disabled: false,
113928
113929     /**
113930      * @cfg {Boolean} dynamic
113931      * Set to true to resize on the fly rather than using a proxy marker. Defaults to false.
113932      */
113933     configs: {
113934         dynamic: true
113935     },
113936
113937     colHeaderCls: Ext.baseCSSPrefix + 'column-header',
113938
113939     minColWidth: 40,
113940     maxColWidth: 1000,
113941     wResizeCursor: 'col-resize',
113942     eResizeCursor: 'col-resize',
113943     // not using w and e resize bc we are only ever resizing one
113944     // column
113945     //wResizeCursor: Ext.isWebKit ? 'w-resize' : 'col-resize',
113946     //eResizeCursor: Ext.isWebKit ? 'e-resize' : 'col-resize',
113947
113948     init: function(headerCt) {
113949         this.headerCt = headerCt;
113950         headerCt.on('render', this.afterHeaderRender, this, {single: true});
113951     },
113952
113953     /**
113954      * @private
113955      * AbstractComponent calls destroy on all its plugins at destroy time.
113956      */
113957     destroy: function() {
113958         if (this.tracker) {
113959             this.tracker.destroy();
113960         }
113961     },
113962
113963     afterHeaderRender: function() {
113964         var headerCt = this.headerCt,
113965             el = headerCt.el;
113966
113967         headerCt.mon(el, 'mousemove', this.onHeaderCtMouseMove, this);
113968
113969         this.tracker = Ext.create('Ext.dd.DragTracker', {
113970             disabled: this.disabled,
113971             onBeforeStart: Ext.Function.bind(this.onBeforeStart, this),
113972             onStart: Ext.Function.bind(this.onStart, this),
113973             onDrag: Ext.Function.bind(this.onDrag, this),
113974             onEnd: Ext.Function.bind(this.onEnd, this),
113975             tolerance: 3,
113976             autoStart: 300,
113977             el: el
113978         });
113979     },
113980
113981     // As we mouse over individual headers, change the cursor to indicate
113982     // that resizing is available, and cache the resize target header for use
113983     // if/when they mousedown.
113984     onHeaderCtMouseMove: function(e, t) {
113985         if (this.headerCt.dragging) {
113986             if (this.activeHd) {
113987                 this.activeHd.el.dom.style.cursor = '';
113988                 delete this.activeHd;
113989             }
113990         } else {
113991             var headerEl = e.getTarget('.' + this.colHeaderCls, 3, true),
113992                 overHeader, resizeHeader;
113993
113994             if (headerEl){
113995                 overHeader = Ext.getCmp(headerEl.id);
113996
113997                 // On left edge, we are resizing the previous non-hidden, base level column.
113998                 if (overHeader.isOnLeftEdge(e)) {
113999                     resizeHeader = overHeader.previousNode('gridcolumn:not([hidden]):not([isGroupHeader])');
114000                 }
114001                 // Else, if on the right edge, we're resizing the column we are over
114002                 else if (overHeader.isOnRightEdge(e)) {
114003                     resizeHeader = overHeader;
114004                 }
114005                 // Between the edges: we are not resizing
114006                 else {
114007                     resizeHeader = null;
114008                 }
114009
114010                 // We *are* resizing
114011                 if (resizeHeader) {
114012                     // If we're attempting to resize a group header, that cannot be resized,
114013                     // so find its last base level column header; Group headers are sized
114014                     // by the size of their child headers.
114015                     if (resizeHeader.isGroupHeader) {
114016                         resizeHeader = resizeHeader.getVisibleGridColumns();
114017                         resizeHeader = resizeHeader[resizeHeader.length - 1];
114018                     }
114019
114020                     if (resizeHeader && !resizeHeader.fixed) {
114021                         this.activeHd = resizeHeader;
114022                         overHeader.el.dom.style.cursor = this.eResizeCursor;
114023                     }
114024                 // reset
114025                 } else {
114026                     overHeader.el.dom.style.cursor = '';
114027                     delete this.activeHd;
114028                 }
114029             }
114030         }
114031     },
114032
114033     // only start when there is an activeHd
114034     onBeforeStart : function(e){
114035         var t = e.getTarget();
114036         // cache the activeHd because it will be cleared.
114037         this.dragHd = this.activeHd;
114038
114039         if (!!this.dragHd && !Ext.fly(t).hasCls('x-column-header-trigger') && !this.headerCt.dragging) {
114040             //this.headerCt.dragging = true;
114041             this.tracker.constrainTo = this.getConstrainRegion();
114042             return true;
114043         } else {
114044             this.headerCt.dragging = false;
114045             return false;
114046         }
114047     },
114048
114049     // get the region to constrain to, takes into account max and min col widths
114050     getConstrainRegion: function() {
114051         var dragHdEl = this.dragHd.el,
114052             region   = Ext.util.Region.getRegion(dragHdEl);
114053
114054         return region.adjust(
114055             0,
114056             this.maxColWidth - dragHdEl.getWidth(),
114057             0,
114058             this.minColWidth
114059         );
114060     },
114061
114062     // initialize the left and right hand side markers around
114063     // the header that we are resizing
114064     onStart: function(e){
114065         var me       = this,
114066             dragHd   = me.dragHd,
114067             dragHdEl = dragHd.el,
114068             width    = dragHdEl.getWidth(),
114069             headerCt = me.headerCt,
114070             t        = e.getTarget();
114071
114072         if (me.dragHd && !Ext.fly(t).hasCls('x-column-header-trigger')) {
114073             headerCt.dragging = true;
114074         }
114075
114076         me.origWidth = width;
114077
114078         // setup marker proxies
114079         if (!me.dynamic) {
114080             var xy           = dragHdEl.getXY(),
114081                 gridSection  = headerCt.up('[scrollerOwner]'),
114082                 dragHct      = me.dragHd.up(':not([isGroupHeader])'),
114083                 firstSection = dragHct.up(),
114084                 lhsMarker    = gridSection.getLhsMarker(),
114085                 rhsMarker    = gridSection.getRhsMarker(),
114086                 el           = rhsMarker.parent(),
114087                 offsetLeft   = el.getLeft(true),
114088                 offsetTop    = el.getTop(true),
114089                 topLeft      = el.translatePoints(xy),
114090                 markerHeight = firstSection.body.getHeight() + headerCt.getHeight(),
114091                 top = topLeft.top - offsetTop;
114092
114093             lhsMarker.setTop(top);
114094             rhsMarker.setTop(top);
114095             lhsMarker.setHeight(markerHeight);
114096             rhsMarker.setHeight(markerHeight);
114097             lhsMarker.setLeft(topLeft.left - offsetLeft);
114098             rhsMarker.setLeft(topLeft.left + width - offsetLeft);
114099         }
114100     },
114101
114102     // synchronize the rhsMarker with the mouse movement
114103     onDrag: function(e){
114104         if (!this.dynamic) {
114105             var xy          = this.tracker.getXY('point'),
114106                 gridSection = this.headerCt.up('[scrollerOwner]'),
114107                 rhsMarker   = gridSection.getRhsMarker(),
114108                 el          = rhsMarker.parent(),
114109                 topLeft     = el.translatePoints(xy),
114110                 offsetLeft  = el.getLeft(true);
114111
114112             rhsMarker.setLeft(topLeft.left - offsetLeft);
114113         // Resize as user interacts
114114         } else {
114115             this.doResize();
114116         }
114117     },
114118
114119     onEnd: function(e){
114120         this.headerCt.dragging = false;
114121         if (this.dragHd) {
114122             if (!this.dynamic) {
114123                 var dragHd      = this.dragHd,
114124                     gridSection = this.headerCt.up('[scrollerOwner]'),
114125                     lhsMarker   = gridSection.getLhsMarker(),
114126                     rhsMarker   = gridSection.getRhsMarker(),
114127                     currWidth   = dragHd.getWidth(),
114128                     offset      = this.tracker.getOffset('point'),
114129                     offscreen   = -9999;
114130
114131                 // hide markers
114132                 lhsMarker.setLeft(offscreen);
114133                 rhsMarker.setLeft(offscreen);
114134             }
114135             this.doResize();
114136         }
114137     },
114138
114139     doResize: function() {
114140         if (this.dragHd) {
114141             var dragHd = this.dragHd,
114142                 nextHd,
114143                 offset = this.tracker.getOffset('point');
114144
114145             // resize the dragHd
114146             if (dragHd.flex) {
114147                 delete dragHd.flex;
114148             }
114149
114150             // If HeaderContainer is configured forceFit, inhibit upstream layout notification, so that
114151             // we can also shrink the following Header by an equal amount, and *then* inform the upstream layout.
114152             if (this.headerCt.forceFit) {
114153                 nextHd = dragHd.nextNode('gridcolumn:not([hidden]):not([isGroupHeader])');
114154                 if (nextHd) {
114155                     this.headerCt.componentLayout.layoutBusy = true;
114156                 }
114157             }
114158
114159             // Non-flexed Headers may never be squeezed in the event of a shortfall so
114160             // always set the minWidth to their current width.
114161             dragHd.minWidth = this.origWidth + offset[0];
114162             dragHd.setWidth(dragHd.minWidth);
114163
114164             // In the case of forceFit, change the following Header width.
114165             // Then apply the two width changes by laying out the owning HeaderContainer
114166             if (nextHd) {
114167                 delete nextHd.flex;
114168                 nextHd.setWidth(nextHd.getWidth() - offset[0]);
114169                 this.headerCt.componentLayout.layoutBusy = false;
114170                 this.headerCt.doComponentLayout();
114171             }
114172         }
114173     },
114174     
114175     disable: function() {
114176         this.disabled = true;
114177         if (this.tracker) {
114178             this.tracker.disable();
114179         }
114180     },
114181     
114182     enable: function() {
114183         this.disabled = false;
114184         if (this.tracker) {
114185             this.tracker.enable();
114186         }
114187     }
114188 });
114189 /**
114190  * @class Ext.grid.plugin.RowEditing
114191  * @extends Ext.grid.plugin.Editing
114192  * 
114193  * The Ext.grid.plugin.RowEditing plugin injects editing at a row level for a Grid. When editing begins,
114194  * a small floating dialog will be shown for the appropriate row. Each editable column will show a field
114195  * for editing. There is a button to save or cancel all changes for the edit.
114196  * 
114197  * The field that will be used for the editor is defined at the
114198  * {@link Ext.grid.column.Column#field field}. The editor can be a field instance or a field configuration.
114199  * If an editor is not specified for a particular column then that column won't be editable and the value of
114200  * the column will be displayed.
114201  * The editor may be shared for each column in the grid, or a different one may be specified for each column.
114202  * An appropriate field type should be chosen to match the data structure that it will be editing. For example,
114203  * to edit a date, it would be useful to specify {@link Ext.form.field.Date} as the editor.
114204  * 
114205  * {@img Ext.grid.plugin.RowEditing/Ext.grid.plugin.RowEditing.png Ext.grid.plugin.RowEditing plugin}
114206  *
114207  * ## Example Usage
114208  *    Ext.create('Ext.data.Store', {
114209  *        storeId:'simpsonsStore',
114210  *        fields:['name', 'email', 'phone'],
114211  *        data:{'items':[
114212  *            {"name":"Lisa", "email":"lisa@simpsons.com", "phone":"555-111-1224"},
114213  *            {"name":"Bart", "email":"bart@simpsons.com", "phone":"555--222-1234"},
114214  *            {"name":"Homer", "email":"home@simpsons.com", "phone":"555-222-1244"},                        
114215  *            {"name":"Marge", "email":"marge@simpsons.com", "phone":"555-222-1254"}            
114216  *        ]},
114217  *        proxy: {
114218  *            type: 'memory',
114219  *            reader: {
114220  *                type: 'json',
114221  *                root: 'items'
114222  *            }
114223  *        }
114224  *    });
114225  *   
114226  *    Ext.create('Ext.grid.Panel', {
114227  *        title: 'Simpsons',
114228  *        store: Ext.data.StoreManager.lookup('simpsonsStore'),
114229  *        columns: [
114230  *            {header: 'Name',  dataIndex: 'name', field: 'textfield'},
114231  *            {header: 'Email', dataIndex: 'email', flex:1, 
114232  *                editor: {
114233  *                    xtype:'textfield',
114234  *                    allowBlank:false
114235  *                }
114236  *            },
114237  *            {header: 'Phone', dataIndex: 'phone'}
114238  *        ],
114239  *        selType: 'rowmodel',
114240  *        plugins: [
114241  *            Ext.create('Ext.grid.plugin.RowEditing', {
114242  *                clicksToEdit: 1
114243  *            })
114244  *        ],
114245  *        height: 200,
114246  *        width: 400,
114247  *        renderTo: Ext.getBody()
114248  *    });
114249  * 
114250  * @markdown
114251  *
114252  */
114253 Ext.define('Ext.grid.plugin.RowEditing', {
114254     extend: 'Ext.grid.plugin.Editing',
114255     alias: 'plugin.rowediting',
114256
114257     requires: [
114258         'Ext.grid.RowEditor'
114259     ],
114260
114261     editStyle: 'row',
114262
114263     /**
114264      * @cfg {Boolean} autoCancel
114265      * `true` to automatically cancel any pending changes when the row editor begins editing a new row.
114266      * `false` to force the user to explicitly cancel the pending changes. Defaults to `true`.
114267      * @markdown
114268      */
114269     autoCancel: true,
114270
114271     /**
114272      * @cfg {Number} clicksToMoveEditor
114273      * The number of clicks to move the row editor to a new row while it is visible and actively editing another row.
114274      * This will default to the same value as {@link Ext.grid.plugin.Editing#clicksToEdit clicksToEdit}.
114275      * @markdown
114276      */
114277
114278     /**
114279      * @cfg {Boolean} errorSummary
114280      * `true` to show a {@link Ext.tip.ToolTip tooltip} that summarizes all validation errors present
114281      * in the row editor. Set to `false` to prevent the tooltip from showing. Defaults to `true`.
114282      * @markdown
114283      */
114284     errorSummary: true,
114285
114286     /**
114287      * @event beforeedit
114288      * Fires before row editing is triggered. The edit event object has the following properties <br />
114289      * <ul style="padding:5px;padding-left:16px;">
114290      * <li>grid - The grid this editor is on</li>
114291      * <li>view - The grid view</li>
114292      * <li>store - The grid store</li>
114293      * <li>record - The record being edited</li>
114294      * <li>row - The grid table row</li>
114295      * <li>column - The grid {@link Ext.grid.column.Column Column} defining the column that initiated the edit</li>
114296      * <li>rowIdx - The row index that is being edited</li>
114297      * <li>colIdx - The column index that initiated the edit</li>
114298      * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
114299      * </ul>
114300      * @param {Ext.grid.plugin.Editing} editor
114301      * @param {Object} e An edit event (see above for description)
114302      */
114303     /**
114304      * @event edit
114305      * Fires after a row is edited. The edit event object has the following properties <br />
114306      * <ul style="padding:5px;padding-left:16px;">
114307      * <li>grid - The grid this editor is on</li>
114308      * <li>view - The grid view</li>
114309      * <li>store - The grid store</li>
114310      * <li>record - The record being edited</li>
114311      * <li>row - The grid table row</li>
114312      * <li>column - The grid {@link Ext.grid.column.Column Column} defining the column that initiated the edit</li>
114313      * <li>rowIdx - The row index that is being edited</li>
114314      * <li>colIdx - The column index that initiated the edit</li>
114315      * </ul>
114316      *
114317      * <pre><code>
114318 grid.on('edit', onEdit, this);
114319
114320 function onEdit(e) {
114321     // execute an XHR to send/commit data to the server, in callback do (if successful):
114322     e.record.commit();
114323 };
114324      * </code></pre>
114325      * @param {Ext.grid.plugin.Editing} editor
114326      * @param {Object} e An edit event (see above for description)
114327      */
114328     /**
114329      * @event validateedit
114330      * Fires after a cell is edited, but before the value is set in the record. Return false
114331      * to cancel the change. The edit event object has the following properties <br />
114332      * <ul style="padding:5px;padding-left:16px;">
114333      * <li>grid - The grid this editor is on</li>
114334      * <li>view - The grid view</li>
114335      * <li>store - The grid store</li>
114336      * <li>record - The record being edited</li>
114337      * <li>row - The grid table row</li>
114338      * <li>column - The grid {@link Ext.grid.column.Column Column} defining the column that initiated the edit</li>
114339      * <li>rowIdx - The row index that is being edited</li>
114340      * <li>colIdx - The column index that initiated the edit</li>
114341      * <li>cancel - Set this to true to cancel the edit or return false from your handler.</li>
114342      * </ul>
114343      * Usage example showing how to remove the red triangle (dirty record indicator) from some
114344      * records (not all).  By observing the grid's validateedit event, it can be cancelled if
114345      * the edit occurs on a targeted row (for example) and then setting the field's new value
114346      * in the Record directly:
114347      * <pre><code>
114348 grid.on('validateedit', function(e) {
114349   var myTargetRow = 6;
114350
114351   if (e.rowIdx == myTargetRow) {
114352     e.cancel = true;
114353     e.record.data[e.field] = e.value;
114354   }
114355 });
114356      * </code></pre>
114357      * @param {Ext.grid.plugin.Editing} editor
114358      * @param {Object} e An edit event (see above for description)
114359      */
114360
114361     constructor: function() {
114362         var me = this;
114363         me.callParent(arguments);
114364
114365         if (!me.clicksToMoveEditor) {
114366             me.clicksToMoveEditor = me.clicksToEdit;
114367         }
114368
114369         me.autoCancel = !!me.autoCancel;
114370     },
114371
114372     /**
114373      * @private
114374      * AbstractComponent calls destroy on all its plugins at destroy time.
114375      */
114376     destroy: function() {
114377         var me = this;
114378         Ext.destroy(me.editor);
114379         me.callParent(arguments);
114380     },
114381
114382     /**
114383      * Start editing the specified record, using the specified Column definition to define which field is being edited.
114384      * @param {Model} record The Store data record which backs the row to be edited.
114385      * @param {Model} columnHeader The Column object defining the column to be edited.
114386      * @override
114387      */
114388     startEdit: function(record, columnHeader) {
114389         var me = this,
114390             editor = me.getEditor();
114391
114392         if (me.callParent(arguments) === false) {
114393             return false;
114394         }
114395
114396         // Fire off our editor
114397         if (editor.beforeEdit() !== false) {
114398             editor.startEdit(me.context.record, me.context.column);
114399         }
114400     },
114401
114402     // private
114403     cancelEdit: function() {
114404         var me = this;
114405
114406         if (me.editing) {
114407             me.getEditor().cancelEdit();
114408             me.callParent(arguments);
114409         }
114410     },
114411
114412     // private
114413     completeEdit: function() {
114414         var me = this;
114415
114416         if (me.editing && me.validateEdit()) {
114417             me.editing = false;
114418             me.fireEvent('edit', me.context);
114419         }
114420     },
114421
114422     // private
114423     validateEdit: function() {
114424         var me = this;
114425         return me.callParent(arguments) && me.getEditor().completeEdit();
114426     },
114427
114428     // private
114429     getEditor: function() {
114430         var me = this;
114431
114432         if (!me.editor) {
114433             me.editor = me.initEditor();
114434         }
114435         return me.editor;
114436     },
114437
114438     // private
114439     initEditor: function() {
114440         var me = this,
114441             grid = me.grid,
114442             view = me.view,
114443             headerCt = grid.headerCt;
114444
114445         return Ext.create('Ext.grid.RowEditor', {
114446             autoCancel: me.autoCancel,
114447             errorSummary: me.errorSummary,
114448             fields: headerCt.getGridColumns(),
114449             hidden: true,
114450
114451             // keep a reference..
114452             editingPlugin: me,
114453             renderTo: view.el
114454         });
114455     },
114456
114457     // private
114458     initEditTriggers: function() {
114459         var me = this,
114460             grid = me.grid,
114461             view = me.view,
114462             headerCt = grid.headerCt,
114463             moveEditorEvent = me.clicksToMoveEditor === 1 ? 'click' : 'dblclick';
114464
114465         me.callParent(arguments);
114466
114467         if (me.clicksToMoveEditor !== me.clicksToEdit) {
114468             me.mon(view, 'cell' + moveEditorEvent, me.moveEditorByClick, me);
114469         }
114470
114471         view.on('render', function() {
114472             // Column events
114473             me.mon(headerCt, {
114474                 add: me.onColumnAdd,
114475                 remove: me.onColumnRemove,
114476                 columnresize: me.onColumnResize,
114477                 columnhide: me.onColumnHide,
114478                 columnshow: me.onColumnShow,
114479                 columnmove: me.onColumnMove,
114480                 scope: me
114481             });
114482         }, me, { single: true });
114483     },
114484
114485     startEditByClick: function() {
114486         var me = this;
114487         if (!me.editing || me.clicksToMoveEditor === me.clicksToEdit) {
114488             me.callParent(arguments);
114489         }
114490     },
114491
114492     moveEditorByClick: function() {
114493         var me = this;
114494         if (me.editing) {
114495             me.superclass.startEditByClick.apply(me, arguments);
114496         }
114497     },
114498
114499     // private
114500     onColumnAdd: function(ct, column) {
114501         var me = this,
114502             editor = me.getEditor();
114503
114504         me.initFieldAccessors(column);
114505         if (editor && editor.onColumnAdd) {
114506             editor.onColumnAdd(column);
114507         }
114508     },
114509
114510     // private
114511     onColumnRemove: function(ct, column) {
114512         var me = this,
114513             editor = me.getEditor();
114514
114515         if (editor && editor.onColumnRemove) {
114516             editor.onColumnRemove(column);
114517         }
114518         me.removeFieldAccessors(column);
114519     },
114520
114521     // private
114522     onColumnResize: function(ct, column, width) {
114523         var me = this,
114524             editor = me.getEditor();
114525
114526         if (editor && editor.onColumnResize) {
114527             editor.onColumnResize(column, width);
114528         }
114529     },
114530
114531     // private
114532     onColumnHide: function(ct, column) {
114533         var me = this,
114534             editor = me.getEditor();
114535
114536         if (editor && editor.onColumnHide) {
114537             editor.onColumnHide(column);
114538         }
114539     },
114540
114541     // private
114542     onColumnShow: function(ct, column) {
114543         var me = this,
114544             editor = me.getEditor();
114545
114546         if (editor && editor.onColumnShow) {
114547             editor.onColumnShow(column);
114548         }
114549     },
114550
114551     // private
114552     onColumnMove: function(ct, column, fromIdx, toIdx) {
114553         var me = this,
114554             editor = me.getEditor();
114555
114556         if (editor && editor.onColumnMove) {
114557             editor.onColumnMove(column, fromIdx, toIdx);
114558         }
114559     },
114560
114561     // private
114562     setColumnField: function(column, field) {
114563         var me = this;
114564         me.callParent(arguments);
114565         me.getEditor().setField(column.field, column);
114566     }
114567 });
114568 /**
114569  * @class Ext.grid.property.Grid
114570  * @extends Ext.grid.Panel
114571  * A specialized grid implementation intended to mimic the traditional property grid as typically seen in
114572  * development IDEs.  Each row in the grid represents a property of some object, and the data is stored
114573  * as a set of name/value pairs in {@link Ext.grid.property.Property Properties}.  Example usage:
114574  * <pre><code>
114575 var grid = new Ext.grid.property.Grid({
114576     title: 'Properties Grid',
114577     width: 300,
114578     renderTo: 'grid-ct',
114579     source: {
114580         "(name)": "My Object",
114581         "Created": Ext.Date.parse('10/15/2006', 'm/d/Y'),
114582         "Available": false,
114583         "Version": .01,
114584         "Description": "A test object"
114585     }
114586 });
114587 </code></pre>
114588  * @constructor
114589  * @param {Object} config The grid config object
114590  */
114591 Ext.define('Ext.grid.property.Grid', {
114592
114593     extend: 'Ext.grid.Panel',
114594
114595     alternateClassName: 'Ext.grid.PropertyGrid',
114596
114597     uses: [
114598        'Ext.grid.plugin.CellEditing',
114599        'Ext.grid.property.Store',
114600        'Ext.grid.property.HeaderContainer',
114601        'Ext.XTemplate',
114602        'Ext.grid.CellEditor',
114603        'Ext.form.field.Date',
114604        'Ext.form.field.Text',
114605        'Ext.form.field.Number'
114606     ],
114607
114608    /**
114609     * @cfg {Object} propertyNames An object containing custom property name/display name pairs.
114610     * If specified, the display name will be shown in the name column instead of the property name.
114611     */
114612
114613     /**
114614     * @cfg {Object} source A data object to use as the data source of the grid (see {@link #setSource} for details).
114615     */
114616
114617     /**
114618     * @cfg {Object} customEditors An object containing name/value pairs of custom editor type definitions that allow
114619     * the grid to support additional types of editable fields.  By default, the grid supports strongly-typed editing
114620     * of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and
114621     * associated with a custom input control by specifying a custom editor.  The name of the editor
114622     * type should correspond with the name of the property that will use the editor.  Example usage:
114623     * <pre><code>
114624 var grid = new Ext.grid.property.Grid({
114625
114626     // Custom editors for certain property names
114627     customEditors: {
114628         evtStart: Ext.create('Ext.form.TimeField' {selectOnFocus:true})
114629     },
114630
114631     // Displayed name for property names in the source
114632     propertyNames: {
114633         evtStart: 'Start Time'
114634     },
114635
114636     // Data object containing properties to edit
114637     source: {
114638         evtStart: '10:00 AM'
114639     }
114640 });
114641 </code></pre>
114642     */
114643
114644     /**
114645     * @cfg {Object} source A data object to use as the data source of the grid (see {@link #setSource} for details).
114646     */
114647
114648     /**
114649     * @cfg {Object} customRenderers An object containing name/value pairs of custom renderer type definitions that allow
114650     * the grid to support custom rendering of fields.  By default, the grid supports strongly-typed rendering
114651     * of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and
114652     * associated with the type of the value.  The name of the renderer type should correspond with the name of the property
114653     * that it will render.  Example usage:
114654     * <pre><code>
114655 var grid = Ext.create('Ext.grid.property.Grid', {
114656     customRenderers: {
114657         Available: function(v){
114658             if (v) {
114659                 return '<span style="color: green;">Yes</span>';
114660             } else {
114661                 return '<span style="color: red;">No</span>';
114662             }
114663         }
114664     },
114665     source: {
114666         Available: true
114667     }
114668 });
114669 </code></pre>
114670     */
114671
114672     /**
114673      * @cfg {String} valueField
114674      * Optional. The name of the field from the property store to use as the value field name. Defaults to <code>'value'</code>
114675      * This may be useful if you do not configure the property Grid from an object, but use your own store configuration.
114676      */
114677     valueField: 'value',
114678
114679     /**
114680      * @cfg {String} nameField
114681      * Optional. The name of the field from the property store to use as the property field name. Defaults to <code>'name'</code>
114682      * This may be useful if you do not configure the property Grid from an object, but use your own store configuration.
114683      */
114684     nameField: 'name',
114685
114686     // private config overrides
114687     enableColumnMove: false,
114688     columnLines: true,
114689     stripeRows: false,
114690     trackMouseOver: false,
114691     clicksToEdit: 1,
114692     enableHdMenu: false,
114693
114694     // private
114695     initComponent : function(){
114696         var me = this;
114697
114698         me.addCls(Ext.baseCSSPrefix + 'property-grid');
114699         me.plugins = me.plugins || [];
114700
114701         // Enable cell editing. Inject a custom startEdit which always edits column 1 regardless of which column was clicked.
114702         me.plugins.push(Ext.create('Ext.grid.plugin.CellEditing', {
114703             clicksToEdit: me.clicksToEdit,
114704
114705             // Inject a startEdit which always edits the value column
114706             startEdit: function(record, column) {
114707                 // Maintainer: Do not change this 'this' to 'me'! It is the CellEditing object's own scope.
114708                 Ext.grid.plugin.CellEditing.prototype.startEdit.call(this, record, me.headerCt.child('#' + me.valueField));
114709             }
114710         }));
114711
114712         me.selModel = {
114713             selType: 'cellmodel',
114714             onCellSelect: function(position) {
114715                 if (position.column != 1) {
114716                     position.column = 1;
114717                     Ext.selection.CellModel.prototype.onCellSelect.call(this, position);
114718                 }
114719             }
114720         };
114721         me.customRenderers = me.customRenderers || {};
114722         me.customEditors = me.customEditors || {};
114723
114724         // Create a property.Store from the source object unless configured with a store
114725         if (!me.store) {
114726             me.propStore = me.store = Ext.create('Ext.grid.property.Store', me, me.source);
114727         }
114728
114729         me.store.sort('name', 'ASC');
114730         me.columns = Ext.create('Ext.grid.property.HeaderContainer', me, me.store);
114731
114732         me.addEvents(
114733             /**
114734              * @event beforepropertychange
114735              * Fires before a property value changes.  Handlers can return false to cancel the property change
114736              * (this will internally call {@link Ext.data.Record#reject} on the property's record).
114737              * @param {Object} source The source data object for the grid (corresponds to the same object passed in
114738              * as the {@link #source} config property).
114739              * @param {String} recordId The record's id in the data store
114740              * @param {Mixed} value The current edited property value
114741              * @param {Mixed} oldValue The original property value prior to editing
114742              */
114743             'beforepropertychange',
114744             /**
114745              * @event propertychange
114746              * Fires after a property value has changed.
114747              * @param {Object} source The source data object for the grid (corresponds to the same object passed in
114748              * as the {@link #source} config property).
114749              * @param {String} recordId The record's id in the data store
114750              * @param {Mixed} value The current edited property value
114751              * @param {Mixed} oldValue The original property value prior to editing
114752              */
114753             'propertychange'
114754         );
114755         me.callParent();
114756
114757         // Inject a custom implementation of walkCells which only goes up or down
114758         me.getView().walkCells = this.walkCells;
114759
114760         // Set up our default editor set for the 4 atomic data types
114761         me.editors = {
114762             'date'    : Ext.create('Ext.grid.CellEditor', { field: Ext.create('Ext.form.field.Date',   {selectOnFocus: true})}),
114763             'string'  : Ext.create('Ext.grid.CellEditor', { field: Ext.create('Ext.form.field.Text',   {selectOnFocus: true})}),
114764             'number'  : Ext.create('Ext.grid.CellEditor', { field: Ext.create('Ext.form.field.Number', {selectOnFocus: true})}),
114765             'boolean' : Ext.create('Ext.grid.CellEditor', { field: Ext.create('Ext.form.field.ComboBox', {
114766                 editable: false,
114767                 store: [[ true, me.headerCt.trueText ], [false, me.headerCt.falseText ]]
114768             })})
114769         };
114770
114771         // Track changes to the data so we can fire our events.
114772         this.store.on('update', me.onUpdate, me);
114773     },
114774
114775     // private
114776     onUpdate : function(store, record, operation) {
114777         var me = this,
114778             v, oldValue;
114779
114780         if (operation == Ext.data.Model.EDIT) {
114781             v = record.get(me.valueField);
114782             oldValue = record.modified.value;
114783             if (me.fireEvent('beforepropertychange', me.source, record.id, v, oldValue) !== false) {
114784                 if (me.source) {
114785                     me.source[record.id] = v;
114786                 }
114787                 record.commit();
114788                 me.fireEvent('propertychange', me.source, record.id, v, oldValue);
114789             } else {
114790                 record.reject();
114791             }
114792         }
114793     },
114794
114795     // Custom implementation of walkCells which only goes up and down.
114796     walkCells: function(pos, direction, e, preventWrap, verifierFn, scope) {
114797         if (direction == 'left') {
114798             direction = 'up';
114799         } else if (direction == 'right') {
114800             direction = 'down';
114801         }
114802         var pos = Ext.view.Table.prototype.walkCells.call(this, pos, direction, e, preventWrap, verifierFn, scope);
114803         if (!pos.column) {
114804             pos.column = 1;
114805         }
114806         return pos;
114807     },
114808
114809     // private
114810     // returns the correct editor type for the property type, or a custom one keyed by the property name
114811     getCellEditor : function(record, column) {
114812         var me = this,
114813             propName = record.get(me.nameField), 
114814             val = record.get(me.valueField),
114815             editor = me.customEditors[propName];
114816
114817         // A custom editor was found. If not already wrapped with a CellEditor, wrap it, and stash it back
114818         // If it's not even a Field, just a config object, instantiate it before wrapping it.
114819         if (editor) {
114820             if (!(editor instanceof Ext.grid.CellEditor)) {
114821                 if (!(editor instanceof Ext.form.field.Base)) {
114822                     editor = Ext.ComponentManager.create(editor, 'textfield');
114823                 }
114824                 editor = me.customEditors[propName] = Ext.create('Ext.grid.CellEditor', { field: editor });
114825             }
114826         } else if (Ext.isDate(val)) {
114827             editor = me.editors.date;
114828         } else if (Ext.isNumber(val)) {
114829             editor = me.editors.number;
114830         } else if (Ext.isBoolean(val)) {
114831             editor = me.editors['boolean'];
114832         } else {
114833             editor = me.editors.string;
114834         }
114835
114836         // Give the editor a unique ID because the CellEditing plugin caches them
114837         editor.editorId = propName;
114838         return editor;
114839     },
114840
114841     beforeDestroy: function() {
114842         var me = this;
114843         me.callParent();
114844         me.destroyEditors(me.editors);
114845         me.destroyEditors(me.customEditors);
114846         delete me.source;
114847     },
114848
114849     destroyEditors: function (editors) {
114850         for (var ed in editors) {
114851             Ext.destroy(editors[ed]);
114852         }
114853     },
114854
114855     /**
114856      * Sets the source data object containing the property data.  The data object can contain one or more name/value
114857      * pairs representing all of the properties of an object to display in the grid, and this data will automatically
114858      * be loaded into the grid's {@link #store}.  The values should be supplied in the proper data type if needed,
114859      * otherwise string type will be assumed.  If the grid already contains data, this method will replace any
114860      * existing data.  See also the {@link #source} config value.  Example usage:
114861      * <pre><code>
114862 grid.setSource({
114863     "(name)": "My Object",
114864     "Created": Ext.Date.parse('10/15/2006', 'm/d/Y'),  // date type
114865     "Available": false,  // boolean type
114866     "Version": .01,      // decimal type
114867     "Description": "A test object"
114868 });
114869 </code></pre>
114870      * @param {Object} source The data object
114871      */
114872     setSource: function(source) {
114873         this.source = source;
114874         this.propStore.setSource(source);
114875     },
114876
114877     /**
114878      * Gets the source data object containing the property data.  See {@link #setSource} for details regarding the
114879      * format of the data object.
114880      * @return {Object} The data object
114881      */
114882     getSource: function() {
114883         return this.propStore.getSource();
114884     },
114885
114886     /**
114887      * Sets the value of a property.
114888      * @param {String} prop The name of the property to set
114889      * @param {Mixed} value The value to test
114890      * @param {Boolean} create (Optional) True to create the property if it doesn't already exist. Defaults to <tt>false</tt>.
114891      */
114892     setProperty: function(prop, value, create) {
114893         this.propStore.setValue(prop, value, create);
114894     },
114895
114896     /**
114897      * Removes a property from the grid.
114898      * @param {String} prop The name of the property to remove
114899      */
114900     removeProperty: function(prop) {
114901         this.propStore.remove(prop);
114902     }
114903
114904     /**
114905      * @cfg store
114906      * @hide
114907      */
114908     /**
114909      * @cfg colModel
114910      * @hide
114911      */
114912     /**
114913      * @cfg cm
114914      * @hide
114915      */
114916     /**
114917      * @cfg columns
114918      * @hide
114919      */
114920 });
114921 /**
114922  * @class Ext.grid.property.HeaderContainer
114923  * @extends Ext.grid.header.Container
114924  * A custom HeaderContainer for the {@link Ext.grid.property.Grid}.  Generally it should not need to be used directly.
114925  * @constructor
114926  * @param {Ext.grid.property.Grid} grid The grid this store will be bound to
114927  * @param {Object} source The source data config object
114928  */
114929 Ext.define('Ext.grid.property.HeaderContainer', {
114930
114931     extend: 'Ext.grid.header.Container',
114932
114933     alternateClassName: 'Ext.grid.PropertyColumnModel',
114934
114935     // private - strings used for locale support
114936     nameText : 'Name',
114937     valueText : 'Value',
114938     dateFormat : 'm/j/Y',
114939     trueText: 'true',
114940     falseText: 'false',
114941
114942     // private
114943     nameColumnCls: Ext.baseCSSPrefix + 'grid-property-name',
114944     
114945     constructor : function(grid, store) {
114946
114947         this.grid = grid;
114948         this.store = store;
114949         this.callParent([{
114950             items: [{
114951                 header: this.nameText,
114952                 width: 115,
114953                 sortable: true,
114954                 dataIndex: grid.nameField,
114955                 renderer: Ext.Function.bind(this.renderProp, this),
114956                 itemId: grid.nameField,
114957                 menuDisabled :true,
114958                 tdCls: this.nameColumnCls
114959             }, {
114960                 header: this.valueText,
114961                 renderer: Ext.Function.bind(this.renderCell, this),
114962                 getEditor: function(record) {
114963                     return grid.getCellEditor(record, this);
114964                 },
114965                 flex: 1,
114966                 fixed: true,
114967                 dataIndex: grid.valueField,
114968                 itemId: grid.valueField,
114969                 menuDisabled: true
114970             }]
114971         }]);
114972     },
114973
114974     // private
114975     // Render a property name cell
114976     renderProp : function(v) {
114977         return this.getPropertyName(v);
114978     },
114979
114980     // private
114981     // Render a property value cell
114982     renderCell : function(val, meta, rec) {
114983         var me = this,
114984             renderer = this.grid.customRenderers[rec.get(me.grid.nameField)],
114985             result = val;
114986
114987         if (renderer) {
114988             return renderer.apply(this, arguments);
114989         }
114990         if (Ext.isDate(val)) {
114991             result = this.renderDate(val);
114992         } else if (Ext.isBoolean(val)) {
114993             result = this.renderBool(val);
114994         }
114995         return Ext.util.Format.htmlEncode(result);
114996     },
114997
114998     // private
114999     renderDate : Ext.util.Format.date,
115000
115001     // private
115002     renderBool : function(bVal) {
115003         return this[bVal ? 'trueText' : 'falseText'];
115004     },
115005
115006     // private
115007     // Renders custom property names instead of raw names if defined in the Grid
115008     getPropertyName : function(name) {
115009         var pn = this.grid.propertyNames;
115010         return pn && pn[name] ? pn[name] : name;
115011     }
115012 });
115013 /**
115014  * @class Ext.grid.property.Property
115015  * A specific {@link Ext.data.Model} type that represents a name/value pair and is made to work with the
115016  * {@link Ext.grid.property.Grid}.  Typically, Properties do not need to be created directly as they can be
115017  * created implicitly by simply using the appropriate data configs either via the {@link Ext.grid.property.Grid#source}
115018  * config property or by calling {@link Ext.grid.property.Grid#setSource}.  However, if the need arises, these records
115019  * can also be created explicitly as shown below.  Example usage:
115020  * <pre><code>
115021 var rec = new Ext.grid.property.Property({
115022     name: 'birthday',
115023     value: Ext.Date.parse('17/06/1962', 'd/m/Y')
115024 });
115025 // Add record to an already populated grid
115026 grid.store.addSorted(rec);
115027 </code></pre>
115028  * @constructor
115029  * @param {Object} config A data object in the format:<pre><code>
115030 {
115031     name: [name],
115032     value: [value]
115033 }</code></pre>
115034  * The specified value's type
115035  * will be read automatically by the grid to determine the type of editor to use when displaying it.
115036  */
115037 Ext.define('Ext.grid.property.Property', {
115038     extend: 'Ext.data.Model',
115039
115040     alternateClassName: 'Ext.PropGridProperty',
115041
115042     fields: [{
115043         name: 'name',
115044         type: 'string'
115045     }, {
115046         name: 'value'
115047     }],
115048     idProperty: 'name'
115049 });
115050 /**
115051  * @class Ext.grid.property.Store
115052  * @extends Ext.data.Store
115053  * A custom {@link Ext.data.Store} for the {@link Ext.grid.property.Grid}. This class handles the mapping
115054  * between the custom data source objects supported by the grid and the {@link Ext.grid.property.Property} format
115055  * used by the {@link Ext.data.Store} base class.
115056  * @constructor
115057  * @param {Ext.grid.Grid} grid The grid this store will be bound to
115058  * @param {Object} source The source data config object
115059  */
115060 Ext.define('Ext.grid.property.Store', {
115061
115062     extend: 'Ext.data.Store',
115063
115064     alternateClassName: 'Ext.grid.PropertyStore',
115065
115066     uses: ['Ext.data.reader.Reader', 'Ext.data.proxy.Proxy', 'Ext.data.ResultSet', 'Ext.grid.property.Property'],
115067
115068     constructor : function(grid, source){
115069         this.grid = grid;
115070         this.source = source;
115071         this.callParent([{
115072             data: source,
115073             model: Ext.grid.property.Property,
115074             proxy: this.getProxy()
115075         }]);
115076     },
115077
115078     // Return a singleton, customized Proxy object which configures itself with a custom Reader
115079     getProxy: function() {
115080         if (!this.proxy) {
115081             Ext.grid.property.Store.prototype.proxy = Ext.create('Ext.data.proxy.Memory', {
115082                 model: Ext.grid.property.Property,
115083                 reader: this.getReader()
115084             });
115085         }
115086         return this.proxy;
115087     },
115088
115089     // Return a singleton, customized Reader object which reads Ext.grid.property.Property records from an object.
115090     getReader: function() {
115091         if (!this.reader) {
115092             Ext.grid.property.Store.prototype.reader = Ext.create('Ext.data.reader.Reader', {
115093                 model: Ext.grid.property.Property,
115094
115095                 buildExtractors: Ext.emptyFn,
115096
115097                 read: function(dataObject) {
115098                     return this.readRecords(dataObject);
115099                 },
115100
115101                 readRecords: function(dataObject) {
115102                     var val,
115103                         result = {
115104                             records: [],
115105                             success: true
115106                         };
115107
115108                     for (var propName in dataObject) {
115109                         val = dataObject[propName];
115110                         if (dataObject.hasOwnProperty(propName) && this.isEditableValue(val)) {
115111                             result.records.push(new Ext.grid.property.Property({
115112                                 name: propName,
115113                                 value: val
115114                             }, propName));
115115                         }
115116                     }
115117                     result.total = result.count = result.records.length;
115118                     return Ext.create('Ext.data.ResultSet', result);
115119                 },
115120
115121                 // private
115122                 isEditableValue: function(val){
115123                     return Ext.isPrimitive(val) || Ext.isDate(val);
115124                 }
115125             });
115126         }
115127         return this.reader;
115128     },
115129
115130     // protected - should only be called by the grid.  Use grid.setSource instead.
115131     setSource : function(dataObject) {
115132         var me = this;
115133
115134         me.source = dataObject;
115135         me.suspendEvents();
115136         me.removeAll();
115137         me.proxy.data = dataObject;
115138         me.load();
115139         me.resumeEvents();
115140         me.fireEvent('datachanged', me);
115141     },
115142
115143     // private
115144     getProperty : function(row) {
115145        return Ext.isNumber(row) ? this.store.getAt(row) : this.store.getById(row);
115146     },
115147
115148     // private
115149     setValue : function(prop, value, create){
115150         var r = this.getRec(prop);
115151         if (r) {
115152             r.set('value', value);
115153             this.source[prop] = value;
115154         } else if (create) {
115155             // only create if specified.
115156             this.source[prop] = value;
115157             r = new Ext.grid.property.Property({name: prop, value: value}, prop);
115158             this.store.add(r);
115159         }
115160     },
115161
115162     // private
115163     remove : function(prop) {
115164         var r = this.getRec(prop);
115165         if(r) {
115166             this.store.remove(r);
115167             delete this.source[prop];
115168         }
115169     },
115170
115171     // private
115172     getRec : function(prop) {
115173         return this.store.getById(prop);
115174     },
115175
115176     // protected - should only be called by the grid.  Use grid.getSource instead.
115177     getSource : function() {
115178         return this.source;
115179     }
115180 });
115181 /**
115182  * Component layout for components which maintain an inner body element which must be resized to synchronize with the
115183  * Component size.
115184  * @class Ext.layout.component.Body
115185  * @extends Ext.layout.component.Component
115186  * @private
115187  */
115188
115189 Ext.define('Ext.layout.component.Body', {
115190
115191     /* Begin Definitions */
115192
115193     alias: ['layout.body'],
115194
115195     extend: 'Ext.layout.component.Component',
115196
115197     uses: ['Ext.layout.container.Container'],
115198
115199     /* End Definitions */
115200
115201     type: 'body',
115202     
115203     onLayout: function(width, height) {
115204         var me = this,
115205             owner = me.owner;
115206
115207         // Size the Component's encapsulating element according to the dimensions
115208         me.setTargetSize(width, height);
115209
115210         // Size the Component's body element according to the content box of the encapsulating element
115211         me.setBodySize.apply(me, arguments);
115212
115213         // We need to bind to the owner whenever we do not have a user set height or width.
115214         if (owner && owner.layout && owner.layout.isLayout) {
115215             if (!Ext.isNumber(owner.height) || !Ext.isNumber(owner.width)) {
115216                 owner.layout.bindToOwnerCtComponent = true;
115217             }
115218             else {
115219                 owner.layout.bindToOwnerCtComponent = false;
115220             }
115221         }
115222         
115223         me.callParent(arguments);
115224     },
115225
115226     /**
115227      * @private
115228      * <p>Sizes the Component's body element to fit exactly within the content box of the Component's encapsulating element.<p>
115229      */
115230     setBodySize: function(width, height) {
115231         var me = this,
115232             owner = me.owner,
115233             frameSize = owner.frameSize,
115234             isNumber = Ext.isNumber;
115235
115236         if (isNumber(width)) {
115237             width -= owner.el.getFrameWidth('lr') - frameSize.left - frameSize.right;
115238         }
115239         if (isNumber(height)) {
115240             height -= owner.el.getFrameWidth('tb') - frameSize.top - frameSize.bottom;
115241         }
115242
115243         me.setElementSize(owner.body, width, height);
115244     }
115245 });
115246 /**
115247  * Component layout for Ext.form.FieldSet components
115248  * @class Ext.layout.component.FieldSet
115249  * @extends Ext.layout.component.Body
115250  * @private
115251  */
115252 Ext.define('Ext.layout.component.FieldSet', {
115253     extend: 'Ext.layout.component.Body',
115254     alias: ['layout.fieldset'],
115255
115256     type: 'fieldset',
115257
115258     doContainerLayout: function() {
115259         // Prevent layout/rendering of children if the fieldset is collapsed
115260         if (!this.owner.collapsed) {
115261             this.callParent();
115262         }
115263     }
115264 });
115265 /**
115266  * Component layout for tabs
115267  * @class Ext.layout.component.Tab
115268  * @extends Ext.layout.component.Button
115269  * @private
115270  */
115271 Ext.define('Ext.layout.component.Tab', {
115272
115273     alias: ['layout.tab'],
115274
115275     extend: 'Ext.layout.component.Button',
115276
115277     //type: 'button',
115278
115279     beforeLayout: function() {
115280         var me = this, dirty = me.lastClosable !== me.owner.closable;
115281
115282         if (dirty) {
115283             delete me.adjWidth;
115284         }
115285
115286         return this.callParent(arguments) || dirty;
115287     },
115288
115289     onLayout: function () {
115290         var me = this;
115291
115292         me.callParent(arguments);
115293
115294         me.lastClosable = me.owner.closable;
115295     }
115296 });
115297 /**
115298  * @private
115299  * @class Ext.layout.component.field.File
115300  * @extends Ext.layout.component.field.Field
115301  * Layout class for {@link Ext.form.field.File} fields. Adjusts the input field size to accommodate
115302  * the file picker trigger button.
115303  * @private
115304  */
115305
115306 Ext.define('Ext.layout.component.field.File', {
115307     alias: ['layout.filefield'],
115308     extend: 'Ext.layout.component.field.Field',
115309
115310     type: 'filefield',
115311
115312     sizeBodyContents: function(width, height) {
115313         var me = this,
115314             owner = me.owner;
115315
115316         if (!owner.buttonOnly) {
115317             // Decrease the field's width by the width of the button and the configured buttonMargin.
115318             // Both the text field and the button are floated left in CSS so they'll stack up side by side.
115319             me.setElementSize(owner.inputEl, Ext.isNumber(width) ? width - owner.button.getWidth() - owner.buttonMargin : width);
115320         }
115321     }
115322 });
115323 /**
115324  * @class Ext.layout.component.field.Slider
115325  * @extends Ext.layout.component.field.Field
115326  * @private
115327  */
115328
115329 Ext.define('Ext.layout.component.field.Slider', {
115330
115331     /* Begin Definitions */
115332
115333     alias: ['layout.sliderfield'],
115334
115335     extend: 'Ext.layout.component.field.Field',
115336
115337     /* End Definitions */
115338
115339     type: 'sliderfield',
115340
115341     sizeBodyContents: function(width, height) {
115342         var owner = this.owner,
115343             thumbs = owner.thumbs,
115344             length = thumbs.length,
115345             inputEl = owner.inputEl,
115346             innerEl = owner.innerEl,
115347             endEl = owner.endEl,
115348             i = 0;
115349
115350         /*
115351          * If we happen to be animating during a resize, the position of the thumb will likely be off
115352          * when the animation stops. As such, just stop any animations before syncing the thumbs.
115353          */
115354         for(; i < length; ++i) {
115355             thumbs[i].el.stopAnimation();
115356         }
115357         
115358         if (owner.vertical) {
115359             inputEl.setHeight(height);
115360             innerEl.setHeight(Ext.isNumber(height) ? height - inputEl.getPadding('t') - endEl.getPadding('b') : height);
115361         }
115362         else {
115363             inputEl.setWidth(width);
115364             innerEl.setWidth(Ext.isNumber(width) ? width - inputEl.getPadding('l') - endEl.getPadding('r') : width);
115365         }
115366         owner.syncThumbs();
115367     }
115368 });
115369
115370 /**
115371  * @class Ext.layout.container.Absolute
115372  * @extends Ext.layout.container.Anchor
115373  * <p>This is a layout that inherits the anchoring of <b>{@link Ext.layout.container.Anchor}</b> and adds the
115374  * ability for x/y positioning using the standard x and y component config options.</p>
115375  * <p>This class is intended to be extended or created via the <tt><b>{@link Ext.container.Container#layout layout}</b></tt>
115376  * configuration property.  See <tt><b>{@link Ext.container.Container#layout}</b></tt> for additional details.</p>
115377  * {@img Ext.layout.container.Absolute/Ext.layout.container.Absolute.png Ext.layout.container.Absolute container layout}
115378  * <p>Example usage:</p>
115379  * <pre><code>
115380     Ext.create('Ext.form.Panel', {
115381         title: 'Absolute Layout',
115382         width: 300,
115383         height: 275,
115384         layout:'absolute',
115385         layoutConfig: {
115386             // layout-specific configs go here
115387             //itemCls: 'x-abs-layout-item',
115388         },
115389         url:'save-form.php',
115390         defaultType: 'textfield',
115391         items: [{
115392             x: 10,
115393             y: 10,
115394             xtype:'label',
115395             text: 'Send To:'
115396         },{
115397             x: 80,
115398             y: 10,
115399             name: 'to',
115400             anchor:'90%'  // anchor width by percentage
115401         },{
115402             x: 10,
115403             y: 40,
115404             xtype:'label',
115405             text: 'Subject:'
115406         },{
115407             x: 80,
115408             y: 40,
115409             name: 'subject',
115410             anchor: '90%'  // anchor width by percentage
115411         },{
115412             x:0,
115413             y: 80,
115414             xtype: 'textareafield',
115415             name: 'msg',
115416             anchor: '100% 100%'  // anchor width and height
115417         }],
115418         renderTo: Ext.getBody()
115419     });
115420 </code></pre>
115421  */
115422
115423 Ext.define('Ext.layout.container.Absolute', {
115424
115425     /* Begin Definitions */
115426
115427     alias: 'layout.absolute',
115428     extend: 'Ext.layout.container.Anchor',
115429     requires: ['Ext.chart.axis.Axis', 'Ext.fx.Anim'],
115430     alternateClassName: 'Ext.layout.AbsoluteLayout',
115431
115432     /* End Definitions */
115433
115434     itemCls: Ext.baseCSSPrefix + 'abs-layout-item',
115435
115436     type: 'absolute',
115437
115438     onLayout: function() {
115439         var me = this,
115440             target = me.getTarget(),
115441             targetIsBody = target.dom === document.body;
115442
115443         // Do not set position: relative; when the absolute layout target is the body
115444         if (!targetIsBody) {
115445             target.position();
115446         }
115447         me.paddingLeft = target.getPadding('l');
115448         me.paddingTop = target.getPadding('t');
115449         me.callParent(arguments);
115450     },
115451
115452     // private
115453     adjustWidthAnchor: function(value, comp) {
115454         //return value ? value - comp.getPosition(true)[0] + this.paddingLeft: value;
115455         return value ? value - comp.getPosition(true)[0] : value;
115456     },
115457
115458     // private
115459     adjustHeightAnchor: function(value, comp) {
115460         //return value ? value - comp.getPosition(true)[1] + this.paddingTop: value;
115461         return value ? value - comp.getPosition(true)[1] : value;
115462     }
115463 });
115464 /**
115465  * @class Ext.layout.container.Accordion
115466  * @extends Ext.layout.container.VBox
115467  * <p>This is a layout that manages multiple Panels in an expandable accordion style such that only
115468  * <b>one Panel can be expanded at any given time</b>. Each Panel has built-in support for expanding and collapsing.</p>
115469  * <p>Note: Only Ext.Panels <b>and all subclasses of Ext.panel.Panel</b> may be used in an accordion layout Container.</p>
115470  * {@img Ext.layout.container.Accordion/Ext.layout.container.Accordion.png Ext.layout.container.Accordion container layout}
115471  * <p>Example usage:</p>
115472  * <pre><code>
115473     Ext.create('Ext.panel.Panel', {
115474         title: 'Accordion Layout',
115475         width: 300,
115476         height: 300,
115477         layout:'accordion',
115478         defaults: {
115479             // applied to each contained panel
115480             bodyStyle: 'padding:15px'
115481         },
115482         layoutConfig: {
115483             // layout-specific configs go here
115484             titleCollapse: false,
115485             animate: true,
115486             activeOnTop: true
115487         },
115488         items: [{
115489             title: 'Panel 1',
115490             html: '<p>Panel content!</p>'
115491         },{
115492             title: 'Panel 2',
115493             html: '<p>Panel content!</p>'
115494         },{
115495             title: 'Panel 3',
115496             html: '<p>Panel content!</p>'
115497         }],
115498         renderTo: Ext.getBody()
115499     });
115500 </code></pre>
115501  */
115502 Ext.define('Ext.layout.container.Accordion', {
115503     extend: 'Ext.layout.container.VBox',
115504     alias: ['layout.accordion'],
115505     alternateClassName: 'Ext.layout.AccordionLayout',
115506     
115507     align: 'stretch',
115508
115509     /**
115510      * @cfg {Boolean} fill
115511      * True to adjust the active item's height to fill the available space in the container, false to use the
115512      * item's current height, or auto height if not explicitly set (defaults to true).
115513      */
115514     fill : true,
115515     /**
115516      * @cfg {Boolean} autoWidth
115517      * <p><b>This config is ignored in ExtJS 4.x.</b></p>
115518      * Child Panels have their width actively managed to fit within the accordion's width.
115519      */
115520     autoWidth : true,
115521     /**
115522      * @cfg {Boolean} titleCollapse
115523      * <p><b>Not implemented in PR2.</b></p>
115524      * True to allow expand/collapse of each contained panel by clicking anywhere on the title bar, false to allow
115525      * expand/collapse only when the toggle tool button is clicked (defaults to true).  When set to false,
115526      * {@link #hideCollapseTool} should be false also.
115527      */
115528     titleCollapse : true,
115529     /**
115530      * @cfg {Boolean} hideCollapseTool
115531      * True to hide the contained Panels' collapse/expand toggle buttons, false to display them (defaults to false).
115532      * When set to true, {@link #titleCollapse} is automatically set to <code>true</code>.
115533      */
115534     hideCollapseTool : false,
115535     /**
115536      * @cfg {Boolean} collapseFirst
115537      * True to make sure the collapse/expand toggle button always renders first (to the left of) any other tools
115538      * in the contained Panels' title bars, false to render it last (defaults to false).
115539      */
115540     collapseFirst : false,
115541     /**
115542      * @cfg {Boolean} animate
115543      * True to slide the contained panels open and closed during expand/collapse using animation, false to open and
115544      * close directly with no animation (defaults to <code>true</code>). Note: The layout performs animated collapsing
115545      * and expanding, <i>not</i> the child Panels.
115546      */
115547     animate : true,
115548     /**
115549      * @cfg {Boolean} activeOnTop
115550      * <p><b>Not implemented in PR4.</b></p>
115551      * <p>Only valid when {@link #multi" is <code>false</code>.</p>
115552      * True to swap the position of each panel as it is expanded so that it becomes the first item in the container,
115553      * false to keep the panels in the rendered order. <b>This is NOT compatible with "animate:true"</b> (defaults to false).
115554      */
115555     activeOnTop : false,
115556     /**
115557      * @cfg {Boolean} multi
115558      * Defaults to <code>false</code>. Set to <code>true</code> to enable multiple accordion items to be open at once.
115559      */
115560     multi: false,
115561
115562     constructor: function() {
115563         var me = this;
115564
115565         me.callParent(arguments);
115566
115567         // animate flag must be false during initial render phase so we don't get animations.
115568         me.initialAnimate = me.animate;
115569         me.animate = false;
115570
115571         // Child Panels are not absolutely positioned if we are not filling, so use a different itemCls.
115572         if (me.fill === false) {
115573             me.itemCls = Ext.baseCSSPrefix + 'accordion-item';
115574         }
115575     },
115576
115577     // Cannot lay out a fitting accordion before we have been allocated a height.
115578     // So during render phase, layout will not be performed.
115579     beforeLayout: function() {
115580         var me = this;
115581
115582         me.callParent(arguments);
115583         if (me.fill) {
115584             if (!me.owner.el.dom.style.height) {
115585                 return false;
115586             }
115587         } else {
115588             me.owner.componentLayout.monitorChildren = false;
115589             me.autoSize = true;
115590             me.owner.setAutoScroll(true);
115591         }
115592     },
115593
115594     renderItems : function(items, target) {
115595         var me = this,
115596             ln = items.length,
115597             i = 0,
115598             comp,
115599             targetSize = me.getLayoutTargetSize(),
115600             renderedPanels = [],
115601             border;
115602
115603         for (; i < ln; i++) {
115604             comp = items[i];
115605             if (!comp.rendered) {
115606                 renderedPanels.push(comp);
115607
115608                 // Set up initial properties for Panels in an accordion.
115609                 if (me.collapseFirst) {
115610                     comp.collapseFirst = me.collapseFirst;
115611                 }
115612                 if (me.hideCollapseTool) {
115613                     comp.hideCollapseTool = me.hideCollapseTool;
115614                     comp.titleCollapse = true;
115615                 }
115616                 else if (me.titleCollapse) {
115617                     comp.titleCollapse = me.titleCollapse;
115618                 }
115619
115620                 delete comp.hideHeader;
115621                 comp.collapsible = true;
115622                 comp.title = comp.title || '&#160;';
115623                 comp.setBorder(false);
115624
115625                 // Set initial sizes
115626                 comp.width = targetSize.width;
115627                 if (me.fill) {
115628                     delete comp.height;
115629                     delete comp.flex;
115630
115631                     // If there is an expanded item, all others must be rendered collapsed.
115632                     if (me.expandedItem !== undefined) {
115633                         comp.collapsed = true;
115634                     }
115635                     // Otherwise expand the first item with collapsed explicitly configured as false
115636                     else if (comp.collapsed === false) {
115637                         comp.flex = 1;
115638                         me.expandedItem = i;
115639                     } else {
115640                         comp.collapsed = true;
115641                     }
115642                 } else {
115643                     delete comp.flex;
115644                     comp.animCollapse = me.initialAnimate;
115645                     comp.autoHeight = true;
115646                     comp.autoScroll = false;
115647                 }
115648             }
115649         }
115650
115651         // If no collapsed:false Panels found, make the first one expanded.
115652         if (ln && me.expandedItem === undefined) {
115653             me.expandedItem = 0;
115654             comp = items[0];
115655             comp.collapsed = false;
115656             if (me.fill) {
115657                 comp.flex = 1;
115658             }
115659         }
115660         
115661         // Render all Panels.
115662         me.callParent(arguments);
115663                 
115664         // Postprocess rendered Panels.
115665         ln = renderedPanels.length;
115666         for (i = 0; i < ln; i++) {
115667             comp = renderedPanels[i];
115668
115669             // Delete the dimension property so that our align: 'stretch' processing manages the width from here
115670             delete comp.width;
115671
115672             comp.header.addCls(Ext.baseCSSPrefix + 'accordion-hd');
115673             comp.body.addCls(Ext.baseCSSPrefix + 'accordion-body');
115674             
115675             // If we are fitting, then intercept expand/collapse requests. 
115676             if (me.fill) {
115677                 me.owner.mon(comp, {
115678                     show: me.onComponentShow,
115679                     beforeexpand: me.onComponentExpand,
115680                     beforecollapse: me.onComponentCollapse,
115681                     scope: me
115682                 });
115683             }
115684         }
115685     },
115686
115687     onLayout: function() {
115688         var me = this;
115689         
115690         me.updatePanelClasses();
115691                 
115692         if (me.fill) {
115693             me.callParent(arguments);
115694         } else {
115695             var targetSize = me.getLayoutTargetSize(),
115696                 items = me.getVisibleItems(),
115697                 len = items.length,
115698                 i = 0, comp;
115699
115700             for (; i < len; i++) {
115701                 comp = items[i];
115702                 if (comp.collapsed) {
115703                     items[i].setWidth(targetSize.width);
115704                 } else {
115705                     items[i].setSize(null, null);
115706                 }
115707             }
115708         }
115709         
115710         return me;
115711     },
115712     
115713     updatePanelClasses: function() {
115714         var children = this.getLayoutItems(),
115715             ln = children.length,
115716             siblingCollapsed = true,
115717             i, child;
115718             
115719         for (i = 0; i < ln; i++) {
115720             child = children[i];
115721             if (!siblingCollapsed) {
115722                 child.header.addCls(Ext.baseCSSPrefix + 'accordion-hd-sibling-expanded');
115723             }
115724             else {
115725                 child.header.removeCls(Ext.baseCSSPrefix + 'accordion-hd-sibling-expanded');
115726             }
115727             if (i + 1 == ln && child.collapsed) {
115728                 child.header.addCls(Ext.baseCSSPrefix + 'accordion-hd-last-collapsed');
115729             }
115730             else {
115731                 child.header.removeCls(Ext.baseCSSPrefix + 'accordion-hd-last-collapsed');
115732             }
115733             siblingCollapsed = child.collapsed;
115734         }
115735     },
115736
115737     // When a Component expands, adjust the heights of the other Components to be just enough to accommodate
115738     // their headers.
115739     // The expanded Component receives the only flex value, and so gets all remaining space.
115740     onComponentExpand: function(toExpand) {
115741         var me = this,
115742             it = me.owner.items.items,
115743             len = it.length,
115744             i = 0,
115745             comp;
115746
115747         for (; i < len; i++) {
115748             comp = it[i];
115749             if (comp === toExpand && comp.collapsed) {
115750                 me.setExpanded(comp);
115751             } else if (!me.multi && (comp.rendered && comp.header.rendered && comp !== toExpand && !comp.collapsed)) {
115752                 me.setCollapsed(comp);
115753             }
115754         }
115755         
115756         me.animate = me.initialAnimate;
115757         me.layout();
115758         me.animate = false;
115759         return false;
115760     },
115761
115762     onComponentCollapse: function(comp) {
115763         var me = this,
115764             toExpand = comp.next() || comp.prev(),
115765             expanded = me.multi ? me.owner.query('>panel:not([collapsed])') : [];
115766
115767         // If we are allowing multi, and the "toCollapse" component is NOT the only expanded Component,
115768         // then ask the box layout to collapse it to its header.
115769         if (me.multi) {
115770             me.setCollapsed(comp);
115771
115772             // If the collapsing Panel is the only expanded one, expand the following Component.
115773             // All this is handling fill: true, so there must be at least one expanded,
115774             if (expanded.length === 1 && expanded[0] === comp) {
115775                 me.setExpanded(toExpand);
115776             }
115777             
115778             me.animate = me.initialAnimate;
115779             me.layout();
115780             me.animate = false;
115781         }
115782         // Not allowing multi: expand the next sibling if possible, prev sibling if we collapsed the last
115783         else if (toExpand) {
115784             me.onComponentExpand(toExpand);
115785         }
115786         return false;
115787     },
115788
115789     onComponentShow: function(comp) {
115790         // Showing a Component means that you want to see it, so expand it.
115791         this.onComponentExpand(comp);
115792     },
115793
115794     setCollapsed: function(comp) {
115795         var otherDocks = comp.getDockedItems(),
115796             dockItem,
115797             len = otherDocks.length,
115798             i = 0;
115799
115800         // Hide all docked items except the header
115801         comp.hiddenDocked = [];
115802         for (; i < len; i++) {
115803             dockItem = otherDocks[i];
115804             if ((dockItem !== comp.header) && !dockItem.hidden) {
115805                 dockItem.hidden = true;
115806                 comp.hiddenDocked.push(dockItem);
115807             }
115808         }
115809         comp.addCls(comp.collapsedCls);
115810         comp.header.addCls(comp.collapsedHeaderCls);
115811         comp.height = comp.header.getHeight();
115812         comp.el.setHeight(comp.height);
115813         comp.collapsed = true;
115814         delete comp.flex;
115815         comp.fireEvent('collapse', comp);
115816         if (comp.collapseTool) {
115817             comp.collapseTool.setType('expand-' + comp.getOppositeDirection(comp.collapseDirection));
115818         }
115819     },
115820
115821     setExpanded: function(comp) {
115822         var otherDocks = comp.hiddenDocked,
115823             len = otherDocks ? otherDocks.length : 0,
115824             i = 0;
115825
115826         // Show temporarily hidden docked items
115827         for (; i < len; i++) {
115828             otherDocks[i].hidden = false;
115829         }
115830
115831         // If it was an initial native collapse which hides the body
115832         if (!comp.body.isVisible()) {
115833             comp.body.show();
115834         }
115835         delete comp.collapsed;
115836         delete comp.height;
115837         delete comp.componentLayout.lastComponentSize;
115838         comp.suspendLayout = false;
115839         comp.flex = 1;
115840         comp.removeCls(comp.collapsedCls);
115841         comp.header.removeCls(comp.collapsedHeaderCls);
115842         comp.fireEvent('expand', comp);
115843         if (comp.collapseTool) {
115844             comp.collapseTool.setType('collapse-' + comp.collapseDirection);
115845         }
115846         comp.setAutoScroll(comp.initialConfig.autoScroll);
115847     }
115848 });
115849 /**
115850  * @class Ext.resizer.Splitter
115851  * @extends Ext.Component
115852  * <p>This class functions <b>between siblings of a {@link Ext.layout.container.VBox VBox} or {@link Ext.layout.container.HBox HBox}
115853  * layout</b> to resize both immediate siblings.</p>
115854  * <p>By default it will set the size of both siblings. <b>One</b> of the siblings may be configured with
115855  * <code>{@link Ext.Component#maintainFlex maintainFlex}: true</code> which will cause it not to receive a new size explicitly, but to be resized
115856  * by the layout.</p>
115857  * <p>A Splitter may be configured to show a centered mini-collapse tool orientated to collapse the {@link #collapseTarget}.
115858  * The Splitter will then call that sibling Panel's {@link Ext.panel.Panel#collapse collapse} or {@link Ext.panel.Panel#expand expand} method
115859  * to perform the appropriate operation (depending on the sibling collapse state). To create the mini-collapse tool but take care
115860  * of collapsing yourself, configure the splitter with <code>{@link #performCollapse} false</code>.</p>
115861  *
115862  * @xtype splitter
115863  */
115864 Ext.define('Ext.resizer.Splitter', {
115865     extend: 'Ext.Component',
115866     requires: ['Ext.XTemplate'],
115867     uses: ['Ext.resizer.SplitterTracker'],
115868     alias: 'widget.splitter',
115869
115870     renderTpl: [
115871         '<tpl if="collapsible===true"><div class="' + Ext.baseCSSPrefix + 'collapse-el ' + Ext.baseCSSPrefix + 'layout-split-{collapseDir}">&nbsp;</div></tpl>'
115872     ],
115873
115874     baseCls: Ext.baseCSSPrefix + 'splitter',
115875     collapsedCls: Ext.baseCSSPrefix + 'splitter-collapsed',
115876
115877     /**
115878      * @cfg {Boolean} collapsible
115879      * <code>true</code> to show a mini-collapse tool in the Splitter to toggle expand and collapse on the {@link #collapseTarget} Panel.
115880      * Defaults to the {@link Ext.panel.Panel#collapsible collapsible} setting of the Panel.
115881      */
115882     collapsible: false,
115883
115884     /**
115885      * @cfg {Boolean} performCollapse
115886      * <p>Set to <code>false</code> to prevent this Splitter's mini-collapse tool from managing the collapse
115887      * state of the {@link #collapseTarget}.</p>
115888      */
115889
115890     /**
115891      * @cfg {Boolean} collapseOnDblClick
115892      * <code>true</code> to enable dblclick to toggle expand and collapse on the {@link #collapseTarget} Panel.
115893      */
115894     collapseOnDblClick: true,
115895
115896     /**
115897      * @cfg {Number} defaultSplitMin
115898      * Provides a default minimum width or height for the two components
115899      * that the splitter is between.
115900      */
115901     defaultSplitMin: 40,
115902
115903     /**
115904      * @cfg {Number} defaultSplitMax
115905      * Provides a default maximum width or height for the two components
115906      * that the splitter is between.
115907      */
115908     defaultSplitMax: 1000,
115909
115910     width: 5,
115911     height: 5,
115912
115913     /**
115914      * @cfg {Mixed} collapseTarget
115915      * <p>A string describing the relative position of the immediate sibling Panel to collapse. May be 'prev' or 'next' (Defaults to 'next')</p>
115916      * <p>Or the immediate sibling Panel to collapse.</p>
115917      * <p>The orientation of the mini-collapse tool will be inferred from this setting.</p>
115918      * <p><b>Note that only Panels may be collapsed.</b></p>
115919      */
115920     collapseTarget: 'next',
115921
115922     /**
115923      * @property orientation
115924      * @type String
115925      * Orientation of this Splitter. <code>'vertical'</code> when used in an hbox layout, <code>'horizontal'</code>
115926      * when used in a vbox layout.
115927      */
115928
115929     onRender: function() {
115930         var me = this,
115931             target = me.getCollapseTarget(),
115932             collapseDir = me.getCollapseDirection();
115933
115934         Ext.applyIf(me.renderData, {
115935             collapseDir: collapseDir,
115936             collapsible: me.collapsible || target.collapsible
115937         });
115938         Ext.applyIf(me.renderSelectors, {
115939             collapseEl: '.' + Ext.baseCSSPrefix + 'collapse-el'
115940         });
115941
115942         this.callParent(arguments);
115943
115944         // Add listeners on the mini-collapse tool unless performCollapse is set to false
115945         if (me.performCollapse !== false) {
115946             if (me.renderData.collapsible) {
115947                 me.mon(me.collapseEl, 'click', me.toggleTargetCmp, me);
115948             }
115949             if (me.collapseOnDblClick) {
115950                 me.mon(me.el, 'dblclick', me.toggleTargetCmp, me);
115951             }
115952         }
115953
115954         // Ensure the mini collapse icon is set to the correct direction when the target is collapsed/expanded by any means
115955         me.mon(target, 'collapse', me.onTargetCollapse, me);
115956         me.mon(target, 'expand', me.onTargetExpand, me);
115957
115958         me.el.addCls(me.baseCls + '-' + me.orientation);
115959         me.el.unselectable();
115960
115961         me.tracker = Ext.create('Ext.resizer.SplitterTracker', {
115962             el: me.el
115963         });
115964     },
115965
115966     getCollapseDirection: function() {
115967         var me = this,
115968             idx,
115969             type = me.ownerCt.layout.type;
115970
115971         // Avoid duplication of string tests.
115972         // Create a two bit truth table of the configuration of the Splitter:
115973         // Collapse Target | orientation
115974         //        0              0             = next, horizontal
115975         //        0              1             = next, vertical
115976         //        1              0             = prev, horizontal
115977         //        1              1             = prev, vertical
115978         if (me.collapseTarget.isComponent) {
115979             idx = Number(me.ownerCt.items.indexOf(me.collapseTarget) == me.ownerCt.items.indexOf(me) - 1) << 1 | Number(type == 'hbox');
115980         } else {
115981             idx = Number(me.collapseTarget == 'prev') << 1 | Number(type == 'hbox');
115982         }
115983
115984         // Read the data out the truth table
115985         me.orientation = ['horizontal', 'vertical'][idx & 1];
115986         return ['bottom', 'right', 'top', 'left'][idx];
115987     },
115988
115989     getCollapseTarget: function() {
115990         return this.collapseTarget.isComponent ? this.collapseTarget : this.collapseTarget == 'prev' ? this.previousSibling() : this.nextSibling();
115991     },
115992
115993     onTargetCollapse: function(target) {
115994         this.el.addCls(this.collapsedCls);
115995     },
115996
115997     onTargetExpand: function(target) {
115998         this.el.removeCls(this.collapsedCls);
115999     },
116000
116001     toggleTargetCmp: function(e, t) {
116002         var cmp = this.getCollapseTarget();
116003
116004         if (cmp.isVisible()) {
116005             // restore
116006             if (cmp.collapsed) {
116007                 cmp.expand(cmp.animCollapse);
116008             // collapse
116009             } else {
116010                 cmp.collapse(this.renderData.collapseDir, cmp.animCollapse);
116011             }
116012         }
116013     },
116014
116015     /*
116016      * Work around IE bug. %age margins do not get recalculated on element resize unless repaint called.
116017      */
116018     setSize: function() {
116019         var me = this;
116020         me.callParent(arguments);
116021         if (Ext.isIE) {
116022             me.el.repaint();
116023         }
116024     }
116025 });
116026
116027 /**
116028  * @class Ext.layout.container.Border
116029  * @extends Ext.layout.container.Container
116030  * <p>This is a multi-pane, application-oriented UI layout style that supports multiple
116031  * nested panels, automatic bars between regions and built-in
116032  * {@link Ext.panel.Panel#collapsible expanding and collapsing} of regions.</p>
116033  * <p>This class is intended to be extended or created via the <code>layout:'border'</code>
116034  * {@link Ext.container.Container#layout} config, and should generally not need to be created directly
116035  * via the new keyword.</p>
116036  * {@img Ext.layout.container.Border/Ext.layout.container.Border.png Ext.layout.container.Border container layout}
116037  * <p>Example usage:</p>
116038  * <pre><code>
116039      Ext.create('Ext.panel.Panel', {
116040         width: 500,
116041         height: 400,
116042         title: 'Border Layout',
116043         layout: 'border',
116044         items: [{
116045             title: 'South Region is resizable',
116046             region: 'south',     // position for region
116047             xtype: 'panel',
116048             height: 100,
116049             split: true,         // enable resizing
116050             margins: '0 5 5 5'
116051         },{
116052             // xtype: 'panel' implied by default
116053             title: 'West Region is collapsible',
116054             region:'west',
116055             xtype: 'panel',
116056             margins: '5 0 0 5',
116057             width: 200,
116058             collapsible: true,   // make collapsible
116059             id: 'west-region-container',
116060             layout: 'fit'
116061         },{
116062             title: 'Center Region',
116063             region: 'center',     // center region is required, no width/height specified
116064             xtype: 'panel',
116065             layout: 'fit',
116066             margins: '5 5 0 0'
116067         }],
116068         renderTo: Ext.getBody()
116069     });
116070 </code></pre>
116071  * <p><b><u>Notes</u></b>:</p><div class="mdetail-params"><ul>
116072  * <li>Any Container using the Border layout <b>must</b> have a child item with <code>region:'center'</code>.
116073  * The child item in the center region will always be resized to fill the remaining space not used by
116074  * the other regions in the layout.</li>
116075  * <li>Any child items with a region of <code>west</code> or <code>east</code> may be configured with either
116076  * an initial <code>width</code>, or a {@link Ext.layout.container.Box#flex} value, or an initial percentage width <b>string</b> (Which is simply divided by 100 and used as a flex value). The 'center' region has a flex value of <code>1</code>.</li>
116077  * <li>Any child items with a region of <code>north</code> or <code>south</code> may be configured with either
116078  * an initial <code>height</code>, or a {@link Ext.layout.container.Box#flex} value, or an initial percentage height <b>string</b> (Which is simply divided by 100 and used as a flex value). The 'center' region has a flex value of <code>1</code>.</li>
116079  * <li>The regions of a BorderLayout are <b>fixed at render time</b> and thereafter, its child Components may not be removed or added</b>.To add/remove
116080  * Components within a BorderLayout, have them wrapped by an additional Container which is directly
116081  * managed by the BorderLayout.  If the region is to be collapsible, the Container used directly
116082  * by the BorderLayout manager should be a Panel.  In the following example a Container (an Ext.panel.Panel)
116083  * is added to the west region:<pre><code>
116084 wrc = {@link Ext#getCmp Ext.getCmp}('west-region-container');
116085 wrc.{@link Ext.container.Container#removeAll removeAll}();
116086 wrc.{@link Ext.container.Container#add add}({
116087     title: 'Added Panel',
116088     html: 'Some content'
116089 });
116090  * </code></pre>
116091  * </li>
116092  * <li><b>There is no BorderLayout.Region class in ExtJS 4.0+</b></li>
116093  * </ul></div>
116094  */
116095 Ext.define('Ext.layout.container.Border', {
116096
116097     alias: ['layout.border'],
116098     extend: 'Ext.layout.container.Container',
116099     requires: ['Ext.resizer.Splitter', 'Ext.container.Container', 'Ext.fx.Anim'],
116100     alternateClassName: 'Ext.layout.BorderLayout',
116101
116102     targetCls: Ext.baseCSSPrefix + 'border-layout-ct',
116103
116104     itemCls: Ext.baseCSSPrefix + 'border-item',
116105
116106     bindToOwnerCtContainer: true,
116107
116108     fixedLayout: false,
116109
116110     percentageRe: /(\d+)%/,
116111
116112     slideDirection: {
116113         north: 't',
116114         south: 'b',
116115         west: 'l',
116116         east: 'r'
116117     },
116118
116119     constructor: function(config) {
116120         this.initialConfig = config;
116121         this.callParent(arguments);
116122     },
116123
116124     onLayout: function() {
116125         var me = this;
116126         if (!me.borderLayoutInitialized) {
116127             me.initializeBorderLayout();
116128         }
116129
116130         // Delegate this operation to the shadow "V" or "H" box layout, and then down to any embedded layout.
116131         me.shadowLayout.onLayout();
116132         if (me.embeddedContainer) {
116133             me.embeddedContainer.layout.onLayout();
116134         }
116135
116136         // If the panel was originally configured with collapsed: true, it will have
116137         // been initialized with a "borderCollapse" flag: Collapse it now before the first layout.
116138         if (!me.initialCollapsedComplete) {
116139             Ext.iterate(me.regions, function(name, region){
116140                 if (region.borderCollapse) {
116141                     me.onBeforeRegionCollapse(region, region.collapseDirection, false, 0);
116142                 }
116143             });
116144             me.initialCollapsedComplete = true;
116145         }
116146     },
116147
116148     isValidParent : function(item, target, position) {
116149         if (!this.borderLayoutInitialized) {
116150             this.initializeBorderLayout();
116151         }
116152
116153         // Delegate this operation to the shadow "V" or "H" box layout.
116154         return this.shadowLayout.isValidParent(item, target, position);
116155     },
116156
116157     beforeLayout: function() {
116158         if (!this.borderLayoutInitialized) {
116159             this.initializeBorderLayout();
116160         }
116161
116162         // Delegate this operation to the shadow "V" or "H" box layout.
116163         this.shadowLayout.beforeLayout();
116164     },
116165
116166     renderItems: function(items, target) {
116167         Ext.Error.raise('This should not be called');
116168     },
116169
116170     renderItem: function(item) {
116171         Ext.Error.raise('This should not be called');
116172     },
116173
116174     initializeBorderLayout: function() {
116175         var me = this,
116176             i = 0,
116177             items = me.getLayoutItems(),
116178             ln = items.length,
116179             regions = (me.regions = {}),
116180             vBoxItems = [],
116181             hBoxItems = [],
116182             horizontalFlex = 0,
116183             verticalFlex = 0,
116184             comp, percentage;
116185
116186         // Map of Splitters for each region
116187         me.splitters = {};
116188
116189         // Map of regions
116190         for (; i < ln; i++) {
116191             comp = items[i];
116192             regions[comp.region] = comp;
116193
116194             // Intercept collapsing to implement showing an alternate Component as a collapsed placeholder
116195             if (comp.region != 'center' && comp.collapsible && comp.collapseMode != 'header') {
116196
116197                 // This layout intercepts any initial collapsed state. Panel must not do this itself.
116198                 comp.borderCollapse = comp.collapsed;
116199                 delete comp.collapsed;
116200
116201                 comp.on({
116202                     beforecollapse: me.onBeforeRegionCollapse,
116203                     beforeexpand: me.onBeforeRegionExpand,
116204                     destroy: me.onRegionDestroy,
116205                     scope: me
116206                 });
116207                 me.setupState(comp);
116208             }
116209         }
116210         if (!regions.center) {
116211             Ext.Error.raise("You must specify a center region when defining a BorderLayout.");
116212         }
116213         comp = regions.center;
116214         if (!comp.flex) {
116215             comp.flex = 1;
116216         }
116217         delete comp.width;
116218         comp.maintainFlex = true;
116219
116220         // Begin the VBox and HBox item list.
116221         comp = regions.west;
116222         if (comp) {
116223             comp.collapseDirection = Ext.Component.DIRECTION_LEFT;
116224             hBoxItems.push(comp);
116225             if (comp.split) {
116226                 hBoxItems.push(me.splitters.west = me.createSplitter(comp));
116227             }
116228             percentage = Ext.isString(comp.width) && comp.width.match(me.percentageRe);
116229             if (percentage) {
116230                 horizontalFlex += (comp.flex = parseInt(percentage[1], 10) / 100);
116231                 delete comp.width;
116232             }
116233         }
116234         comp = regions.north;
116235         if (comp) {
116236             comp.collapseDirection = Ext.Component.DIRECTION_TOP;
116237             vBoxItems.push(comp);
116238             if (comp.split) {
116239                 vBoxItems.push(me.splitters.north = me.createSplitter(comp));
116240             }
116241             percentage = Ext.isString(comp.height) && comp.height.match(me.percentageRe);
116242             if (percentage) {
116243                 verticalFlex += (comp.flex = parseInt(percentage[1], 10) / 100);
116244                 delete comp.height;
116245             }
116246         }
116247
116248         // Decide into which Collection the center region goes.
116249         if (regions.north || regions.south) {
116250             if (regions.east || regions.west) {
116251
116252                 // Create the embedded center. Mark it with the region: 'center' property so that it can be identified as the center.
116253                 vBoxItems.push(me.embeddedContainer = Ext.create('Ext.container.Container', {
116254                     xtype: 'container',
116255                     region: 'center',
116256                     id: me.owner.id + '-embedded-center',
116257                     cls: Ext.baseCSSPrefix + 'border-item',
116258                     flex: regions.center.flex,
116259                     maintainFlex: true,
116260                     layout: {
116261                         type: 'hbox',
116262                         align: 'stretch'
116263                     }
116264                 }));
116265                 hBoxItems.push(regions.center);
116266             }
116267             // No east or west: the original center goes straight into the vbox
116268             else {
116269                 vBoxItems.push(regions.center);
116270             }
116271         }
116272         // If we have no north or south, then the center is part of the HBox items
116273         else {
116274             hBoxItems.push(regions.center);
116275         }
116276
116277         // Finish off the VBox and HBox item list.
116278         comp = regions.south;
116279         if (comp) {
116280             comp.collapseDirection = Ext.Component.DIRECTION_BOTTOM;
116281             if (comp.split) {
116282                 vBoxItems.push(me.splitters.south = me.createSplitter(comp));
116283             }
116284             percentage = Ext.isString(comp.height) && comp.height.match(me.percentageRe);
116285             if (percentage) {
116286                 verticalFlex += (comp.flex = parseInt(percentage[1], 10) / 100);
116287                 delete comp.height;
116288             }
116289             vBoxItems.push(comp);
116290         }
116291         comp = regions.east;
116292         if (comp) {
116293             comp.collapseDirection = Ext.Component.DIRECTION_RIGHT;
116294             if (comp.split) {
116295                 hBoxItems.push(me.splitters.east = me.createSplitter(comp));
116296             }
116297             percentage = Ext.isString(comp.width) && comp.width.match(me.percentageRe);
116298             if (percentage) {
116299                 horizontalFlex += (comp.flex = parseInt(percentage[1], 10) / 100);
116300                 delete comp.width;
116301             }
116302             hBoxItems.push(comp);
116303         }
116304
116305         // Create the injected "items" collections for the Containers.
116306         // If we have north or south, then the shadow Container will be a VBox.
116307         // If there are also east or west regions, its center will be a shadow HBox.
116308         // If there are *only* east or west regions, then the shadow layout will be an HBox (or Fit).
116309         if (regions.north || regions.south) {
116310
116311             me.shadowContainer = Ext.create('Ext.container.Container', {
116312                 ownerCt: me.owner,
116313                 el: me.getTarget(),
116314                 layout: Ext.applyIf({
116315                     type: 'vbox',
116316                     align: 'stretch'
116317                 }, me.initialConfig)
116318             });
116319             me.createItems(me.shadowContainer, vBoxItems);
116320
116321             // Allow the Splitters to orientate themselves
116322             if (me.splitters.north) {
116323                 me.splitters.north.ownerCt = me.shadowContainer;
116324             }
116325             if (me.splitters.south) {
116326                 me.splitters.south.ownerCt = me.shadowContainer;
116327             }
116328
116329             // Inject items into the HBox Container if there is one - if there was an east or west.
116330             if (me.embeddedContainer) {
116331                 me.embeddedContainer.ownerCt = me.shadowContainer;
116332                 me.createItems(me.embeddedContainer, hBoxItems);
116333
116334                 // Allow the Splitters to orientate themselves
116335                 if (me.splitters.east) {
116336                     me.splitters.east.ownerCt = me.embeddedContainer;
116337                 }
116338                 if (me.splitters.west) {
116339                     me.splitters.west.ownerCt = me.embeddedContainer;
116340                 }
116341
116342                 // The east or west region wanted a percentage
116343                 if (horizontalFlex) {
116344                     regions.center.flex -= horizontalFlex;
116345                 }
116346                 // The north or south region wanted a percentage
116347                 if (verticalFlex) {
116348                     me.embeddedContainer.flex -= verticalFlex;
116349                 }
116350             } else {
116351                 // The north or south region wanted a percentage
116352                 if (verticalFlex) {
116353                     regions.center.flex -= verticalFlex;
116354                 }
116355             }
116356         }
116357         // If we have no north or south, then there's only one Container, and it's
116358         // an HBox, or, if only a center region was specified, a Fit.
116359         else {
116360             me.shadowContainer = Ext.create('Ext.container.Container', {
116361                 ownerCt: me.owner,
116362                 el: me.getTarget(),
116363                 layout: Ext.applyIf({
116364                     type: (hBoxItems.length == 1) ? 'fit' : 'hbox',
116365                     align: 'stretch'
116366                 }, me.initialConfig)
116367             });
116368             me.createItems(me.shadowContainer, hBoxItems);
116369
116370             // Allow the Splitters to orientate themselves
116371             if (me.splitters.east) {
116372                 me.splitters.east.ownerCt = me.shadowContainer;
116373             }
116374             if (me.splitters.west) {
116375                 me.splitters.west.ownerCt = me.shadowContainer;
116376             }
116377
116378             // The east or west region wanted a percentage
116379             if (horizontalFlex) {
116380                 regions.center.flex -= verticalFlex;
116381             }
116382         }
116383
116384         // Create upward links from the region Components to their shadow ownerCts
116385         for (i = 0, items = me.shadowContainer.items.items, ln = items.length; i < ln; i++) {
116386             items[i].shadowOwnerCt = me.shadowContainer;
116387         }
116388         if (me.embeddedContainer) {
116389             for (i = 0, items = me.embeddedContainer.items.items, ln = items.length; i < ln; i++) {
116390                 items[i].shadowOwnerCt = me.embeddedContainer;
116391             }
116392         }
116393
116394         // This is the layout that we delegate all operations to
116395         me.shadowLayout = me.shadowContainer.getLayout();
116396
116397         me.borderLayoutInitialized = true;
116398     },
116399
116400
116401     setupState: function(comp){
116402         var getState = comp.getState;
116403         comp.getState = function(){
116404             // call the original getState
116405             var state = getState.call(comp) || {},
116406                 region = comp.region;
116407
116408             state.collapsed = !!comp.collapsed;
116409             if (region == 'west' || region == 'east') {
116410                 state.width = comp.getWidth();
116411             } else {
116412                 state.height = comp.getHeight();
116413             }
116414             return state;
116415         };
116416         comp.addStateEvents(['collapse', 'expand', 'resize']);
116417     },
116418
116419     /**
116420      * Create the items collection for our shadow/embedded containers
116421      * @private
116422      */
116423     createItems: function(container, items){
116424         // Have to inject an items Collection *after* construction.
116425         // The child items of the shadow layout must retain their original, user-defined ownerCt
116426         delete container.items;
116427         container.initItems();
116428         container.items.addAll(items);
116429     },
116430
116431     // Private
116432     // Create a splitter for a child of the layout.
116433     createSplitter: function(comp) {
116434         var me = this,
116435             interceptCollapse = (comp.collapseMode != 'header'),
116436             resizer;
116437
116438         resizer = Ext.create('Ext.resizer.Splitter', {
116439             hidden: !!comp.hidden,
116440             collapseTarget: comp,
116441             performCollapse: !interceptCollapse,
116442             listeners: interceptCollapse ? {
116443                 click: {
116444                     fn: Ext.Function.bind(me.onSplitterCollapseClick, me, [comp]),
116445                     element: 'collapseEl'
116446                 }
116447             } : null
116448         });
116449
116450         // Mini collapse means that the splitter is the placeholder Component
116451         if (comp.collapseMode == 'mini') {
116452             comp.placeholder = resizer;
116453         }
116454
116455         // Arrange to hide/show a region's associated splitter when the region is hidden/shown
116456         comp.on({
116457             hide: me.onRegionVisibilityChange,
116458             show: me.onRegionVisibilityChange,
116459             scope: me
116460         });
116461         return resizer;
116462     },
116463
116464     // Hide/show a region's associated splitter when the region is hidden/shown
116465     onRegionVisibilityChange: function(comp){
116466         this.splitters[comp.region][comp.hidden ? 'hide' : 'show']();
116467         this.layout();
116468     },
116469
116470     // Called when a splitter mini-collapse tool is clicked on.
116471     // The listener is only added if this layout is controlling collapsing,
116472     // not if the component's collapseMode is 'mini' or 'header'.
116473     onSplitterCollapseClick: function(comp) {
116474         if (comp.collapsed) {
116475             this.onPlaceHolderToolClick(null, null, null, {client: comp});
116476         } else {
116477             comp.collapse();
116478         }
116479     },
116480
116481     /**
116482      * <p>Return the {@link Ext.panel.Panel#placeholder placeholder} Component to which the passed child Panel of the layout will collapse.
116483      * By default, this will be a {@link Ext.panel.Header Header} component (Docked to the appropriate border). See {@link Ext.panel.Panel#placeholder placeholder}.
116484      * config to customize this.</p>
116485      * <p><b>Note that this will be a fully instantiated Component, but will only be <i>rendered</i> when the Panel is first collapsed.</b></p>
116486      * @param {Panel} panel The child Panel of the layout for which to return the {@link Ext.panel.Panel#placeholder placeholder}.
116487      * @returns {Component} The Panel's {@link Ext.panel.Panel#placeholder placeholder} unless the {@link Ext.panel.Panel#collapseMode collapseMode} is
116488      * <code>'header'</code>, in which case <i>undefined</i> is returned.
116489      */
116490     getPlaceholder: function(comp) {
116491         var me = this,
116492             placeholder = comp.placeholder,
116493             shadowContainer = comp.shadowOwnerCt,
116494             shadowLayout = shadowContainer.layout,
116495             oppositeDirection = Ext.panel.Panel.prototype.getOppositeDirection(comp.collapseDirection),
116496             horiz = (comp.region == 'north' || comp.region == 'south');
116497
116498         // No placeholder if the collapse mode is not the Border layout default
116499         if (comp.collapseMode == 'header') {
116500             return;
116501         }
116502
116503         // Provide a replacement Container with an expand tool
116504         if (!placeholder) {
116505             if (comp.collapseMode == 'mini') {
116506                 placeholder = Ext.create('Ext.resizer.Splitter', {
116507                     id: 'collapse-placeholder-' + comp.id,
116508                     collapseTarget: comp,
116509                     performCollapse: false,
116510                     listeners: {
116511                         click: {
116512                             fn: Ext.Function.bind(me.onSplitterCollapseClick, me, [comp]),
116513                             element: 'collapseEl'
116514                         }
116515                     }
116516                 });
116517                 placeholder.addCls(placeholder.collapsedCls);
116518             } else {
116519                 placeholder = {
116520                     id: 'collapse-placeholder-' + comp.id,
116521                     margins: comp.initialConfig.margins || Ext.getClass(comp).prototype.margins,
116522                     xtype: 'header',
116523                     orientation: horiz ? 'horizontal' : 'vertical',
116524                     title: comp.title,
116525                     textCls: comp.headerTextCls,
116526                     iconCls: comp.iconCls,
116527                     baseCls: comp.baseCls + '-header',
116528                     ui: comp.ui,
116529                     indicateDrag: comp.draggable,
116530                     cls: Ext.baseCSSPrefix + 'region-collapsed-placeholder ' + Ext.baseCSSPrefix + 'region-collapsed-' + comp.collapseDirection + '-placeholder',
116531                     listeners: comp.floatable ? {
116532                         click: {
116533                             fn: function(e) {
116534                                 me.floatCollapsedPanel(e, comp);
116535                             },
116536                             element: 'el'
116537                         }
116538                     } : null
116539                 };
116540                 // Hack for IE6/7/IEQuirks's inability to display an inline-block
116541                 if ((Ext.isIE6 || Ext.isIE7 || (Ext.isIEQuirks)) && !horiz) {
116542                     placeholder.width = 25;
116543                 }
116544                 placeholder[horiz ? 'tools' : 'items'] = [{
116545                     xtype: 'tool',
116546                     client: comp,
116547                     type: 'expand-' + oppositeDirection,
116548                     handler: me.onPlaceHolderToolClick,
116549                     scope: me
116550                 }];
116551             }
116552             placeholder = me.owner.createComponent(placeholder);
116553             if (comp.isXType('panel')) {
116554                 comp.on({
116555                     titlechange: me.onRegionTitleChange,
116556                     iconchange: me.onRegionIconChange,
116557                     scope: me
116558                 });
116559             }
116560         }
116561
116562         // The collapsed Component holds a reference to its placeholder and vice versa
116563         comp.placeholder = placeholder;
116564         placeholder.comp = comp;
116565
116566         return placeholder;
116567     },
116568
116569     /**
116570      * @private
116571      * Update the placeholder title when panel title has been set or changed.
116572      */
116573     onRegionTitleChange: function(comp, newTitle) {
116574         comp.placeholder.setTitle(newTitle);
116575     },
116576
116577     /**
116578      * @private
116579      * Update the placeholder iconCls when panel iconCls has been set or changed.
116580      */
116581     onRegionIconChange: function(comp, newIconCls) {
116582         comp.placeholder.setIconCls(newIconCls);
116583     },
116584
116585     /**
116586      * @private
116587      * Calculates the size and positioning of the passed child item. Must be present because Panel's expand,
116588      * when configured with a flex, calls this method on its ownerCt's layout.
116589      * @param {Component} child The child Component to calculate the box for
116590      * @return {Object} Object containing box measurements for the child. Properties are left,top,width,height.
116591      */
116592     calculateChildBox: function(comp) {
116593         var me = this;
116594         if (me.shadowContainer.items.contains(comp)) {
116595             return me.shadowContainer.layout.calculateChildBox(comp);
116596         }
116597         else if (me.embeddedContainer && me.embeddedContainer.items.contains(comp)) {
116598             return me.embeddedContainer.layout.calculateChildBox(comp);
116599         }
116600     },
116601
116602     /**
116603      * @private
116604      * Intercepts the Panel's own collapse event and perform's substitution of the Panel
116605      * with a placeholder Header orientated in the appropriate dimension.
116606      * @param comp The Panel being collapsed.
116607      * @param direction
116608      * @param animate
116609      * @returns {Boolean} false to inhibit the Panel from performing its own collapse.
116610      */
116611     onBeforeRegionCollapse: function(comp, direction, animate) {
116612         var me = this,
116613             compEl = comp.el,
116614             miniCollapse = comp.collapseMode == 'mini',
116615             shadowContainer = comp.shadowOwnerCt,
116616             shadowLayout = shadowContainer.layout,
116617             placeholder = comp.placeholder,
116618             placeholderBox,
116619             targetSize = shadowLayout.getLayoutTargetSize(),
116620             sl = me.owner.suspendLayout,
116621             scsl = shadowContainer.suspendLayout,
116622             isNorthOrWest = (comp.region == 'north' || comp.region == 'west'); // Flag to keep the placeholder non-adjacent to any Splitter
116623
116624         // Do not trigger a layout during transition to collapsed Component
116625         me.owner.suspendLayout = true;
116626         shadowContainer.suspendLayout = true;
116627
116628         // Prevent upward notifications from downstream layouts
116629         shadowLayout.layoutBusy = true;
116630         if (shadowContainer.componentLayout) {
116631             shadowContainer.componentLayout.layoutBusy = true;
116632         }
116633         me.shadowContainer.layout.layoutBusy = true;
116634         me.layoutBusy = true;
116635         me.owner.componentLayout.layoutBusy = true;
116636
116637         // Provide a replacement Container with an expand tool
116638         if (!placeholder) {
116639             placeholder = me.getPlaceholder(comp);
116640         }
116641
116642         // placeholder already in place; show it.
116643         if (placeholder.shadowOwnerCt === shadowContainer) {
116644             placeholder.show();
116645         }
116646         // Insert the collapsed placeholder Component into the appropriate Box layout shadow Container
116647         // It must go next to its client Component, but non-adjacent to the splitter so splitter can find its collapse client.
116648         // Inject an ownerCt value pointing to the owner, border layout Container as the user will expect.
116649         else {
116650             shadowContainer.insert(shadowContainer.items.indexOf(comp) + (isNorthOrWest ? 0 : 1), placeholder);
116651             placeholder.shadowOwnerCt = shadowContainer;
116652             placeholder.ownerCt = me.owner;
116653         }
116654
116655         // Flag the collapsing Component as hidden and show the placeholder.
116656         // This causes the shadow Box layout's calculateChildBoxes to calculate the correct new arrangement.
116657         // We hide or slideOut the Component's element
116658         comp.hidden = true;
116659
116660         if (!placeholder.rendered) {
116661             shadowLayout.renderItem(placeholder, shadowLayout.innerCt);
116662         }
116663
116664         // Jobs to be done after the collapse has been done
116665         function afterCollapse() {
116666
116667             // Reinstate automatic laying out.
116668             me.owner.suspendLayout = sl;
116669             shadowContainer.suspendLayout = scsl;
116670             delete shadowLayout.layoutBusy;
116671             if (shadowContainer.componentLayout) {
116672                 delete shadowContainer.componentLayout.layoutBusy;
116673             }
116674             delete me.shadowContainer.layout.layoutBusy;
116675             delete me.layoutBusy;
116676             delete me.owner.componentLayout.layoutBusy;
116677
116678             // Fire the collapse event: The Panel has in fact been collapsed, but by substitution of an alternative Component
116679             comp.collapsed = true;
116680             comp.fireEvent('collapse', comp);
116681         }
116682
116683         /*
116684          * Set everything to the new positions. Note that we
116685          * only want to animate the collapse if it wasn't configured
116686          * initially with collapsed: true
116687          */
116688         if (comp.animCollapse && me.initialCollapsedComplete) {
116689             shadowLayout.layout();
116690             compEl.dom.style.zIndex = 100;
116691
116692             // If we're mini-collapsing, the placholder is a Splitter. We don't want it to "bounce in"
116693             if (!miniCollapse) {
116694                 placeholder.el.hide();
116695             }
116696             compEl.slideOut(me.slideDirection[comp.region], {
116697                 duration: Ext.Number.from(comp.animCollapse, Ext.fx.Anim.prototype.duration),
116698                 listeners: {
116699                     afteranimate: function() {
116700                         compEl.show().setLeftTop(-10000, -10000);
116701                         compEl.dom.style.zIndex = '';
116702
116703                         // If we're mini-collapsing, the placholder is a Splitter. We don't want it to "bounce in"
116704                        if (!miniCollapse) {
116705                             placeholder.el.slideIn(me.slideDirection[comp.region], {
116706                                 easing: 'linear',
116707                                 duration: 100
116708                             });
116709                         }
116710                         afterCollapse();
116711                     }
116712                 }
116713             });
116714         } else {
116715             compEl.setLeftTop(-10000, -10000);
116716             shadowLayout.layout();
116717             afterCollapse();
116718
116719             // Horrible workaround for https://sencha.jira.com/browse/EXTJSIV-1562
116720             if (Ext.isIE) {
116721                 placeholder.setCalculatedSize(placeholder.el.getWidth());
116722             }
116723         }
116724
116725         return false;
116726     },
116727
116728     // Hijack the expand operation to remove the placeholder and slide the region back in.
116729     onBeforeRegionExpand: function(comp, animate) {
116730         this.onPlaceHolderToolClick(null, null, null, {client: comp});
116731         return false;
116732     },
116733
116734     // Called when the collapsed placeholder is clicked to reinstate a "collapsed" (in reality hidden) Panel.
116735     onPlaceHolderToolClick: function(e, target, owner, tool) {
116736         var me = this,
116737             comp = tool.client,
116738
116739             // Hide the placeholder unless it was the Component's preexisting splitter
116740             hidePlaceholder = (comp.collapseMode != 'mini') || !comp.split,
116741             compEl = comp.el,
116742             toCompBox,
116743             placeholder = comp.placeholder,
116744             placeholderEl = placeholder.el,
116745             shadowContainer = comp.shadowOwnerCt,
116746             shadowLayout = shadowContainer.layout,
116747             curSize,
116748             sl = me.owner.suspendLayout,
116749             scsl = shadowContainer.suspendLayout,
116750             isFloating;
116751
116752         // If the slide in is still going, stop it.
116753         // This will either leave the Component in its fully floated state (which is processed below)
116754         // or in its collapsed state. Either way, we expand it..
116755         if (comp.getActiveAnimation()) {
116756             comp.stopAnimation();
116757         }
116758
116759         // If the Component is fully floated when they click the placeholder Tool,
116760         // it will be primed with a slide out animation object... so delete that
116761         // and remove the mouseout listeners
116762         if (comp.slideOutAnim) {
116763             // Remove mouse leave monitors
116764             compEl.un(comp.panelMouseMon);
116765             placeholderEl.un(comp.placeholderMouseMon);
116766
116767             delete comp.slideOutAnim;
116768             delete comp.panelMouseMon;
116769             delete comp.placeholderMouseMon;
116770
116771             // If the Panel was floated and primed with a slideOut animation, we don't want to animate its layout operation.
116772             isFloating = true;
116773         }
116774
116775         // Do not trigger a layout during transition to expanded Component
116776         me.owner.suspendLayout = true;
116777         shadowContainer.suspendLayout = true;
116778
116779         // Prevent upward notifications from downstream layouts
116780         shadowLayout.layoutBusy = true;
116781         if (shadowContainer.componentLayout) {
116782             shadowContainer.componentLayout.layoutBusy = true;
116783         }
116784         me.shadowContainer.layout.layoutBusy = true;
116785         me.layoutBusy = true;
116786         me.owner.componentLayout.layoutBusy = true;
116787
116788         // Unset the hidden and collapsed flags set in onBeforeRegionCollapse. The shadowLayout will now take it into account
116789         // Find where the shadow Box layout plans to put the expanding Component.
116790         comp.hidden = false;
116791         comp.collapsed = false;
116792         if (hidePlaceholder) {
116793             placeholder.hidden = true;
116794         }
116795         toCompBox = shadowLayout.calculateChildBox(comp);
116796
116797         // Show the collapse tool in case it was hidden by the slide-in
116798         if (comp.collapseTool) {
116799             comp.collapseTool.show();
116800         }
116801
116802         // If we're going to animate, we need to hide the component before moving it back into position
116803         if (comp.animCollapse && !isFloating) {
116804             compEl.setStyle('visibility', 'hidden');
116805         }
116806         compEl.setLeftTop(toCompBox.left, toCompBox.top);
116807
116808         // Equalize the size of the expanding Component prior to animation
116809         // in case the layout area has changed size during the time it was collapsed.
116810         curSize = comp.getSize();
116811         if (curSize.height != toCompBox.height || curSize.width != toCompBox.width) {
116812             me.setItemSize(comp, toCompBox.width, toCompBox.height);
116813         }
116814
116815         // Jobs to be done after the expand has been done
116816         function afterExpand() {
116817             // Reinstate automatic laying out.
116818             me.owner.suspendLayout = sl;
116819             shadowContainer.suspendLayout = scsl;
116820             delete shadowLayout.layoutBusy;
116821             if (shadowContainer.componentLayout) {
116822                 delete shadowContainer.componentLayout.layoutBusy;
116823             }
116824             delete me.shadowContainer.layout.layoutBusy;
116825             delete me.layoutBusy;
116826             delete me.owner.componentLayout.layoutBusy;
116827
116828             // In case it was floated out and they clicked the re-expand tool
116829             comp.removeCls(Ext.baseCSSPrefix + 'border-region-slide-in');
116830
116831             // Fire the expand event: The Panel has in fact been expanded, but by removal of an alternative Component
116832             comp.fireEvent('expand', comp);
116833         }
116834
116835         // Hide the placeholder
116836         if (hidePlaceholder) {
116837             placeholder.el.hide();
116838         }
116839
116840         // Slide the expanding Component to its new position.
116841         // When that is done, layout the layout.
116842         if (comp.animCollapse && !isFloating) {
116843             compEl.dom.style.zIndex = 100;
116844             compEl.slideIn(me.slideDirection[comp.region], {
116845                 duration: Ext.Number.from(comp.animCollapse, Ext.fx.Anim.prototype.duration),
116846                 listeners: {
116847                     afteranimate: function() {
116848                         compEl.dom.style.zIndex = '';
116849                         comp.hidden = false;
116850                         shadowLayout.onLayout();
116851                         afterExpand();
116852                     }
116853                 }
116854             });
116855         } else {
116856             shadowLayout.onLayout();
116857             afterExpand();
116858         }
116859     },
116860
116861     floatCollapsedPanel: function(e, comp) {
116862
116863         if (comp.floatable === false) {
116864             return;
116865         }
116866
116867         var me = this,
116868             compEl = comp.el,
116869             placeholder = comp.placeholder,
116870             placeholderEl = placeholder.el,
116871             shadowContainer = comp.shadowOwnerCt,
116872             shadowLayout = shadowContainer.layout,
116873             placeholderBox = shadowLayout.getChildBox(placeholder),
116874             scsl = shadowContainer.suspendLayout,
116875             curSize, toCompBox, compAnim;
116876
116877         // Ignore clicks on tools.
116878         if (e.getTarget('.' + Ext.baseCSSPrefix + 'tool')) {
116879             return;
116880         }
116881
116882         // It's *being* animated, ignore the click.
116883         // Possible future enhancement: Stop and *reverse* the current active Fx.
116884         if (compEl.getActiveAnimation()) {
116885             return;
116886         }
116887
116888         // If the Component is already fully floated when they click the placeholder,
116889         // it will be primed with a slide out animation object... so slide it out.
116890         if (comp.slideOutAnim) {
116891             me.slideOutFloatedComponent(comp);
116892             return;
116893         }
116894
116895         // Function to be called when the mouse leaves the floated Panel
116896         // Slide out when the mouse leaves the region bounded by the slid Component and its placeholder.
116897         function onMouseLeaveFloated(e) {
116898             var slideRegion = compEl.getRegion().union(placeholderEl.getRegion()).adjust(1, -1, -1, 1);
116899
116900             // If mouse is not within slide Region, slide it out
116901             if (!slideRegion.contains(e.getPoint())) {
116902                 me.slideOutFloatedComponent(comp);
116903             }
116904         }
116905
116906         // Monitor for mouseouting of the placeholder. Hide it if they exit for half a second or more
116907         comp.placeholderMouseMon = placeholderEl.monitorMouseLeave(500, onMouseLeaveFloated);
116908
116909         // Do not trigger a layout during slide out of the Component
116910         shadowContainer.suspendLayout = true;
116911
116912         // Prevent upward notifications from downstream layouts
116913         me.layoutBusy = true;
116914         me.owner.componentLayout.layoutBusy = true;
116915
116916         // The collapse tool is hidden while slid.
116917         // It is re-shown on expand.
116918         if (comp.collapseTool) {
116919             comp.collapseTool.hide();
116920         }
116921
116922         // Set flags so that the layout will calculate the boxes for what we want
116923         comp.hidden = false;
116924         comp.collapsed = false;
116925         placeholder.hidden = true;
116926
116927         // Recalculate new arrangement of the Component being floated.
116928         toCompBox = shadowLayout.calculateChildBox(comp);
116929         placeholder.hidden = false;
116930
116931         // Component to appear just after the placeholder, whatever "after" means in the context of the shadow Box layout.
116932         if (comp.region == 'north' || comp.region == 'west') {
116933             toCompBox[shadowLayout.parallelBefore] += placeholderBox[shadowLayout.parallelPrefix] - 1;
116934         } else {
116935             toCompBox[shadowLayout.parallelBefore] -= (placeholderBox[shadowLayout.parallelPrefix] - 1);
116936         }
116937         compEl.setStyle('visibility', 'hidden');
116938         compEl.setLeftTop(toCompBox.left, toCompBox.top);
116939
116940         // Equalize the size of the expanding Component prior to animation
116941         // in case the layout area has changed size during the time it was collapsed.
116942         curSize = comp.getSize();
116943         if (curSize.height != toCompBox.height || curSize.width != toCompBox.width) {
116944             me.setItemSize(comp, toCompBox.width, toCompBox.height);
116945         }
116946
116947         // This animation slides the collapsed Component's el out to just beyond its placeholder
116948         compAnim = {
116949             listeners: {
116950                 afteranimate: function() {
116951                     shadowContainer.suspendLayout = scsl;
116952                     delete me.layoutBusy;
116953                     delete me.owner.componentLayout.layoutBusy;
116954
116955                     // Prime the Component with an Anim config object to slide it back out
116956                     compAnim.listeners = {
116957                         afterAnimate: function() {
116958                             compEl.show().removeCls(Ext.baseCSSPrefix + 'border-region-slide-in').setLeftTop(-10000, -10000);
116959
116960                             // Reinstate the correct, current state after slide out animation finishes
116961                             comp.hidden = true;
116962                             comp.collapsed = true;
116963                             delete comp.slideOutAnim;
116964                             delete comp.panelMouseMon;
116965                             delete comp.placeholderMouseMon;
116966                         }
116967                     };
116968                     comp.slideOutAnim = compAnim;
116969                 }
116970             },
116971             duration: 500
116972         };
116973
116974         // Give the element the correct class which places it at a high z-index
116975         compEl.addCls(Ext.baseCSSPrefix + 'border-region-slide-in');
116976
116977         // Begin the slide in
116978         compEl.slideIn(me.slideDirection[comp.region], compAnim);
116979
116980         // Monitor for mouseouting of the slid area. Hide it if they exit for half a second or more
116981         comp.panelMouseMon = compEl.monitorMouseLeave(500, onMouseLeaveFloated);
116982
116983     },
116984
116985     slideOutFloatedComponent: function(comp) {
116986         var compEl = comp.el,
116987             slideOutAnim;
116988
116989         // Remove mouse leave monitors
116990         compEl.un(comp.panelMouseMon);
116991         comp.placeholder.el.un(comp.placeholderMouseMon);
116992
116993         // Slide the Component out
116994         compEl.slideOut(this.slideDirection[comp.region], comp.slideOutAnim);
116995
116996         delete comp.slideOutAnim;
116997         delete comp.panelMouseMon;
116998         delete comp.placeholderMouseMon;
116999     },
117000
117001     /*
117002      * @private
117003      * Ensure any collapsed placeholder Component is destroyed along with its region.
117004      * Can't do this in onDestroy because they may remove a Component and use it elsewhere.
117005      */
117006     onRegionDestroy: function(comp) {
117007         var placeholder = comp.placeholder;
117008         if (placeholder) {
117009             delete placeholder.ownerCt;
117010             placeholder.destroy();
117011         }
117012     },
117013
117014     /*
117015      * @private
117016      * Ensure any shadow Containers are destroyed.
117017      * Ensure we don't keep references to Components.
117018      */
117019     onDestroy: function() {
117020         var me = this,
117021             shadowContainer = me.shadowContainer,
117022             embeddedContainer = me.embeddedContainer;
117023
117024         if (shadowContainer) {
117025             delete shadowContainer.ownerCt;
117026             Ext.destroy(shadowContainer);
117027         }
117028
117029         if (embeddedContainer) {
117030             delete embeddedContainer.ownerCt;
117031             Ext.destroy(embeddedContainer);
117032         }
117033         delete me.regions;
117034         delete me.splitters;
117035         delete me.shadowContainer;
117036         delete me.embeddedContainer;
117037         me.callParent(arguments);
117038     }
117039 });
117040
117041 /**
117042  * @class Ext.layout.container.Card
117043  * @extends Ext.layout.container.AbstractCard
117044   * <p>This layout manages multiple child Components, each fitted to the Container, where only a single child Component can be
117045   * visible at any given time.  This layout style is most commonly used for wizards, tab implementations, etc.
117046   * This class is intended to be extended or created via the layout:'card' {@link Ext.container.Container#layout} config,
117047   * and should generally not need to be created directly via the new keyword.</p>
117048   * <p>The CardLayout's focal method is {@link #setActiveItem}.  Since only one panel is displayed at a time,
117049   * the only way to move from one Component to the next is by calling setActiveItem, passing the id or index of
117050   * the next panel to display.  The layout itself does not provide a user interface for handling this navigation,
117051   * so that functionality must be provided by the developer.</p>
117052   * <p>In the following example, a simplistic wizard setup is demonstrated.  A button bar is added
117053   * to the footer of the containing panel to provide navigation buttons.  The buttons will be handled by a
117054   * common navigation routine -- for this example, the implementation of that routine has been ommitted since
117055   * it can be any type of custom logic.  Note that other uses of a CardLayout (like a tab control) would require a
117056   * completely different implementation.  For serious implementations, a better approach would be to extend
117057   * CardLayout to provide the custom functionality needed.  
117058   * {@img Ext.layout.container.Card/Ext.layout.container.Card.png Ext.layout.container.Card container layout}
117059   * Example usage:</p>
117060   * <pre><code>
117061     var navHandler = function(direction){
117062          // This routine could contain business logic required to manage the navigation steps.
117063          // It would call setActiveItem as needed, manage navigation button state, handle any
117064          // branching logic that might be required, handle alternate actions like cancellation
117065          // or finalization, etc.  A complete wizard implementation could get pretty
117066          // sophisticated depending on the complexity required, and should probably be
117067          // done as a subclass of CardLayout in a real-world implementation.
117068      };
117069
117070     Ext.create('Ext.panel.Panel', {
117071         title: 'Example Wizard',
117072         width: 300,
117073         height: 200,
117074         layout: 'card',
117075         activeItem: 0, // make sure the active item is set on the container config!
117076         bodyStyle: 'padding:15px',
117077         defaults: {
117078             // applied to each contained panel
117079             border:false
117080         },
117081         // just an example of one possible navigation scheme, using buttons
117082         bbar: [
117083         {
117084             id: 'move-prev',
117085             text: 'Back',
117086             handler: navHandler(this, [-1]),
117087             disabled: true
117088         },
117089         '->', // greedy spacer so that the buttons are aligned to each side
117090         {
117091             id: 'move-next',
117092             text: 'Next',
117093             handler: navHandler(this, [1])
117094         }],
117095         // the panels (or "cards") within the layout
117096         items: [{
117097             id: 'card-0',
117098             html: '<h1>Welcome to the Wizard!</h1><p>Step 1 of 3</p>'
117099         },{
117100             id: 'card-1',
117101             html: '<p>Step 2 of 3</p>'
117102         },{
117103             id: 'card-2',
117104             html: '<h1>Congratulations!</h1><p>Step 3 of 3 - Complete</p>'
117105         }],
117106         renderTo: Ext.getBody()
117107     });  
117108  </code></pre>
117109   */
117110 Ext.define('Ext.layout.container.Card', {
117111
117112     /* Begin Definitions */
117113
117114     alias: ['layout.card'],
117115     alternateClassName: 'Ext.layout.CardLayout',
117116
117117     extend: 'Ext.layout.container.AbstractCard',
117118
117119     /* End Definitions */
117120
117121     setActiveItem: function(newCard) {
117122         var me = this,
117123             owner = me.owner,
117124             oldCard = me.activeItem,
117125             newIndex;
117126
117127         // Block upward layouts until we are done.
117128         me.layoutBusy = true;
117129
117130         newCard = me.parseActiveItem(newCard);
117131         newIndex = owner.items.indexOf(newCard);
117132
117133         // If the card is not a child of the owner, then add it
117134         if (newIndex == -1) {
117135             newIndex = owner.items.items.length;
117136             owner.add(newCard);
117137         }
117138
117139         // Is this a valid, different card?
117140         if (newCard && oldCard != newCard) {
117141             // If the card has not been rendered yet, now is the time to do so.
117142             if (!newCard.rendered) {
117143                 me.renderItem(newCard, me.getRenderTarget(), owner.items.length);
117144                 me.configureItem(newCard, 0);
117145             }
117146
117147             me.activeItem = newCard;
117148
117149             // Fire the beforeactivate and beforedeactivate events on the cards
117150             if (newCard.fireEvent('beforeactivate', newCard, oldCard) === false) {
117151                 me.layoutBusy = false;
117152                 return false;
117153             }
117154             if (oldCard && oldCard.fireEvent('beforedeactivate', oldCard, newCard) === false) {
117155                 me.layoutBusy = false;
117156                 return false;
117157             }
117158
117159             // If the card hasnt been sized yet, do it now
117160             if (!me.sizeAllCards) {
117161                 me.setItemBox(newCard, me.getTargetBox());
117162             }
117163             else {
117164                 // onLayout calls setItemBox
117165                 me.onLayout();
117166             }
117167
117168             if (oldCard) {
117169                 if (me.hideInactive) {
117170                     oldCard.hide();
117171                 }
117172                 oldCard.fireEvent('deactivate', oldCard, newCard);
117173             }
117174
117175             // Make sure the new card is shown
117176             if (newCard.hidden) {
117177                 newCard.show();
117178             }
117179
117180             newCard.fireEvent('activate', newCard, oldCard);
117181
117182             me.layoutBusy = false;
117183
117184             if (!me.sizeAllCards) {
117185                 if (!owner.componentLayout.layoutBusy) {
117186                     me.onLayout();
117187                 }
117188             }
117189             return newCard;
117190         }
117191
117192         me.layoutBusy = false;
117193         return false;
117194     }
117195 });
117196 /**
117197  * @class Ext.layout.container.Column
117198  * @extends Ext.layout.container.Auto
117199  * <p>This is the layout style of choice for creating structural layouts in a multi-column format where the width of
117200  * each column can be specified as a percentage or fixed width, but the height is allowed to vary based on the content.
117201  * This class is intended to be extended or created via the layout:'column' {@link Ext.container.Container#layout} config,
117202  * and should generally not need to be created directly via the new keyword.</p>
117203  * <p>ColumnLayout does not have any direct config options (other than inherited ones), but it does support a
117204  * specific config property of <b><tt>columnWidth</tt></b> that can be included in the config of any panel added to it.  The
117205  * layout will use the columnWidth (if present) or width of each panel during layout to determine how to size each panel.
117206  * If width or columnWidth is not specified for a given panel, its width will default to the panel's width (or auto).</p>
117207  * <p>The width property is always evaluated as pixels, and must be a number greater than or equal to 1.
117208  * The columnWidth property is always evaluated as a percentage, and must be a decimal value greater than 0 and
117209  * less than 1 (e.g., .25).</p>
117210  * <p>The basic rules for specifying column widths are pretty simple.  The logic makes two passes through the
117211  * set of contained panels.  During the first layout pass, all panels that either have a fixed width or none
117212  * specified (auto) are skipped, but their widths are subtracted from the overall container width.  During the second
117213  * pass, all panels with columnWidths are assigned pixel widths in proportion to their percentages based on
117214  * the total <b>remaining</b> container width.  In other words, percentage width panels are designed to fill the space
117215  * left over by all the fixed-width and/or auto-width panels.  Because of this, while you can specify any number of columns
117216  * with different percentages, the columnWidths must always add up to 1 (or 100%) when added together, otherwise your
117217  * layout may not render as expected.  
117218  * {@img Ext.layout.container.Column/Ext.layout.container.Column1.png Ext.layout.container.Column container layout}
117219  * Example usage:</p>
117220  * <pre><code>
117221     // All columns are percentages -- they must add up to 1
117222     Ext.create('Ext.panel.Panel', {
117223         title: 'Column Layout - Percentage Only',
117224         width: 350,
117225         height: 250,
117226         layout:'column',
117227         items: [{
117228             title: 'Column 1',
117229             columnWidth: .25
117230         },{
117231             title: 'Column 2',
117232             columnWidth: .55
117233         },{
117234             title: 'Column 3',
117235             columnWidth: .20
117236         }],
117237         renderTo: Ext.getBody()
117238     }); 
117239
117240 // {@img Ext.layout.container.Column/Ext.layout.container.Column2.png Ext.layout.container.Column container layout}
117241 // Mix of width and columnWidth -- all columnWidth values must add up
117242 // to 1. The first column will take up exactly 120px, and the last two
117243 // columns will fill the remaining container width.
117244
117245     Ext.create('Ext.Panel', {
117246         title: 'Column Layout - Mixed',
117247         width: 350,
117248         height: 250,
117249         layout:'column',
117250         items: [{
117251             title: 'Column 1',
117252             width: 120
117253         },{
117254             title: 'Column 2',
117255             columnWidth: .7
117256         },{
117257             title: 'Column 3',
117258             columnWidth: .3
117259         }],
117260         renderTo: Ext.getBody()
117261     }); 
117262 </code></pre>
117263  */
117264 Ext.define('Ext.layout.container.Column', {
117265
117266     extend: 'Ext.layout.container.Auto',
117267     alias: ['layout.column'],
117268     alternateClassName: 'Ext.layout.ColumnLayout',
117269
117270     type: 'column',
117271
117272     itemCls: Ext.baseCSSPrefix + 'column',
117273
117274     targetCls: Ext.baseCSSPrefix + 'column-layout-ct',
117275
117276     scrollOffset: 0,
117277
117278     bindToOwnerCtComponent: false,
117279
117280     getRenderTarget : function() {
117281         if (!this.innerCt) {
117282
117283             // the innerCt prevents wrapping and shuffling while
117284             // the container is resizing
117285             this.innerCt = this.getTarget().createChild({
117286                 cls: Ext.baseCSSPrefix + 'column-inner'
117287             });
117288
117289             // Column layout uses natural HTML flow to arrange the child items.
117290             // To ensure that all browsers (I'm looking at you IE!) add the bottom margin of the last child to the
117291             // containing element height, we create a zero-sized element with style clear:both to force a "new line"
117292             this.clearEl = this.innerCt.createChild({
117293                 cls: Ext.baseCSSPrefix + 'clear',
117294                 role: 'presentation'
117295             });
117296         }
117297         return this.innerCt;
117298     },
117299
117300     // private
117301     onLayout : function() {
117302         var me = this,
117303             target = me.getTarget(),
117304             items = me.getLayoutItems(),
117305             len = items.length,
117306             item,
117307             i,
117308             parallelMargins = [],
117309             itemParallelMargins,
117310             size,
117311             availableWidth,
117312             columnWidth;
117313
117314         size = me.getLayoutTargetSize();
117315         if (size.width < len * 10) { // Don't lay out in impossibly small target (probably display:none, or initial, unsized Container)
117316             return;
117317         }
117318
117319         // On the first pass, for all except IE6-7, we lay out the items with no scrollbars visible using style overflow: hidden.
117320         // If, after the layout, it is detected that there is vertical overflow,
117321         // we will recurse back through here. Do not adjust overflow style at that time.
117322         if (me.adjustmentPass) {
117323             if (Ext.isIE6 || Ext.isIE7 || Ext.isIEQuirks) {
117324                 size.width = me.adjustedWidth;
117325             }
117326         } else {
117327             i = target.getStyle('overflow');
117328             if (i && i != 'hidden') {
117329                 me.autoScroll = true;
117330                 if (!(Ext.isIE6 || Ext.isIE7 || Ext.isIEQuirks)) {
117331                     target.setStyle('overflow', 'hidden');
117332                     size = me.getLayoutTargetSize();
117333                 }
117334             }
117335         }
117336
117337         availableWidth = size.width - me.scrollOffset;
117338         me.innerCt.setWidth(availableWidth);
117339
117340         // some columns can be percentages while others are fixed
117341         // so we need to make 2 passes
117342         for (i = 0; i < len; i++) {
117343             item = items[i];
117344             itemParallelMargins = parallelMargins[i] = item.getEl().getMargin('lr');
117345             if (!item.columnWidth) {
117346                 availableWidth -= (item.getWidth() + itemParallelMargins);
117347             }
117348         }
117349
117350         availableWidth = availableWidth < 0 ? 0 : availableWidth;
117351         for (i = 0; i < len; i++) {
117352             item = items[i];
117353             if (item.columnWidth) {
117354                 columnWidth = Math.floor(item.columnWidth * availableWidth) - parallelMargins[i];
117355                 if (item.getWidth() != columnWidth) {
117356                     me.setItemSize(item, columnWidth, item.height);
117357                 }
117358             }
117359         }
117360
117361         // After the first pass on an autoScroll layout, restore the overflow settings if it had been changed (only changed for non-IE6)
117362         if (!me.adjustmentPass && me.autoScroll) {
117363
117364             // If there's a vertical overflow, relay with scrollbars
117365             target.setStyle('overflow', 'auto');
117366             me.adjustmentPass = (target.dom.scrollHeight > size.height);
117367             if (Ext.isIE6 || Ext.isIE7 || Ext.isIEQuirks) {
117368                 me.adjustedWidth = size.width - Ext.getScrollBarWidth();
117369             } else {
117370                 target.setStyle('overflow', 'auto');
117371             }
117372
117373             // If the layout caused height overflow, recurse back and recalculate (with overflow setting restored on non-IE6)
117374             if (me.adjustmentPass) {
117375                 me.onLayout();
117376             }
117377         }
117378         delete me.adjustmentPass;
117379     }
117380 });
117381 /**
117382  * @class Ext.layout.container.Table
117383  * @extends Ext.layout.container.Auto
117384  * <p>This layout allows you to easily render content into an HTML table.  The total number of columns can be
117385  * specified, and rowspan and colspan can be used to create complex layouts within the table.
117386  * This class is intended to be extended or created via the <code>layout: {type: 'table'}</code>
117387  * {@link Ext.container.Container#layout} config, and should generally not need to be created directly via the new keyword.</p>
117388  * <p>Note that when creating a layout via config, the layout-specific config properties must be passed in via
117389  * the {@link Ext.container.Container#layout} object which will then be applied internally to the layout.  In the
117390  * case of TableLayout, the only valid layout config properties are {@link #columns} and {@link #tableAttrs}.
117391  * However, the items added to a TableLayout can supply the following table-specific config properties:</p>
117392  * <ul>
117393  * <li><b>rowspan</b> Applied to the table cell containing the item.</li>
117394  * <li><b>colspan</b> Applied to the table cell containing the item.</li>
117395  * <li><b>cellId</b> An id applied to the table cell containing the item.</li>
117396  * <li><b>cellCls</b> A CSS class name added to the table cell containing the item.</li>
117397  * </ul>
117398  * <p>The basic concept of building up a TableLayout is conceptually very similar to building up a standard
117399  * HTML table.  You simply add each panel (or "cell") that you want to include along with any span attributes
117400  * specified as the special config properties of rowspan and colspan which work exactly like their HTML counterparts.
117401  * Rather than explicitly creating and nesting rows and columns as you would in HTML, you simply specify the
117402  * total column count in the layoutConfig and start adding panels in their natural order from left to right,
117403  * top to bottom.  The layout will automatically figure out, based on the column count, rowspans and colspans,
117404  * how to position each panel within the table.  Just like with HTML tables, your rowspans and colspans must add
117405  * up correctly in your overall layout or you'll end up with missing and/or extra cells!  Example usage:</p>
117406  * {@img Ext.layout.container.Table/Ext.layout.container.Table.png Ext.layout.container.Table container layout}
117407  * <pre><code>
117408 // This code will generate a layout table that is 3 columns by 2 rows
117409 // with some spanning included.  The basic layout will be:
117410 // +--------+-----------------+
117411 // |   A    |   B             |
117412 // |        |--------+--------|
117413 // |        |   C    |   D    |
117414 // +--------+--------+--------+
117415     Ext.create('Ext.panel.Panel', {
117416         title: 'Table Layout',
117417         width: 300,
117418         height: 150,
117419         layout: {
117420             type: 'table',
117421             // The total column count must be specified here
117422             columns: 3
117423         },
117424         defaults: {
117425             // applied to each contained panel
117426             bodyStyle:'padding:20px'
117427         },
117428         items: [{
117429             html: '<p>Cell A content</p>',
117430             rowspan: 2
117431         },{
117432             html: '<p>Cell B content</p>',
117433             colspan: 2
117434         },{
117435             html: '<p>Cell C content</p>',
117436             cellCls: 'highlight'
117437         },{
117438             html: '<p>Cell D content</p>'
117439         }],
117440         renderTo: Ext.getBody()
117441     });
117442 </code></pre>
117443  */
117444
117445 Ext.define('Ext.layout.container.Table', {
117446
117447     /* Begin Definitions */
117448
117449     alias: ['layout.table'],
117450     extend: 'Ext.layout.container.Auto',
117451     alternateClassName: 'Ext.layout.TableLayout',
117452
117453     /* End Definitions */
117454
117455     /**
117456      * @cfg {Number} columns
117457      * The total number of columns to create in the table for this layout.  If not specified, all Components added to
117458      * this layout will be rendered into a single row using one column per Component.
117459      */
117460
117461     // private
117462     monitorResize:false,
117463
117464     type: 'table',
117465
117466     // Table layout is a self-sizing layout. When an item of for example, a dock layout, the Panel must expand to accommodate
117467     // a table layout. See in particular AbstractDock::onLayout for use of this flag.
117468     autoSize: true,
117469
117470     clearEl: true, // Base class will not create it if already truthy. Not needed in tables.
117471
117472     targetCls: Ext.baseCSSPrefix + 'table-layout-ct',
117473     tableCls: Ext.baseCSSPrefix + 'table-layout',
117474     cellCls: Ext.baseCSSPrefix + 'table-layout-cell',
117475
117476     /**
117477      * @cfg {Object} tableAttrs
117478      * <p>An object containing properties which are added to the {@link Ext.core.DomHelper DomHelper} specification
117479      * used to create the layout's <tt>&lt;table&gt;</tt> element. Example:</p><pre><code>
117480 {
117481     xtype: 'panel',
117482     layout: {
117483         type: 'table',
117484         columns: 3,
117485         tableAttrs: {
117486             style: {
117487                 width: '100%'
117488             }
117489         }
117490     }
117491 }</code></pre>
117492      */
117493     tableAttrs:null,
117494
117495     /**
117496      * @private
117497      * Iterates over all passed items, ensuring they are rendered in a cell in the proper
117498      * location in the table structure.
117499      */
117500     renderItems: function(items) {
117501         var tbody = this.getTable().tBodies[0],
117502             rows = tbody.rows,
117503             i = 0,
117504             len = items.length,
117505             cells, curCell, rowIdx, cellIdx, item, trEl, tdEl, itemCt;
117506
117507         // Calculate the correct cell structure for the current items
117508         cells = this.calculateCells(items);
117509
117510         // Loop over each cell and compare to the current cells in the table, inserting/
117511         // removing/moving cells as needed, and making sure each item is rendered into
117512         // the correct cell.
117513         for (; i < len; i++) {
117514             curCell = cells[i];
117515             rowIdx = curCell.rowIdx;
117516             cellIdx = curCell.cellIdx;
117517             item = items[i];
117518
117519             // If no row present, create and insert one
117520             trEl = rows[rowIdx];
117521             if (!trEl) {
117522                 trEl = tbody.insertRow(rowIdx);
117523             }
117524
117525             // If no cell present, create and insert one
117526             itemCt = tdEl = Ext.get(trEl.cells[cellIdx] || trEl.insertCell(cellIdx));
117527             if (this.needsDivWrap()) { //create wrapper div if needed - see docs below
117528                 itemCt = tdEl.first() || tdEl.createChild({tag: 'div'});
117529                 itemCt.setWidth(null);
117530             }
117531
117532             // Render or move the component into the cell
117533             if (!item.rendered) {
117534                 this.renderItem(item, itemCt, 0);
117535             }
117536             else if (!this.isValidParent(item, itemCt, 0)) {
117537                 this.moveItem(item, itemCt, 0);
117538             }
117539
117540             // Set the cell properties
117541             tdEl.set({
117542                 colSpan: item.colspan || 1,
117543                 rowSpan: item.rowspan || 1,
117544                 id: item.cellId || '',
117545                 cls: this.cellCls + ' ' + (item.cellCls || '')
117546             });
117547
117548             // If at the end of a row, remove any extra cells
117549             if (!cells[i + 1] || cells[i + 1].rowIdx !== rowIdx) {
117550                 cellIdx++;
117551                 while (trEl.cells[cellIdx]) {
117552                     trEl.deleteCell(cellIdx);
117553                 }
117554             }
117555         }
117556
117557         // Delete any extra rows
117558         rowIdx++;
117559         while (tbody.rows[rowIdx]) {
117560             tbody.deleteRow(rowIdx);
117561         }
117562     },
117563
117564     afterLayout: function() {
117565         this.callParent();
117566
117567         if (this.needsDivWrap()) {
117568             // set wrapper div width to match layed out item - see docs below
117569             Ext.Array.forEach(this.getLayoutItems(), function(item) {
117570                 Ext.fly(item.el.dom.parentNode).setWidth(item.getWidth());
117571             });
117572         }
117573     },
117574
117575     /**
117576      * @private
117577      * Determine the row and cell indexes for each component, taking into consideration
117578      * the number of columns and each item's configured colspan/rowspan values.
117579      * @param {Array} items The layout components
117580      * @return {Array} List of row and cell indexes for each of the components
117581      */
117582     calculateCells: function(items) {
117583         var cells = [],
117584             rowIdx = 0,
117585             colIdx = 0,
117586             cellIdx = 0,
117587             totalCols = this.columns || Infinity,
117588             rowspans = [], //rolling list of active rowspans for each column
117589             i = 0, j,
117590             len = items.length,
117591             item;
117592
117593         for (; i < len; i++) {
117594             item = items[i];
117595
117596             // Find the first available row/col slot not taken up by a spanning cell
117597             while (colIdx >= totalCols || rowspans[colIdx] > 0) {
117598                 if (colIdx >= totalCols) {
117599                     // move down to next row
117600                     colIdx = 0;
117601                     cellIdx = 0;
117602                     rowIdx++;
117603
117604                     // decrement all rowspans
117605                     for (j = 0; j < totalCols; j++) {
117606                         if (rowspans[j] > 0) {
117607                             rowspans[j]--;
117608                         }
117609                     }
117610                 } else {
117611                     colIdx++;
117612                 }
117613             }
117614
117615             // Add the cell info to the list
117616             cells.push({
117617                 rowIdx: rowIdx,
117618                 cellIdx: cellIdx
117619             });
117620
117621             // Increment
117622             rowspans[colIdx] = item.rowspan || 1;
117623             colIdx += item.colspan || 1;
117624             cellIdx++;
117625         }
117626
117627         return cells;
117628     },
117629
117630     /**
117631      * @private
117632      * Return the layout's table element, creating it if necessary.
117633      */
117634     getTable: function() {
117635         var table = this.table;
117636         if (!table) {
117637             table = this.table = this.getTarget().createChild(
117638                 Ext.apply({
117639                     tag: 'table',
117640                     role: 'presentation',
117641                     cls: this.tableCls,
117642                     cellspacing: 0, //TODO should this be specified or should CSS handle it?
117643                     cn: {tag: 'tbody'}
117644                 }, this.tableAttrs),
117645                 null, true
117646             );
117647         }
117648         return table;
117649     },
117650
117651     /**
117652      * @private
117653      * Opera 10.5 has a bug where if a table cell's child has box-sizing:border-box and padding, it
117654      * will include that padding in the size of the cell, making it always larger than the
117655      * shrink-wrapped size of its contents. To get around this we have to wrap the contents in a div
117656      * and then set that div's width to match the item rendered within it afterLayout. This method
117657      * determines whether we need the wrapper div; it currently does a straight UA sniff as this bug
117658      * seems isolated to just Opera 10.5, but feature detection could be added here if needed.
117659      */
117660     needsDivWrap: function() {
117661         return Ext.isOpera10_5;
117662     }
117663 });
117664 /**
117665  * @class Ext.menu.Item
117666  * @extends Ext.Component
117667
117668  * A base class for all menu items that require menu-related functionality such as click handling,
117669  * sub-menus, icons, etc.
117670  * {@img Ext.menu.Menu/Ext.menu.Menu.png Ext.menu.Menu component}
117671 __Example Usage:__
117672     Ext.create('Ext.menu.Menu', {
117673                 width: 100,
117674                 height: 100,
117675                 floating: false,  // usually you want this set to True (default)
117676                 renderTo: Ext.getBody(),  // usually rendered by it's containing component
117677                 items: [{
117678                     text: 'icon item',
117679                     iconCls: 'add16'
117680                 },{
117681                         text: 'text item',
117682                 },{                        
117683                         text: 'plain item',
117684                         plain: true        
117685                 }]
117686         }); 
117687
117688  * @xtype menuitem
117689  * @markdown
117690  * @constructor
117691  * @param {Object} config The config object
117692  */
117693 Ext.define('Ext.menu.Item', {
117694     extend: 'Ext.Component',
117695     alias: 'widget.menuitem',
117696     alternateClassName: 'Ext.menu.TextItem',
117697     
117698     /**
117699      * @property {Boolean} activated
117700      * Whether or not this item is currently activated
117701      */
117702
117703     /**
117704      * @cfg {String} activeCls
117705      * The CSS class added to the menu item when the item is activated (focused/mouseover).
117706      * Defaults to `Ext.baseCSSPrefix + 'menu-item-active'`.
117707      * @markdown
117708      */
117709     activeCls: Ext.baseCSSPrefix + 'menu-item-active',
117710     
117711     /**
117712      * @cfg {String} ariaRole @hide
117713      */
117714     ariaRole: 'menuitem',
117715     
117716     /**
117717      * @cfg {Boolean} canActivate
117718      * Whether or not this menu item can be activated when focused/mouseovered. Defaults to `true`.
117719      * @markdown
117720      */
117721     canActivate: true,
117722     
117723     /**
117724      * @cfg {Number} clickHideDelay
117725      * The delay in milliseconds to wait before hiding the menu after clicking the menu item.
117726      * This only has an effect when `hideOnClick: true`. Defaults to `1`.
117727      * @markdown
117728      */
117729     clickHideDelay: 1,
117730     
117731     /**
117732      * @cfg {Boolean} destroyMenu
117733      * Whether or not to destroy any associated sub-menu when this item is destroyed. Defaults to `true`.
117734      */
117735     destroyMenu: true,
117736     
117737     /**
117738      * @cfg {String} disabledCls
117739      * The CSS class added to the menu item when the item is disabled.
117740      * Defaults to `Ext.baseCSSPrefix + 'menu-item-disabled'`.
117741      * @markdown
117742      */
117743     disabledCls: Ext.baseCSSPrefix + 'menu-item-disabled',
117744     
117745     /**
117746      * @cfg {String} href
117747      * The href attribute to use for the underlying anchor link. Defaults to `#`.
117748      * @markdown
117749      */
117750      
117751      /**
117752       * @cfg {String} hrefTarget
117753       * The target attribute to use for the underlying anchor link. Defaults to `undefined`.
117754       * @markdown
117755       */
117756     
117757     /**
117758      * @cfg {Boolean} hideOnClick
117759      * Whether to not to hide the owning menu when this item is clicked. Defaults to `true`.
117760      * @markdown
117761      */
117762     hideOnClick: true,
117763     
117764     /**
117765      * @cfg {String} icon
117766      * The path to an icon to display in this item. Defaults to `Ext.BLANK_IMAGE_URL`.
117767      * @markdown
117768      */
117769      
117770     /**
117771      * @cfg {String} iconCls
117772      * A CSS class that specifies a `background-image` to use as the icon for this item. Defaults to `undefined`.
117773      * @markdown
117774      */
117775     
117776     isMenuItem: true,
117777     
117778     /**
117779      * @cfg {Mixed} menu
117780      * Either an instance of {@link Ext.menu.Menu} or a config object for an {@link Ext.menu.Menu}
117781      * which will act as a sub-menu to this item.
117782      * @markdown
117783      * @property {Ext.menu.Menu} menu The sub-menu associated with this item, if one was configured.
117784      */
117785     
117786     /**
117787      * @cfg {String} menuAlign
117788      * The default {@link Ext.core.Element#getAlignToXY Ext.Element.getAlignToXY} anchor position value for this
117789      * item's sub-menu relative to this item's position. Defaults to `'tl-tr?'`.
117790      * @markdown
117791      */
117792     menuAlign: 'tl-tr?',
117793     
117794     /**
117795      * @cfg {Number} menuExpandDelay
117796      * The delay in milliseconds before this item's sub-menu expands after this item is moused over. Defaults to `200`.
117797      * @markdown
117798      */
117799     menuExpandDelay: 200,
117800     
117801     /**
117802      * @cfg {Number} menuHideDelay
117803      * The delay in milliseconds before this item's sub-menu hides after this item is moused out. Defaults to `200`.
117804      * @markdown
117805      */
117806     menuHideDelay: 200,
117807     
117808     /**
117809      * @cfg {Boolean} plain
117810      * Whether or not this item is plain text/html with no icon or visual activation. Defaults to `false`.
117811      * @markdown
117812      */
117813     
117814     renderTpl: [
117815         '<tpl if="plain">',
117816             '{text}',
117817         '</tpl>',
117818         '<tpl if="!plain">',
117819             '<a class="' + Ext.baseCSSPrefix + 'menu-item-link" href="{href}" <tpl if="hrefTarget">target="{hrefTarget}"</tpl> hidefocus="true" unselectable="on">',
117820                 '<img src="{icon}" class="' + Ext.baseCSSPrefix + 'menu-item-icon {iconCls}" />',
117821                 '<span class="' + Ext.baseCSSPrefix + 'menu-item-text" <tpl if="menu">style="margin-right: 17px;"</tpl> >{text}</span>',
117822                 '<tpl if="menu">',
117823                     '<img src="' + Ext.BLANK_IMAGE_URL + '" class="' + Ext.baseCSSPrefix + 'menu-item-arrow" />',
117824                 '</tpl>',
117825             '</a>',
117826         '</tpl>'
117827     ],
117828     
117829     maskOnDisable: false,
117830     
117831     /**
117832      * @cfg {String} text
117833      * The text/html to display in this item. Defaults to `undefined`.
117834      * @markdown
117835      */
117836     
117837     activate: function() {
117838         var me = this;
117839         
117840         if (!me.activated && me.canActivate && me.rendered && !me.isDisabled() && me.isVisible()) {
117841             me.el.addCls(me.activeCls);
117842             me.focus();
117843             me.activated = true;
117844             me.fireEvent('activate', me);
117845         }
117846     },
117847     
117848     blur: function() {
117849         this.$focused = false;
117850         this.callParent(arguments);
117851     },
117852     
117853     deactivate: function() {
117854         var me = this;
117855         
117856         if (me.activated) {
117857             me.el.removeCls(me.activeCls);
117858             me.blur();
117859             me.hideMenu();
117860             me.activated = false;
117861             me.fireEvent('deactivate', me);
117862         }
117863     },
117864     
117865     deferExpandMenu: function() {
117866         var me = this;
117867         
117868         if (!me.menu.rendered || !me.menu.isVisible()) {
117869             me.parentMenu.activeChild = me.menu;
117870             me.menu.parentItem = me;
117871             me.menu.parentMenu = me.menu.ownerCt = me.parentMenu;
117872             me.menu.showBy(me, me.menuAlign);
117873         }
117874     },
117875     
117876     deferHideMenu: function() {
117877         if (this.menu.isVisible()) {
117878             this.menu.hide();
117879         }
117880     },
117881     
117882     deferHideParentMenus: function() {
117883         Ext.menu.Manager.hideAll();
117884     },
117885     
117886     expandMenu: function(delay) {
117887         var me = this;
117888         
117889         if (me.menu) {
117890             clearTimeout(me.hideMenuTimer);
117891             if (delay === 0) {
117892                 me.deferExpandMenu();
117893             } else {
117894                 me.expandMenuTimer = Ext.defer(me.deferExpandMenu, Ext.isNumber(delay) ? delay : me.menuExpandDelay, me);
117895             }
117896         }
117897     },
117898     
117899     focus: function() {
117900         this.$focused = true;
117901         this.callParent(arguments);
117902     },
117903     
117904     getRefItems: function(deep){
117905         var menu = this.menu,
117906             items;
117907         
117908         if (menu) {
117909             items = menu.getRefItems(deep);
117910             items.unshift(menu);
117911         }   
117912         return items || [];   
117913     },
117914     
117915     hideMenu: function(delay) {
117916         var me = this;
117917         
117918         if (me.menu) {
117919             clearTimeout(me.expandMenuTimer);
117920             me.hideMenuTimer = Ext.defer(me.deferHideMenu, Ext.isNumber(delay) ? delay : me.menuHideDelay, me);
117921         }
117922     },
117923     
117924     initComponent: function() {
117925         var me = this,
117926             prefix = Ext.baseCSSPrefix,
117927             cls = [prefix + 'menu-item'];
117928         
117929         me.addEvents(
117930             /**
117931              * @event activate
117932              * Fires when this item is activated
117933              * @param {Ext.menu.Item} item The activated item
117934              */
117935             'activate',
117936             
117937             /**
117938              * @event click
117939              * Fires when this item is clicked
117940              * @param {Ext.menu.Item} item The item that was clicked
117941              * @param {Ext.EventObject} e The underyling {@link Ext.EventObject}.
117942              */
117943             'click',
117944             
117945             /**
117946              * @event deactivate
117947              * Fires when this tiem is deactivated
117948              * @param {Ext.menu.Item} item The deactivated item
117949              */
117950             'deactivate'
117951         );
117952         
117953         if (me.plain) {
117954             cls.push(prefix + 'menu-item-plain');
117955         }
117956         
117957         if (me.cls) {
117958             cls.push(me.cls);
117959         }
117960         
117961         me.cls = cls.join(' ');
117962         
117963         if (me.menu) {
117964             me.menu = Ext.menu.Manager.get(me.menu);
117965         }
117966         
117967         me.callParent(arguments);
117968     },
117969     
117970     onClick: function(e) {
117971         var me = this;
117972         
117973         if (!me.href) {
117974             e.stopEvent();
117975         }
117976         
117977         if (me.disabled) {
117978             return;
117979         }
117980         
117981         if (me.hideOnClick) {
117982             me.deferHideParentMenusTimer = Ext.defer(me.deferHideParentMenus, me.clickHideDelay, me);
117983         }
117984         
117985         Ext.callback(me.handler, me.scope || me, [me, e]);
117986         me.fireEvent('click', me, e);
117987         
117988         if (!me.hideOnClick) {
117989             me.focus();
117990         }
117991     },
117992     
117993     onDestroy: function() {
117994         var me = this;
117995         
117996         clearTimeout(me.expandMenuTimer);
117997         clearTimeout(me.hideMenuTimer);
117998         clearTimeout(me.deferHideParentMenusTimer);
117999         
118000         if (me.menu) {
118001             delete me.menu.parentItem;
118002             delete me.menu.parentMenu;
118003             delete me.menu.ownerCt;
118004             if (me.destroyMenu !== false) {
118005                 me.menu.destroy();
118006             }
118007         }
118008         me.callParent(arguments);
118009     },
118010     
118011     onRender: function(ct, pos) {
118012         var me = this,
118013             prefix = '.' + Ext.baseCSSPrefix;
118014         
118015         Ext.applyIf(me.renderData, {
118016             href: me.href || '#',
118017             hrefTarget: me.hrefTarget,
118018             icon: me.icon || Ext.BLANK_IMAGE_URL,
118019             iconCls: me.iconCls,
118020             menu: Ext.isDefined(me.menu),
118021             plain: me.plain,
118022             text: me.text
118023         });
118024         
118025         Ext.applyIf(me.renderSelectors, {
118026             itemEl: prefix + 'menu-item-link',
118027             iconEl: prefix + 'menu-item-icon',
118028             textEl: prefix + 'menu-item-text',
118029             arrowEl: prefix + 'menu-item-arrow'
118030         });
118031         
118032         me.callParent(arguments);
118033     },
118034     
118035     /**
118036      * Sets the {@link #click} handler of this item
118037      * @param {Function} fn The handler function
118038      * @param {Object} scope (optional) The scope of the handler function
118039      */
118040     setHandler: function(fn, scope) {
118041         this.handler = fn || null;
118042         this.scope = scope;
118043     },
118044     
118045     /**
118046      * Sets the {@link #iconCls} of this item
118047      * @param {String} iconCls The CSS class to set to {@link #iconCls}
118048      */
118049     setIconCls: function(iconCls) {
118050         var me = this;
118051         
118052         if (me.iconEl) {
118053             if (me.iconCls) {
118054                 me.iconEl.removeCls(me.iconCls);
118055             }
118056             
118057             if (iconCls) {
118058                 me.iconEl.addCls(iconCls);
118059             }
118060         }
118061         
118062         me.iconCls = iconCls;
118063     },
118064     
118065     /**
118066      * Sets the {@link #text} of this item
118067      * @param {String} text The {@link #text}
118068      */
118069     setText: function(text) {
118070         var me = this,
118071             el = me.textEl || me.el,
118072             newWidth;
118073         
118074         if (text && el) {
118075             el.update(text);
118076                 
118077             if (me.textEl) {
118078                 // Resize the menu to fit the text
118079                 newWidth = me.textEl.getWidth() + me.iconEl.getWidth() + 25 + (me.arrowEl ? me.arrowEl.getWidth() : 0);
118080                 if (newWidth > me.itemEl.getWidth()) {
118081                     me.parentMenu.setWidth(newWidth);
118082                 }
118083             }
118084         } else if (el) {
118085             el.update('');
118086         }
118087         
118088         me.text = text;
118089     }
118090 });
118091
118092 /**
118093  * @class Ext.menu.CheckItem
118094  * @extends Ext.menu.Item
118095
118096 A menu item that contains a togglable checkbox by default, but that can also be a part of a radio group.
118097 {@img Ext.menu.CheckItem/Ext.menu.CheckItem.png Ext.menu.CheckItem component}
118098 __Example Usage__    
118099     Ext.create('Ext.menu.Menu', {
118100                 width: 100,
118101                 height: 110,
118102                 floating: false,  // usually you want this set to True (default)
118103                 renderTo: Ext.getBody(),  // usually rendered by it's containing component
118104                 items: [{
118105                     xtype: 'menucheckitem',
118106                     text: 'select all'
118107                 },{
118108                     xtype: 'menucheckitem',
118109                         text: 'select specific',
118110                 },{
118111             iconCls: 'add16',
118112                     text: 'icon item' 
118113                 },{
118114                     text: 'regular item'
118115                 }]
118116         }); 
118117         
118118  * @xtype menucheckitem
118119  * @markdown
118120  * @constructor
118121  * @param {Object} config The config object
118122  */
118123
118124 Ext.define('Ext.menu.CheckItem', {
118125     extend: 'Ext.menu.Item',
118126     alias: 'widget.menucheckitem',
118127
118128     /**
118129      * @cfg {String} checkedCls
118130      * The CSS class used by {@link #cls} to show the checked state.
118131      * Defaults to `Ext.baseCSSPrefix + 'menu-item-checked'`.
118132      * @markdown
118133      */
118134     checkedCls: Ext.baseCSSPrefix + 'menu-item-checked',
118135     /**
118136      * @cfg {String} uncheckedCls
118137      * The CSS class used by {@link #cls} to show the unchecked state.
118138      * Defaults to `Ext.baseCSSPrefix + 'menu-item-unchecked'`.
118139      * @markdown
118140      */
118141     uncheckedCls: Ext.baseCSSPrefix + 'menu-item-unchecked',
118142     /**
118143      * @cfg {String} groupCls
118144      * The CSS class applied to this item's icon image to denote being a part of a radio group.
118145      * Defaults to `Ext.baseCSSClass + 'menu-group-icon'`.
118146      * Any specified {@link #iconCls} overrides this.
118147      * @markdown
118148      */
118149     groupCls: Ext.baseCSSPrefix + 'menu-group-icon',
118150
118151     /**
118152      * @cfg {Boolean} hideOnClick
118153      * Whether to not to hide the owning menu when this item is clicked.
118154      * Defaults to `false` for checkbox items, and to `true` for radio group items.
118155      * @markdown
118156      */
118157     hideOnClick: false,
118158
118159     afterRender: function() {
118160         var me = this;
118161         this.callParent();
118162         me.checked = !me.checked;
118163         me.setChecked(!me.checked, true);
118164     },
118165
118166     initComponent: function() {
118167         var me = this;
118168         me.addEvents(
118169             /**
118170              * @event beforecheckchange
118171              * Fires before a change event. Return false to cancel.
118172              * @param {Ext.menu.CheckItem} this
118173              * @param {Boolean} checked
118174              */
118175             'beforecheckchange',
118176
118177             /**
118178              * @event checkchange
118179              * Fires after a change event.
118180              * @param {Ext.menu.CheckItem} this
118181              * @param {Boolean} checked
118182              */
118183             'checkchange'
118184         );
118185
118186         me.callParent(arguments);
118187
118188         Ext.menu.Manager.registerCheckable(me);
118189
118190         if (me.group) {
118191             if (!me.iconCls) {
118192                 me.iconCls = me.groupCls;
118193             }
118194             if (me.initialConfig.hideOnClick !== false) {
118195                 me.hideOnClick = true;
118196             }
118197         }
118198     },
118199
118200     /**
118201      * Disables just the checkbox functionality of this menu Item. If this menu item has a submenu, that submenu
118202      * will still be accessible
118203      */
118204     disableCheckChange: function() {
118205         var me = this;
118206
118207         me.iconEl.addCls(me.disabledCls);
118208         me.checkChangeDisabled = true;
118209     },
118210
118211     /**
118212      * Reenables the checkbox functionality of this menu item after having been disabled by {@link #disableCheckChange}
118213      */
118214     enableCheckChange: function() {
118215         var me = this;
118216
118217         me.iconEl.removeCls(me.disabledCls);
118218         me.checkChangeDisabled = false;
118219     },
118220
118221     onClick: function(e) {
118222         var me = this;
118223         if(!me.disabled && !me.checkChangeDisabled && !(me.checked && me.group)) {
118224             me.setChecked(!me.checked);
118225         }
118226         this.callParent([e]);
118227     },
118228
118229     onDestroy: function() {
118230         Ext.menu.Manager.unregisterCheckable(this);
118231         this.callParent(arguments);
118232     },
118233
118234     /**
118235      * Sets the checked state of the item
118236      * @param {Boolean} checked True to check, false to uncheck
118237      * @param {Boolean} suppressEvents (optional) True to prevent firing the checkchange events. Defaults to `false`.
118238      * @markdown
118239      */
118240     setChecked: function(checked, suppressEvents) {
118241         var me = this;
118242         if (me.checked !== checked && (suppressEvents || me.fireEvent('beforecheckchange', me, checked) !== false)) {
118243             if (me.el) {
118244                 me.el[checked  ? 'addCls' : 'removeCls'](me.checkedCls)[!checked ? 'addCls' : 'removeCls'](me.uncheckedCls);
118245             }
118246             me.checked = checked;
118247             Ext.menu.Manager.onCheckChange(me, checked);
118248             if (!suppressEvents) {
118249                 Ext.callback(me.checkHandler, me.scope, [me, checked]);
118250                 me.fireEvent('checkchange', me, checked);
118251             }
118252         }
118253     }
118254 });
118255
118256 /**
118257  * @class Ext.menu.KeyNav
118258  * @private
118259  */
118260 Ext.define('Ext.menu.KeyNav', {
118261     extend: 'Ext.util.KeyNav',
118262
118263     requires: ['Ext.FocusManager'],
118264     
118265     constructor: function(menu) {
118266         var me = this;
118267
118268         me.menu = menu;
118269         me.callParent([menu.el, {
118270             down: me.down,
118271             enter: me.enter,
118272             esc: me.escape,
118273             left: me.left,
118274             right: me.right,
118275             space: me.enter,
118276             tab: me.tab,
118277             up: me.up
118278         }]);
118279     },
118280
118281     down: function(e) {
118282         var me = this,
118283             fi = me.menu.focusedItem;
118284
118285         if (fi && e.getKey() == Ext.EventObject.DOWN && me.isWhitelisted(fi)) {
118286             return true;
118287         }
118288         me.focusNextItem(1);
118289     },
118290
118291     enter: function(e) {
118292         var menu = this.menu;
118293
118294         if (menu.activeItem) {
118295             menu.onClick(e);
118296         }
118297     },
118298
118299     escape: function(e) {
118300         Ext.menu.Manager.hideAll();
118301     },
118302
118303     focusNextItem: function(step) {
118304         var menu = this.menu,
118305             items = menu.items,
118306             focusedItem = menu.focusedItem,
118307             startIdx = focusedItem ? items.indexOf(focusedItem) : -1,
118308             idx = startIdx + step;
118309
118310         while (idx != startIdx) {
118311             if (idx < 0) {
118312                 idx = items.length - 1;
118313             } else if (idx >= items.length) {
118314                 idx = 0;
118315             }
118316
118317             var item = items.getAt(idx);
118318             if (menu.canActivateItem(item)) {
118319                 menu.setActiveItem(item);
118320                 break;
118321             }
118322             idx += step;
118323         }
118324     },
118325
118326     isWhitelisted: function(item) {
118327         return Ext.FocusManager.isWhitelisted(item);
118328     },
118329
118330     left: function(e) {
118331         var menu = this.menu,
118332             fi = menu.focusedItem,
118333             ai = menu.activeItem;
118334
118335         if (fi && this.isWhitelisted(fi)) {
118336             return true;
118337         }
118338
118339         menu.hide();
118340         if (menu.parentMenu) {
118341             menu.parentMenu.focus();
118342         }
118343     },
118344
118345     right: function(e) {
118346         var menu = this.menu,
118347             fi = menu.focusedItem,
118348             ai = menu.activeItem,
118349             am;
118350
118351         if (fi && this.isWhitelisted(fi)) {
118352             return true;
118353         }
118354
118355         if (ai) {
118356             am = menu.activeItem.menu;
118357             if (am) {
118358                 ai.expandMenu(0);
118359                 Ext.defer(function() {
118360                     am.setActiveItem(am.items.getAt(0));
118361                 }, 25);
118362             }
118363         }
118364     },
118365
118366     tab: function(e) {
118367         var me = this;
118368
118369         if (e.shiftKey) {
118370             me.up(e);
118371         } else {
118372             me.down(e);
118373         }
118374     },
118375
118376     up: function(e) {
118377         var me = this,
118378             fi = me.menu.focusedItem;
118379
118380         if (fi && e.getKey() == Ext.EventObject.UP && me.isWhitelisted(fi)) {
118381             return true;
118382         }
118383         me.focusNextItem(-1);
118384     }
118385 });
118386 /**
118387  * @class Ext.menu.Separator
118388  * @extends Ext.menu.Item
118389  *
118390  * Adds a separator bar to a menu, used to divide logical groups of menu items. Generally you will
118391  * add one of these by using "-" in your call to add() or in your items config rather than creating one directly.
118392  *
118393  * {@img Ext.menu.Separator/Ext.menu.Separator.png Ext.menu.Separator component}
118394  *
118395  * ## Code 
118396  *
118397  *     Ext.create('Ext.menu.Menu', {
118398  *         width: 100,
118399  *         height: 100,
118400  *         floating: false,  // usually you want this set to True (default)
118401  *         renderTo: Ext.getBody(),  // usually rendered by it's containing component
118402  *         items: [{
118403  *             text: 'icon item',
118404  *             iconCls: 'add16'
118405  *         },{
118406  *             xtype: 'menuseparator'
118407  *         },{
118408  *            text: 'seperator above',
118409  *         },{
118410  *            text: 'regular item',
118411  *         }]
118412  *     }); 
118413  *
118414  * @xtype menuseparator
118415  * @markdown
118416  * @constructor
118417  * @param {Object} config The config object
118418  */
118419 Ext.define('Ext.menu.Separator', {
118420     extend: 'Ext.menu.Item',
118421     alias: 'widget.menuseparator',
118422     
118423     /**
118424      * @cfg {String} activeCls @hide
118425      */
118426     
118427     /**
118428      * @cfg {Boolean} canActivate @hide
118429      */
118430     canActivate: false,
118431     
118432     /**
118433      * @cfg {Boolean} clickHideDelay @hide
118434      */
118435      
118436     /**
118437      * @cfg {Boolean} destroyMenu @hide
118438      */
118439      
118440     /**
118441      * @cfg {Boolean} disabledCls @hide
118442      */
118443      
118444     focusable: false,
118445      
118446     /**
118447      * @cfg {String} href @hide
118448      */
118449     
118450     /**
118451      * @cfg {String} hrefTarget @hide
118452      */
118453     
118454     /**
118455      * @cfg {Boolean} hideOnClick @hide
118456      */
118457     hideOnClick: false,
118458     
118459     /**
118460      * @cfg {String} icon @hide
118461      */
118462     
118463     /**
118464      * @cfg {String} iconCls @hide
118465      */
118466     
118467     /**
118468      * @cfg {Mixed} menu @hide
118469      */
118470     
118471     /**
118472      * @cfg {String} menuAlign @hide
118473      */
118474     
118475     /**
118476      * @cfg {Number} menuExpandDelay @hide
118477      */
118478     
118479     /**
118480      * @cfg {Number} menuHideDelay @hide
118481      */
118482     
118483     /**
118484      * @cfg {Boolean} plain @hide
118485      */
118486     plain: true,
118487     
118488     /**
118489      * @cfg {String} separatorCls
118490      * The CSS class used by the separator item to show the incised line.
118491      * Defaults to `Ext.baseCSSPrefix + 'menu-item-separator'`.
118492      * @markdown
118493      */
118494     separatorCls: Ext.baseCSSPrefix + 'menu-item-separator',
118495     
118496     /**
118497      * @cfg {String} text @hide
118498      */
118499     text: '&#160;',
118500     
118501     onRender: function(ct, pos) {
118502         var me = this,
118503             sepCls = me.separatorCls;
118504             
118505         me.cls += ' ' + sepCls;
118506         
118507         Ext.applyIf(me.renderSelectors, {
118508             itemSepEl: '.' + sepCls
118509         });
118510         
118511         me.callParent(arguments);
118512     }
118513 });
118514 /**
118515  * @class Ext.menu.Menu
118516  * @extends Ext.panel.Panel
118517  *
118518  * A menu object. This is the container to which you may add {@link Ext.menu.Item menu items}.
118519  *
118520  * Menus may contain either {@link Ext.menu.Item menu items}, or general {@link Ext.Component Components}.
118521  * Menus may also contain {@link Ext.panel.AbstractPanel#dockedItems docked items} because it extends {@link Ext.panel.Panel}.
118522  *
118523  * To make a contained general {@link Ext.Component Component} line up with other {@link Ext.menu.Item menu items},
118524  * specify `{@link Ext.menu.Item#iconCls iconCls}: 'no-icon'` _or_ `{@link Ext.menu.Item#indent indent}: true`.
118525  * This reserves a space for an icon, and indents the Component in line with the other menu items.
118526  * See {@link Ext.form.field.ComboBox}.{@link Ext.form.field.ComboBox#getListParent getListParent} for an example.
118527
118528  * By default, Menus are absolutely positioned, floating Components. By configuring a Menu with `{@link #floating}:false`,
118529  * a Menu may be used as a child of a {@link Ext.container.Container Container}.
118530  * {@img Ext.menu.Item/Ext.menu.Item.png Ext.menu.Item component}
118531 __Example Usage__
118532         Ext.create('Ext.menu.Menu', {
118533                 width: 100,
118534                 height: 100,
118535                 margin: '0 0 10 0',
118536                 floating: false,  // usually you want this set to True (default)
118537                 renderTo: Ext.getBody(),  // usually rendered by it's containing component
118538                 items: [{                        
118539                         text: 'regular item 1'        
118540                 },{
118541                     text: 'regular item 2'
118542                 },{
118543                         text: 'regular item 3'  
118544                 }]
118545         }); 
118546         
118547         Ext.create('Ext.menu.Menu', {
118548                 width: 100,
118549                 height: 100,
118550                 plain: true,
118551                 floating: false,  // usually you want this set to True (default)
118552                 renderTo: Ext.getBody(),  // usually rendered by it's containing component
118553                 items: [{                        
118554                         text: 'plain item 1'    
118555                 },{
118556                     text: 'plain item 2'
118557                 },{
118558                         text: 'plain item 3'
118559                 }]
118560         }); 
118561  * @xtype menu
118562  * @markdown
118563  * @constructor
118564  * @param {Object} config The config object
118565  */
118566 Ext.define('Ext.menu.Menu', {
118567     extend: 'Ext.panel.Panel',
118568     alias: 'widget.menu',
118569     requires: [
118570         'Ext.layout.container.Fit',
118571         'Ext.layout.container.VBox',
118572         'Ext.menu.CheckItem',
118573         'Ext.menu.Item',
118574         'Ext.menu.KeyNav',
118575         'Ext.menu.Manager',
118576         'Ext.menu.Separator'
118577     ],
118578
118579     /**
118580      * @cfg {Boolean} allowOtherMenus
118581      * True to allow multiple menus to be displayed at the same time. Defaults to `false`.
118582      * @markdown
118583      */
118584     allowOtherMenus: false,
118585
118586     /**
118587      * @cfg {String} ariaRole @hide
118588      */
118589     ariaRole: 'menu',
118590
118591     /**
118592      * @cfg {Boolean} autoRender @hide
118593      * floating is true, so autoRender always happens
118594      */
118595
118596     /**
118597      * @cfg {String} defaultAlign
118598      * The default {@link Ext.core.Element#getAlignToXY Ext.core.Element#getAlignToXY} anchor position value for this menu
118599      * relative to its element of origin. Defaults to `'tl-bl?'`.
118600      * @markdown
118601      */
118602     defaultAlign: 'tl-bl?',
118603
118604     /**
118605      * @cfg {Boolean} floating
118606      * A Menu configured as `floating: true` (the default) will be rendered as an absolutely positioned,
118607      * {@link Ext.Component#floating floating} {@link Ext.Component Component}. If configured as `floating: false`, the Menu may be
118608      * used as a child item of another {@link Ext.container.Container Container}.
118609      * @markdown
118610      */
118611     floating: true,
118612
118613     /**
118614      * @cfg {Boolean} @hide
118615      * Menu performs its own size changing constraining, so ensure Component's constraining is not applied
118616      */
118617     constrain: false,
118618
118619     /**
118620      * @cfg {Boolean} hidden
118621      * True to initially render the Menu as hidden, requiring to be shown manually.
118622      * Defaults to `true` when `floating: true`, and defaults to `false` when `floating: false`.
118623      * @markdown
118624      */
118625     hidden: true,
118626
118627     /**
118628      * @cfg {Boolean} ignoreParentClicks
118629      * True to ignore clicks on any item in this menu that is a parent item (displays a submenu)
118630      * so that the submenu is not dismissed when clicking the parent item. Defaults to `false`.
118631      * @markdown
118632      */
118633     ignoreParentClicks: false,
118634
118635     isMenu: true,
118636
118637     /**
118638      * @cfg {String/Object} layout @hide
118639      */
118640
118641     /**
118642      * @cfg {Boolean} showSeparator True to show the icon separator. (defaults to true).
118643      */
118644     showSeparator : true,
118645
118646     /**
118647      * @cfg {Number} minWidth
118648      * The minimum width of the Menu. Defaults to `120`.
118649      * @markdown
118650      */
118651     minWidth: 120,
118652
118653     /**
118654      * @cfg {Boolean} plain
118655      * True to remove the incised line down the left side of the menu and to not
118656      * indent general Component items. Defaults to `false`.
118657      * @markdown
118658      */
118659
118660     initComponent: function() {
118661         var me = this,
118662             prefix = Ext.baseCSSPrefix;
118663
118664         me.addEvents(
118665             /**
118666              * @event click
118667              * Fires when this menu is clicked
118668              * @param {Ext.menu.Menu} menu The menu which has been clicked
118669              * @param {Ext.Component} item The menu item that was clicked. `undefined` if not applicable.
118670              * @param {Ext.EventObject} e The underlying {@link Ext.EventObject}.
118671              * @markdown
118672              */
118673             'click',
118674
118675             /**
118676              * @event mouseenter
118677              * Fires when the mouse enters this menu
118678              * @param {Ext.menu.Menu} menu The menu
118679              * @param {Ext.EventObject} e The underlying {@link Ext.EventObject}
118680              * @markdown
118681              */
118682             'mouseenter',
118683
118684             /**
118685              * @event mouseleave
118686              * Fires when the mouse leaves this menu
118687              * @param {Ext.menu.Menu} menu The menu
118688              * @param {Ext.EventObject} e The underlying {@link Ext.EventObject}
118689              * @markdown
118690              */
118691             'mouseleave',
118692
118693             /**
118694              * @event mouseover
118695              * Fires when the mouse is hovering over this menu
118696              * @param {Ext.menu.Menu} menu The menu
118697              * @param {Ext.Component} item The menu item that the mouse is over. `undefined` if not applicable.
118698              * @param {Ext.EventObject} e The underlying {@link Ext.EventObject}
118699              */
118700             'mouseover'
118701         );
118702
118703         Ext.menu.Manager.register(me);
118704
118705         // Menu classes
118706         var cls = [prefix + 'menu'];
118707         if (me.plain) {
118708             cls.push(prefix + 'menu-plain');
118709         }
118710         me.cls = cls.join(' ');
118711
118712         // Menu body classes
118713         var bodyCls = me.bodyCls ? [me.bodyCls] : [];
118714         bodyCls.unshift(prefix + 'menu-body');
118715         me.bodyCls = bodyCls.join(' ');
118716
118717         // Internal vbox layout, with scrolling overflow
118718         // Placed in initComponent (rather than prototype) in order to support dynamic layout/scroller
118719         // options if we wish to allow for such configurations on the Menu.
118720         // e.g., scrolling speed, vbox align stretch, etc.
118721         me.layout = {
118722             type: 'vbox',
118723             align: 'stretchmax',
118724             autoSize: true,
118725             clearInnerCtOnLayout: true,
118726             overflowHandler: 'Scroller'
118727         };
118728
118729         // hidden defaults to false if floating is configured as false
118730         if (me.floating === false && me.initialConfig.hidden !== true) {
118731             me.hidden = false;
118732         }
118733
118734         me.callParent(arguments);
118735
118736         me.on('beforeshow', function() {
118737             var hasItems = !!me.items.length;
118738             // FIXME: When a menu has its show cancelled because of no items, it
118739             // gets a visibility: hidden applied to it (instead of the default display: none)
118740             // Not sure why, but we remove this style when we want to show again.
118741             if (hasItems && me.rendered) {
118742                 me.el.setStyle('visibility', null);
118743             }
118744             return hasItems;
118745         });
118746     },
118747
118748     afterRender: function(ct) {
118749         var me = this,
118750             prefix = Ext.baseCSSPrefix,
118751             space = '&#160;';
118752
118753         me.callParent(arguments);
118754
118755         // TODO: Move this to a subTemplate When we support them in the future
118756         if (me.showSeparator) {
118757             me.iconSepEl = me.layout.getRenderTarget().insertFirst({
118758                 cls: prefix + 'menu-icon-separator',
118759                 html: space
118760             });
118761         }
118762
118763         me.focusEl = me.el.createChild({
118764             cls: prefix + 'menu-focus',
118765             tabIndex: '-1',
118766             html: space
118767         });
118768
118769         me.mon(me.el, {
118770             click: me.onClick,
118771             mouseover: me.onMouseOver,
118772             scope: me
118773         });
118774         me.mouseMonitor = me.el.monitorMouseLeave(100, me.onMouseLeave, me);
118775
118776         if (me.showSeparator && ((!Ext.isStrict && Ext.isIE) || Ext.isIE6)) {
118777             me.iconSepEl.setHeight(me.el.getHeight());
118778         }
118779
118780         me.keyNav = Ext.create('Ext.menu.KeyNav', me);
118781     },
118782
118783     afterLayout: function() {
118784         var me = this;
118785         me.callParent(arguments);
118786
118787         // For IE6 & IE quirks, we have to resize the el and body since position: absolute
118788         // floating elements inherit their parent's width, making them the width of
118789         // document.body instead of the width of their contents.
118790         // This includes left/right dock items.
118791         if ((!Ext.iStrict && Ext.isIE) || Ext.isIE6) {
118792             var innerCt = me.layout.getRenderTarget(),
118793                 innerCtWidth = 0,
118794                 dis = me.dockedItems,
118795                 l = dis.length,
118796                 i = 0,
118797                 di, clone, newWidth;
118798
118799             innerCtWidth = innerCt.getWidth();
118800
118801             newWidth = innerCtWidth + me.body.getBorderWidth('lr') + me.body.getPadding('lr');
118802
118803             // First set the body to the new width
118804             me.body.setWidth(newWidth);
118805
118806             // Now we calculate additional width (docked items) and set the el's width
118807             for (; i < l, di = dis.getAt(i); i++) {
118808                 if (di.dock == 'left' || di.dock == 'right') {
118809                     newWidth += di.getWidth();
118810                 }
118811             }
118812             me.el.setWidth(newWidth);
118813         }
118814     },
118815
118816     /**
118817      * Returns whether a menu item can be activated or not.
118818      * @return {Boolean}
118819      */
118820     canActivateItem: function(item) {
118821         return item && !item.isDisabled() && item.isVisible() && (item.canActivate || item.getXTypes().indexOf('menuitem') < 0);
118822     },
118823
118824     /**
118825      * Deactivates the current active item on the menu, if one exists.
118826      */
118827     deactivateActiveItem: function() {
118828         var me = this;
118829
118830         if (me.activeItem) {
118831             me.activeItem.deactivate();
118832             if (!me.activeItem.activated) {
118833                 delete me.activeItem;
118834             }
118835         }
118836         if (me.focusedItem) {
118837             me.focusedItem.blur();
118838             if (!me.focusedItem.$focused) {
118839                 delete me.focusedItem;
118840             }
118841         }
118842     },
118843
118844     // inherit docs
118845     getFocusEl: function() {
118846         return this.focusEl;
118847     },
118848
118849     // inherit docs
118850     hide: function() {
118851         this.deactivateActiveItem();
118852         this.callParent(arguments);
118853     },
118854
118855     // private
118856     getItemFromEvent: function(e) {
118857         return this.getChildByElement(e.getTarget());
118858     },
118859
118860     lookupComponent: function(cmp) {
118861         var me = this;
118862
118863         if (Ext.isString(cmp)) {
118864             cmp = me.lookupItemFromString(cmp);
118865         } else if (Ext.isObject(cmp)) {
118866             cmp = me.lookupItemFromObject(cmp);
118867         }
118868
118869         // Apply our minWidth to all of our child components so it's accounted
118870         // for in our VBox layout
118871         cmp.minWidth = cmp.minWidth || me.minWidth;
118872
118873         return cmp;
118874     },
118875
118876     // private
118877     lookupItemFromObject: function(cmp) {
118878         var me = this,
118879             prefix = Ext.baseCSSPrefix;
118880
118881         if (!cmp.isComponent) {
118882             if (!cmp.xtype) {
118883                 cmp = Ext.create('Ext.menu.' + (Ext.isBoolean(cmp.checked) ? 'Check': '') + 'Item', cmp);
118884             } else {
118885                 cmp = Ext.ComponentManager.create(cmp, cmp.xtype);
118886             }
118887         }
118888
118889         if (cmp.isMenuItem) {
118890             cmp.parentMenu = me;
118891         }
118892
118893         if (!cmp.isMenuItem && !cmp.dock) {
118894             var cls = [
118895                     prefix + 'menu-item',
118896                     prefix + 'menu-item-cmp'
118897                 ],
118898                 intercept = Ext.Function.createInterceptor;
118899
118900             // Wrap focus/blur to control component focus
118901             cmp.focus = intercept(cmp.focus, function() {
118902                 this.$focused = true;
118903             }, cmp);
118904             cmp.blur = intercept(cmp.blur, function() {
118905                 this.$focused = false;
118906             }, cmp);
118907
118908             if (!me.plain && (cmp.indent === true || cmp.iconCls === 'no-icon')) {
118909                 cls.push(prefix + 'menu-item-indent');
118910             }
118911
118912             if (cmp.rendered) {
118913                 cmp.el.addCls(cls);
118914             } else {
118915                 cmp.cls = (cmp.cls ? cmp.cls : '') + ' ' + cls.join(' ');
118916             }
118917             cmp.isMenuItem = true;
118918         }
118919         return cmp;
118920     },
118921
118922     // private
118923     lookupItemFromString: function(cmp) {
118924         return (cmp == 'separator' || cmp == '-') ?
118925             Ext.createWidget('menuseparator')
118926             : Ext.createWidget('menuitem', {
118927                 canActivate: false,
118928                 hideOnClick: false,
118929                 plain: true,
118930                 text: cmp
118931             });
118932     },
118933
118934     onClick: function(e) {
118935         var me = this,
118936             item;
118937
118938         if (me.disabled) {
118939             e.stopEvent();
118940             return;
118941         }
118942
118943         if ((e.getTarget() == me.focusEl.dom) || e.within(me.layout.getRenderTarget())) {
118944             item = me.getItemFromEvent(e) || me.activeItem;
118945
118946             if (item) {
118947                 if (item.getXTypes().indexOf('menuitem') >= 0) {
118948                     if (!item.menu || !me.ignoreParentClicks) {
118949                         item.onClick(e);
118950                     } else {
118951                         e.stopEvent();
118952                     }
118953                 }
118954             }
118955             me.fireEvent('click', me, item, e);
118956         }
118957     },
118958
118959     onDestroy: function() {
118960         var me = this;
118961
118962         Ext.menu.Manager.unregister(me);
118963         if (me.rendered) {
118964             me.el.un(me.mouseMonitor);
118965             me.keyNav.destroy();
118966             delete me.keyNav;
118967         }
118968         me.callParent(arguments);
118969     },
118970
118971     onMouseLeave: function(e) {
118972         var me = this;
118973
118974         me.deactivateActiveItem();
118975
118976         if (me.disabled) {
118977             return;
118978         }
118979
118980         me.fireEvent('mouseleave', me, e);
118981     },
118982
118983     onMouseOver: function(e) {
118984         var me = this,
118985             fromEl = e.getRelatedTarget(),
118986             mouseEnter = !me.el.contains(fromEl),
118987             item = me.getItemFromEvent(e);
118988
118989         if (mouseEnter && me.parentMenu) {
118990             me.parentMenu.setActiveItem(me.parentItem);
118991             me.parentMenu.mouseMonitor.mouseenter();
118992         }
118993
118994         if (me.disabled) {
118995             return;
118996         }
118997
118998         if (item) {
118999             me.setActiveItem(item);
119000             if (item.activated && item.expandMenu) {
119001                 item.expandMenu();
119002             }
119003         }
119004         if (mouseEnter) {
119005             me.fireEvent('mouseenter', me, e);
119006         }
119007         me.fireEvent('mouseover', me, item, e);
119008     },
119009
119010     setActiveItem: function(item) {
119011         var me = this;
119012
119013         if (item && (item != me.activeItem && item != me.focusedItem)) {
119014             me.deactivateActiveItem();
119015             if (me.canActivateItem(item)) {
119016                 if (item.activate) {
119017                     item.activate();
119018                     if (item.activated) {
119019                         me.activeItem = item;
119020                         me.focusedItem = item;
119021                         me.focus();
119022                     }
119023                 } else {
119024                     item.focus();
119025                     me.focusedItem = item;
119026                 }
119027             }
119028             item.el.scrollIntoView(me.layout.getRenderTarget());
119029         }
119030     },
119031
119032     /**
119033      * Shows the floating menu by the specified {@link Ext.Component Component} or {@link Ext.core.Element Element}.
119034      * @param {Mixed component} The {@link Ext.Component} or {@link Ext.core.Element} to show the menu by.
119035      * @param {String} position (optional) Alignment position as used by {@link Ext.core.Element#getAlignToXY Ext.core.Element.getAlignToXY}. Defaults to `{@link #defaultAlign}`.
119036      * @param {Array} offsets (optional) Alignment offsets as used by {@link Ext.core.Element#getAlignToXY Ext.core.Element.getAlignToXY}. Defaults to `undefined`.
119037      * @return {Menu} This Menu.
119038      * @markdown
119039      */
119040     showBy: function(cmp, pos, off) {
119041         var me = this;
119042
119043         if (me.floating && cmp) {
119044             me.layout.autoSize = true;
119045             me.show();
119046
119047             // Component or Element
119048             cmp = cmp.el || cmp;
119049
119050             // Convert absolute to floatParent-relative coordinates if necessary.
119051             var xy = me.el.getAlignToXY(cmp, pos || me.defaultAlign, off);
119052             if (me.floatParent) {
119053                 var r = me.floatParent.getTargetEl().getViewRegion();
119054                 xy[0] -= r.x;
119055                 xy[1] -= r.y;
119056             }
119057             me.showAt(xy);
119058             me.doConstrain();
119059         }
119060         return me;
119061     },
119062
119063     doConstrain : function() {
119064         var me = this,
119065             y = this.el.getY(),
119066             max, full,
119067             returnY = y, normalY, parentEl, scrollTop, viewHeight;
119068
119069         delete me.height;
119070         me.setSize();
119071         full = me.getHeight();
119072         if (me.floating) {
119073             parentEl = Ext.fly(me.el.dom.parentNode);
119074             scrollTop = parentEl.getScroll().top;
119075             viewHeight = parentEl.getViewSize().height;
119076             //Normalize y by the scroll position for the parent element.  Need to move it into the coordinate space
119077             //of the view.
119078             normalY = y - scrollTop;
119079             max = me.maxHeight ? me.maxHeight : viewHeight - normalY;
119080             if (full > viewHeight) {
119081                 max = viewHeight;
119082                 //Set returnY equal to (0,0) in view space by reducing y by the value of normalY
119083                 returnY = y - normalY;
119084             } else if (max < full) {
119085                 returnY = y - (full - max);
119086                 max = full;
119087             }
119088         }else{
119089             max = me.getHeight();
119090         }
119091         // Always respect maxHeight
119092         if (me.maxHeight){
119093             max = Math.min(me.maxHeight, max);
119094         }
119095         if (full > max && max > 0){
119096             me.layout.autoSize = false;
119097             me.setHeight(max);
119098             if (me.showSeparator){
119099                 me.iconSepEl.setHeight(me.layout.getRenderTarget().dom.scrollHeight);
119100             }
119101         }
119102         me.el.setY(returnY);
119103     }
119104 });
119105 /**
119106  * @class Ext.menu.ColorPicker
119107  * @extends Ext.menu.Menu
119108  * <p>A menu containing a {@link Ext.picker.Color} Component.</p>
119109  * <p>Notes:</p><div class="mdetail-params"><ul>
119110  * <li>Although not listed here, the <b>constructor</b> for this class
119111  * accepts all of the configuration options of <b>{@link Ext.picker.Color}</b>.</li>
119112  * <li>If subclassing ColorMenu, any configuration options for the ColorPicker must be
119113  * applied to the <tt><b>initialConfig</b></tt> property of the ColorMenu.
119114  * Applying {@link Ext.picker.Color ColorPicker} configuration settings to
119115  * <b><tt>this</tt></b> will <b>not</b> affect the ColorPicker's configuration.</li>
119116  * </ul></div>
119117  * {@img Ext.menu.ColorPicker/Ext.menu.ColorPicker.png Ext.menu.ColorPicker component}
119118  * __Example Usage__
119119      var colorPicker = Ext.create('Ext.menu.ColorPicker', {
119120         value: '000000'
119121     });
119122
119123     Ext.create('Ext.menu.Menu', {
119124                 width: 100,
119125                 height: 90,
119126                 floating: false,  // usually you want this set to True (default)
119127                 renderTo: Ext.getBody(),  // usually rendered by it's containing component
119128                 items: [{
119129                     text: 'choose a color',
119130                     menu: colorPicker
119131                 },{
119132             iconCls: 'add16',
119133                     text: 'icon item'
119134                 },{
119135                     text: 'regular item'
119136                 }]
119137         });
119138
119139  * @xtype colormenu
119140  * @author Nicolas Ferrero
119141  */
119142  Ext.define('Ext.menu.ColorPicker', {
119143      extend: 'Ext.menu.Menu',
119144
119145      alias: 'widget.colormenu',
119146
119147      requires: [
119148         'Ext.picker.Color'
119149      ],
119150
119151     /**
119152      * @cfg {Boolean} hideOnClick
119153      * False to continue showing the menu after a date is selected, defaults to true.
119154      */
119155     hideOnClick : true,
119156
119157     /**
119158      * @cfg {String} pickerId
119159      * An id to assign to the underlying color picker. Defaults to <tt>null</tt>.
119160      */
119161     pickerId : null,
119162
119163     /**
119164      * @cfg {Number} maxHeight
119165      * @hide
119166      */
119167
119168     /**
119169      * The {@link Ext.picker.Color} instance for this ColorMenu
119170      * @property picker
119171      * @type ColorPicker
119172      */
119173
119174     /**
119175      * @event click
119176      * @hide
119177      */
119178
119179     /**
119180      * @event itemclick
119181      * @hide
119182      */
119183
119184     initComponent : function(){
119185         var me = this;
119186
119187         Ext.apply(me, {
119188             plain: true,
119189             showSeparator: false,
119190             items: Ext.applyIf({
119191                 cls: Ext.baseCSSPrefix + 'menu-color-item',
119192                 id: me.pickerId,
119193                 xtype: 'colorpicker'
119194             }, me.initialConfig)
119195         });
119196
119197         me.callParent(arguments);
119198
119199         me.picker = me.down('colorpicker');
119200
119201         /**
119202          * @event select
119203          * Fires when a date is selected from the {@link #picker Ext.picker.Color}
119204          * @param {Ext.picker.Color} picker The {@link #picker Ext.picker.Color}
119205          * @param {String} color The 6-digit color hex code (without the # symbol)
119206          */
119207         me.relayEvents(me.picker, ['select']);
119208
119209         if (me.hideOnClick) {
119210             me.on('select', me.hidePickerOnSelect, me);
119211         }
119212     },
119213
119214     /**
119215      * Hides picker on select if hideOnClick is true
119216      * @private
119217      */
119218     hidePickerOnSelect: function() {
119219         Ext.menu.Manager.hideAll();
119220     }
119221  });
119222 /**
119223  * @class Ext.menu.DatePicker
119224  * @extends Ext.menu.Menu
119225  * <p>A menu containing an {@link Ext.picker.Date} Component.</p>
119226  * <p>Notes:</p><div class="mdetail-params"><ul>
119227  * <li>Although not listed here, the <b>constructor</b> for this class
119228  * accepts all of the configuration options of <b>{@link Ext.picker.Date}</b>.</li>
119229  * <li>If subclassing DateMenu, any configuration options for the DatePicker must be
119230  * applied to the <tt><b>initialConfig</b></tt> property of the DateMenu.
119231  * Applying {@link Ext.picker.Date DatePicker} configuration settings to
119232  * <b><tt>this</tt></b> will <b>not</b> affect the DatePicker's configuration.</li>
119233  * </ul></div>
119234  * {@img Ext.menu.DatePicker/Ext.menu.DatePicker.png Ext.menu.DatePicker component}
119235  * __Example Usage__
119236      var dateMenu = Ext.create('Ext.menu.DatePicker', {
119237         handler: function(dp, date){
119238             Ext.Msg.alert('Date Selected', 'You choose {0}.', Ext.Date.format(date, 'M j, Y'));
119239
119240         }
119241     });
119242
119243     Ext.create('Ext.menu.Menu', {
119244                 width: 100,
119245                 height: 90,
119246                 floating: false,  // usually you want this set to True (default)
119247                 renderTo: Ext.getBody(),  // usually rendered by it's containing component
119248                 items: [{
119249                     text: 'choose a date',
119250                     menu: dateMenu
119251                 },{
119252             iconCls: 'add16',
119253                     text: 'icon item'
119254                 },{
119255                     text: 'regular item'
119256                 }]
119257         });
119258
119259  * @xtype datemenu
119260  * @author Nicolas Ferrero
119261  */
119262  Ext.define('Ext.menu.DatePicker', {
119263      extend: 'Ext.menu.Menu',
119264
119265      alias: 'widget.datemenu',
119266
119267      requires: [
119268         'Ext.picker.Date'
119269      ],
119270
119271     /**
119272      * @cfg {Boolean} hideOnClick
119273      * False to continue showing the menu after a date is selected, defaults to true.
119274      */
119275     hideOnClick : true,
119276
119277     /**
119278      * @cfg {String} pickerId
119279      * An id to assign to the underlying date picker. Defaults to <tt>null</tt>.
119280      */
119281     pickerId : null,
119282
119283     /**
119284      * @cfg {Number} maxHeight
119285      * @hide
119286      */
119287
119288     /**
119289      * The {@link Ext.picker.Date} instance for this DateMenu
119290      * @property picker
119291      * @type Ext.picker.Date
119292      */
119293
119294     /**
119295      * @event click
119296      * @hide
119297      */
119298
119299     /**
119300      * @event itemclick
119301      * @hide
119302      */
119303
119304     initComponent : function(){
119305         var me = this;
119306
119307         Ext.apply(me, {
119308             showSeparator: false,
119309             plain: true,
119310             items: Ext.applyIf({
119311                 cls: Ext.baseCSSPrefix + 'menu-date-item',
119312                 id: me.pickerId,
119313                 xtype: 'datepicker'
119314             }, me.initialConfig)
119315         });
119316
119317         me.callParent(arguments);
119318
119319         me.picker = me.down('datepicker');
119320         /**
119321          * @event select
119322          * Fires when a date is selected from the {@link #picker Ext.picker.Date}
119323          * @param {Ext.picker.Date} picker The {@link #picker Ext.picker.Date}
119324          * @param {Date} date The selected date
119325          */
119326         me.relayEvents(me.picker, ['select']);
119327
119328         if (me.hideOnClick) {
119329             me.on('select', me.hidePickerOnSelect, me);
119330         }
119331     },
119332
119333     hidePickerOnSelect: function() {
119334         Ext.menu.Manager.hideAll();
119335     }
119336  });
119337 /**
119338  * @class Ext.panel.Tool
119339  * @extends Ext.Component
119340
119341 This class is used to display small visual icons in the header of a panel. There are a set of
119342 25 icons that can be specified by using the {@link #type} config. The {@link #handler} config
119343 can be used to provide a function that will respond to any click events. In general, this class
119344 will not be instantiated directly, rather it will be created by specifying the {@link Ext.panel.Panel#tools}
119345 configuration on the Panel itself.
119346
119347 __Example Usage__
119348
119349     Ext.create('Ext.panel.Panel', {
119350        width: 200,
119351        height: 200,
119352        renderTo: document.body,
119353        title: 'A Panel',
119354        tools: [{
119355            type: 'help',
119356            handler: function(){
119357                // show help here
119358            }
119359        }, {
119360            itemId: 'refresh',
119361            type: 'refresh',
119362            hidden: true,
119363            handler: function(){
119364                // do refresh
119365            }
119366        }, {
119367            type: 'search',
119368            handler: function(event, target, owner, tool){
119369                // do search
119370                owner.child('#refresh').show();
119371            }
119372        }]
119373     });
119374
119375  * @markdown
119376  * @xtype tool
119377  */
119378 Ext.define('Ext.panel.Tool', {
119379     extend: 'Ext.Component',
119380     requires: ['Ext.tip.QuickTipManager'],
119381     alias: 'widget.tool',
119382
119383     baseCls: Ext.baseCSSPrefix + 'tool',
119384     disabledCls: Ext.baseCSSPrefix + 'tool-disabled',
119385     toolPressedCls: Ext.baseCSSPrefix + 'tool-pressed',
119386     toolOverCls: Ext.baseCSSPrefix + 'tool-over',
119387     ariaRole: 'button',
119388     renderTpl: ['<img src="{blank}" class="{baseCls}-{type}" role="presentation"/>'],
119389     
119390     /**
119391      * @cfg {Function} handler
119392      * A function to execute when the tool is clicked.
119393      * Arguments passed are:
119394      * <ul>
119395      * <li><b>event</b> : Ext.EventObject<div class="sub-desc">The click event.</div></li>
119396      * <li><b>toolEl</b> : Ext.core.Element<div class="sub-desc">The tool Element.</div></li>
119397      * <li><b>panel</b> : Ext.panel.Panel<div class="sub-desc">The host Panel</div></li>
119398      * <li><b>tool</b> : Ext.panel.Tool<div class="sub-desc">The tool object</div></li>
119399      * </ul>
119400      */
119401     
119402     /**
119403      * @cfg {Object} scope
119404      * The scope to execute the {@link #handler} function. Defaults to the tool.
119405      */
119406     
119407     /**
119408      * @cfg {String} type
119409      * The type of tool to render. The following types are available:
119410      * <ul>
119411      * <li>close</li>
119412      * <li>collapse</li>
119413      * <li>down</li>
119414      * <li>expand</li>
119415      * <li>gear</li>
119416      * <li>help</li>
119417      * <li>left</li>
119418      * <li>maximize</li>
119419      * <li>minimize</li>
119420      * <li>minus</li>
119421      * <li>move</li>
119422      * <li>next</li>
119423      * <li>pin</li>
119424      * <li>plus</li>
119425      * <li>prev</li>
119426      * <li>print</li>
119427      * <li>refresh</li>
119428      * <li>resize</li>
119429      * <li>restore</li>
119430      * <li>right</li>
119431      * <li>save</li>
119432      * <li>search</li>
119433      * <li>toggle</li>
119434      * <li>unpin</li>
119435      * <li>up</li>
119436      * </ul>
119437      */
119438     
119439     /**
119440      * @cfg {String/Object} tooltip 
119441      * The tooltip for the tool - can be a string to be used as innerHTML (html tags are accepted) or QuickTips config object
119442      */
119443     
119444     /**
119445      * @cfg {Boolean} stopEvent
119446      * Defaults to true. Specify as false to allow click event to propagate.
119447      */
119448     stopEvent: true,
119449
119450     initComponent: function() {
119451         var me = this;
119452         me.addEvents(
119453             /**
119454              * @event click
119455              * Fires when the tool is clicked
119456              * @param {Ext.panel.Tool} this
119457              * @param {Ext.EventObject} e The event object
119458              */
119459             'click'
119460         );
119461         
119462         var types = [
119463             'close', 
119464             'collapse', 
119465             'down', 
119466             'expand', 
119467             'gear', 
119468             'help', 
119469             'left', 
119470             'maximize', 
119471             'minimize', 
119472             'minus', 
119473             'move', 
119474             'next', 
119475             'pin', 
119476             'plus', 
119477             'prev', 
119478             'print', 
119479             'refresh', 
119480             'resize', 
119481             'restore', 
119482             'right', 
119483             'save', 
119484             'search', 
119485             'toggle',
119486             'unpin', 
119487             'up'
119488         ];
119489         
119490         if (me.id && Ext.Array.indexOf(types, me.id) > -1) {
119491             Ext.global.console.warn('When specifying a tool you should use the type option, the id can conflict now that tool is a Component');
119492         }
119493         
119494         me.type = me.type || me.id;
119495
119496         Ext.applyIf(me.renderData, {
119497             baseCls: me.baseCls,
119498             blank: Ext.BLANK_IMAGE_URL,
119499             type: me.type
119500         });
119501         me.renderSelectors.toolEl = '.' + me.baseCls + '-' + me.type;
119502         me.callParent();
119503     },
119504
119505     // inherit docs
119506     afterRender: function() {
119507         var me = this;
119508         me.callParent(arguments);
119509         if (me.qtip) {
119510             if (Ext.isObject(me.qtip)) {
119511                 Ext.tip.QuickTipManager.register(Ext.apply({
119512                     target: me.id
119513                 }, me.qtip));
119514             }
119515             else {
119516                 me.toolEl.dom.qtip = me.qtip;
119517             }
119518         }
119519
119520         me.mon(me.toolEl, {
119521             click: me.onClick,
119522             mousedown: me.onMouseDown,
119523             mouseover: me.onMouseOver,
119524             mouseout: me.onMouseOut,
119525             scope: me
119526         });
119527     },
119528
119529     /**
119530      * Set the type of the tool. Allows the icon to be changed.
119531      * @param {String} type The new type. See the {@link #type} config.
119532      * @return {Ext.panel.Tool} this
119533      */
119534     setType: function(type) {
119535         var me = this;
119536         
119537         me.type = type;
119538         if (me.rendered) {
119539             me.toolEl.dom.className = me.baseCls + '-' + type;
119540         }
119541         return me;
119542     },
119543
119544     /**
119545      * Binds this tool to a component.
119546      * @private
119547      * @param {Ext.Component} component The component
119548      */
119549     bindTo: function(component) {
119550         this.owner = component;
119551     },
119552
119553     /**
119554      * Fired when the tool element is clicked
119555      * @private
119556      * @param {Ext.EventObject} e
119557      * @param {HTMLElement} target The target element
119558      */
119559     onClick: function(e, target) {
119560         var me = this,
119561             owner;
119562             
119563         if (me.disabled) {
119564             return false;
119565         }
119566         owner = me.owner || me.ownerCt;
119567
119568         //remove the pressed + over class
119569         me.el.removeCls(me.toolPressedCls);
119570         me.el.removeCls(me.toolOverCls);
119571
119572         if (me.stopEvent !== false) {
119573             e.stopEvent();
119574         }
119575
119576         Ext.callback(me.handler, me.scope || me, [e, target, owner, me]);
119577         me.fireEvent('click', me, e);
119578         return true;
119579     },
119580     
119581     // inherit docs
119582     onDestroy: function(){
119583         if (Ext.isObject(this.tooltip)) {
119584             Ext.tip.QuickTipManager.unregister(this.id);
119585         }    
119586         this.callParent();
119587     },
119588
119589     /**
119590      * Called then the user pressing their mouse button down on a tool
119591      * Adds the press class ({@link #toolPressedCls})
119592      * @private
119593      */
119594     onMouseDown: function() {
119595         if (this.disabled) {
119596             return false;
119597         }
119598
119599         this.el.addCls(this.toolPressedCls);
119600     },
119601
119602     /**
119603      * Called when the user rolls over a tool
119604      * Adds the over class ({@link #toolOverCls})
119605      * @private
119606      */
119607     onMouseOver: function() {
119608         if (this.disabled) {
119609             return false;
119610         }
119611         this.el.addCls(this.toolOverCls);
119612     },
119613
119614     /**
119615      * Called when the user rolls out from a tool.
119616      * Removes the over class ({@link #toolOverCls})
119617      * @private
119618      */
119619     onMouseOut: function() {
119620         this.el.removeCls(this.toolOverCls);
119621     }
119622 });
119623 /**
119624  * @class Ext.resizer.Handle
119625  * @extends Ext.Component
119626  *
119627  * Provides a handle for 9-point resizing of Elements or Components.
119628  */
119629 Ext.define('Ext.resizer.Handle', {
119630     extend: 'Ext.Component',
119631     handleCls: '',
119632     baseHandleCls: Ext.baseCSSPrefix + 'resizable-handle',
119633     // Ext.resizer.Resizer.prototype.possiblePositions define the regions
119634     // which will be passed in as a region configuration.
119635     region: '',
119636
119637     onRender: function() {
119638         this.addCls(
119639             this.baseHandleCls,
119640             this.baseHandleCls + '-' + this.region,
119641             this.handleCls
119642         );
119643         this.callParent(arguments);
119644         this.el.unselectable();
119645     }
119646 });
119647
119648 /**
119649  * @class Ext.resizer.Resizer
119650  * <p>Applies drag handles to an element or component to make it resizable. The
119651  * drag handles are inserted into the element (or component's element) and
119652  * positioned absolute.</p>
119653  *
119654  * <p>Textarea and img elements will be wrapped with an additional div because
119655  * these elements do not support child nodes. The original element can be accessed
119656  * through the originalTarget property.</p>
119657  *
119658  * <p>Here is the list of valid resize handles:</p>
119659  * <pre>
119660 Value   Description
119661 ------  -------------------
119662  'n'     north
119663  's'     south
119664  'e'     east
119665  'w'     west
119666  'nw'    northwest
119667  'sw'    southwest
119668  'se'    southeast
119669  'ne'    northeast
119670  'all'   all
119671 </pre>
119672  * {@img Ext.resizer.Resizer/Ext.resizer.Resizer.png Ext.resizer.Resizer component}
119673  * <p>Here's an example showing the creation of a typical Resizer:</p>
119674  * <pre><code>
119675     <div id="elToResize" style="width:200px; height:100px; background-color:#000000;"></div>
119676
119677     Ext.create('Ext.resizer.Resizer', {
119678         el: 'elToResize',
119679         handles: 'all',
119680         minWidth: 200,
119681         minHeight: 100,
119682         maxWidth: 500,
119683         maxHeight: 400,
119684         pinned: true
119685     });
119686 </code></pre>
119687 */
119688 Ext.define('Ext.resizer.Resizer', {
119689     mixins: {
119690         observable: 'Ext.util.Observable'
119691     },
119692     uses: ['Ext.resizer.ResizeTracker', 'Ext.Component'],
119693
119694     alternateClassName: 'Ext.Resizable',
119695
119696     handleCls: Ext.baseCSSPrefix + 'resizable-handle',
119697     pinnedCls: Ext.baseCSSPrefix + 'resizable-pinned',
119698     overCls:   Ext.baseCSSPrefix + 'resizable-over',
119699     proxyCls:  Ext.baseCSSPrefix + 'resizable-proxy',
119700     wrapCls:   Ext.baseCSSPrefix + 'resizable-wrap',
119701
119702     /**
119703      * @cfg {Boolean} dynamic
119704      * <p>Specify as true to update the {@link #target} (Element or {@link Ext.Component Component}) dynamically during dragging.
119705      * This is <code>true</code> by default, but the {@link Ext.Component Component} class passes <code>false</code> when it
119706      * is configured as {@link Ext.Component#resizable}.</p>
119707      * <p>If specified as <code>false</code>, a proxy element is displayed during the resize operation, and the {@link #target}
119708      * is updated on mouseup.</p>
119709      */
119710     dynamic: true,
119711
119712     /**
119713      * @cfg {String} handles String consisting of the resize handles to display. Defaults to 's e se' for
119714      * Elements and fixed position Components. Defaults to 8 point resizing for floating Components (such as Windows).
119715      * Specify either <code>'all'</code> or any of <code>'n s e w ne nw se sw'</code>.
119716      */
119717     handles: 's e se',
119718
119719     /**
119720      * @cfg {Number} height Optional. The height to set target to in pixels (defaults to null)
119721      */
119722     height : null,
119723
119724     /**
119725      * @cfg {Number} width Optional. The width to set the target to in pixels (defaults to null)
119726      */
119727     width : null,
119728
119729     /**
119730      * @cfg {Number} minHeight The minimum height for the element (defaults to 20)
119731      */
119732     minHeight : 20,
119733
119734     /**
119735      * @cfg {Number} minWidth The minimum width for the element (defaults to 20)
119736      */
119737     minWidth : 20,
119738
119739     /**
119740      * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
119741      */
119742     maxHeight : 10000,
119743
119744     /**
119745      * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
119746      */
119747     maxWidth : 10000,
119748
119749     /**
119750      * @cfg {Boolean} pinned True to ensure that the resize handles are always
119751      * visible, false indicates resizing by cursor changes only (defaults to false)
119752      */
119753     pinned: false,
119754
119755     /**
119756      * @cfg {Boolean} preserveRatio True to preserve the original ratio between height
119757      * and width during resize (defaults to false)
119758      */
119759     preserveRatio: false,
119760
119761     /**
119762      * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
119763      */
119764     transparent: false,
119765
119766     /**
119767      * @cfg {Mixed} constrainTo Optional. An element, or a {@link Ext.util.Region} into which the resize operation
119768      * must be constrained.
119769      */
119770
119771     possiblePositions: {
119772         n:  'north',
119773         s:  'south',
119774         e:  'east',
119775         w:  'west',
119776         se: 'southeast',
119777         sw: 'southwest',
119778         nw: 'northwest',
119779         ne: 'northeast'
119780     },
119781
119782     /**
119783      * @cfg {Mixed} target The Element or Component to resize.
119784      */
119785
119786     /**
119787      * Outer element for resizing behavior.
119788      * @type Ext.core.Element
119789      * @property el
119790      */
119791
119792     constructor: function(config) {
119793         var me = this,
119794             target,
119795             tag,
119796             handles = me.handles,
119797             handleCls,
119798             possibles,
119799             len,
119800             i = 0,
119801             pos;
119802
119803         this.addEvents(
119804             /**
119805              * @event beforeresize
119806              * Fired before resize is allowed. Return false to cancel resize.
119807              * @param {Ext.resizer.Resizer} this
119808              * @param {Number} width The start width
119809              * @param {Number} height The start height
119810              * @param {Ext.EventObject} e The mousedown event
119811              */
119812             'beforeresize',
119813             /**
119814              * @event resizedrag
119815              * Fires during resizing. Return false to cancel resize.
119816              * @param {Ext.resizer.Resizer} this
119817              * @param {Number} width The new width
119818              * @param {Number} height The new height
119819              * @param {Ext.EventObject} e The mousedown event
119820              */
119821             'resizedrag',
119822             /**
119823              * @event resize
119824              * Fired after a resize.
119825              * @param {Ext.resizer.Resizer} this
119826              * @param {Number} width The new width
119827              * @param {Number} height The new height
119828              * @param {Ext.EventObject} e The mouseup event
119829              */
119830             'resize'
119831         );
119832
119833         if (Ext.isString(config) || Ext.isElement(config) || config.dom) {
119834             target = config;
119835             config = arguments[1] || {};
119836             config.target = target;
119837         }
119838         // will apply config to this
119839         me.mixins.observable.constructor.call(me, config);
119840
119841         // If target is a Component, ensure that we pull the element out.
119842         // Resizer must examine the underlying Element.
119843         target = me.target;
119844         if (target) {
119845             if (target.isComponent) {
119846                 me.el = target.getEl();
119847                 if (target.minWidth) {
119848                     me.minWidth = target.minWidth;
119849                 }
119850                 if (target.minHeight) {
119851                     me.minHeight = target.minHeight;
119852                 }
119853                 if (target.maxWidth) {
119854                     me.maxWidth = target.maxWidth;
119855                 }
119856                 if (target.maxHeight) {
119857                     me.maxHeight = target.maxHeight;
119858                 }
119859                 if (target.floating) {
119860                     if (!this.hasOwnProperty('handles')) {
119861                         this.handles = 'n ne e se s sw w nw';
119862                     }
119863                 }
119864             } else {
119865                 me.el = me.target = Ext.get(target);
119866             }
119867         }
119868         // Backwards compatibility with Ext3.x's Resizable which used el as a config.
119869         else {
119870             me.target = me.el = Ext.get(me.el);
119871         }
119872
119873         // Tags like textarea and img cannot
119874         // have children and therefore must
119875         // be wrapped
119876         tag = me.el.dom.tagName;
119877         if (tag == 'TEXTAREA' || tag == 'IMG') {
119878             /**
119879              * Reference to the original resize target if the element of the original
119880              * resize target was an IMG or a TEXTAREA which must be wrapped in a DIV.
119881              * @type Mixed
119882              * @property originalTarget
119883              */
119884             me.originalTarget = me.target;
119885             me.target = me.el = me.el.wrap({
119886                 cls: me.wrapCls,
119887                 id: me.el.id + '-rzwrap'
119888             });
119889
119890             // Transfer originalTarget's positioning/sizing
119891             me.el.setPositioning(me.originalTarget.getPositioning());
119892             me.originalTarget.clearPositioning();
119893             var box = me.originalTarget.getBox();
119894             me.el.setBox(box);
119895         }
119896
119897         // Position the element, this enables us to absolute position
119898         // the handles within this.el
119899         me.el.position();
119900         if (me.pinned) {
119901             me.el.addCls(me.pinnedCls);
119902         }
119903
119904         /**
119905          * @type Ext.resizer.ResizeTracker
119906          * @property resizeTracker
119907          */
119908         me.resizeTracker = Ext.create('Ext.resizer.ResizeTracker', {
119909             disabled: me.disabled,
119910             target: me.target,
119911             constrainTo: me.constrainTo,
119912             overCls: me.overCls,
119913             throttle: me.throttle,
119914             originalTarget: me.originalTarget,
119915             delegate: '.' + me.handleCls,
119916             dynamic: me.dynamic,
119917             preserveRatio: me.preserveRatio,
119918             minHeight: me.minHeight,
119919             maxHeight: me.maxHeight,
119920             minWidth: me.minWidth,
119921             maxWidth: me.maxWidth
119922         });
119923
119924         // Relay the ResizeTracker's superclass events as our own resize events
119925         me.resizeTracker.on('mousedown', me.onBeforeResize, me);
119926         me.resizeTracker.on('drag', me.onResize, me);
119927         me.resizeTracker.on('dragend', me.onResizeEnd, me);
119928
119929         if (me.handles == 'all') {
119930             me.handles = 'n s e w ne nw se sw';
119931         }
119932
119933         handles = me.handles = me.handles.split(/ |\s*?[,;]\s*?/);
119934         possibles = me.possiblePositions;
119935         len = handles.length;
119936         handleCls = me.handleCls + ' ' + (this.target.isComponent ? (me.target.baseCls + '-handle ') : '') + me.handleCls + '-';
119937
119938         for(; i < len; i++){
119939             // if specified and possible, create
119940             if (handles[i] && possibles[handles[i]]) {
119941                 pos = possibles[handles[i]];
119942                 // store a reference in this.east, this.west, etc
119943
119944                 me[pos] = Ext.create('Ext.Component', {
119945                     owner: this,
119946                     region: pos,
119947                     cls: handleCls + pos,
119948                     renderTo: me.el
119949                 });
119950                 me[pos].el.unselectable();
119951                 if (me.transparent) {
119952                     me[pos].el.setOpacity(0);
119953                 }
119954             }
119955         }
119956
119957         // Constrain within configured maxima
119958         if (Ext.isNumber(me.width)) {
119959             me.width = Ext.Number.constrain(me.width, me.minWidth, me.maxWidth);
119960         }
119961         if (Ext.isNumber(me.height)) {
119962             me.height = Ext.Number.constrain(me.height, me.minHeight, me.maxHeight);
119963         }
119964
119965         // Size the element
119966         if (me.width != null || me.height != null) {
119967             if (me.originalTarget) {
119968                 me.originalTarget.setWidth(me.width);
119969                 me.originalTarget.setHeight(me.height);
119970             }
119971             me.resizeTo(me.width, me.height);
119972         }
119973
119974         me.forceHandlesHeight();
119975     },
119976
119977     disable: function() {
119978         this.resizeTracker.disable();
119979     },
119980
119981     enable: function() {
119982         this.resizeTracker.enable();
119983     },
119984
119985     /**
119986      * @private Relay the Tracker's mousedown event as beforeresize
119987      * @param tracker The Resizer
119988      * @param e The Event
119989      */
119990     onBeforeResize: function(tracker, e) {
119991         var b = this.target.getBox();
119992         return this.fireEvent('beforeresize', this, b.width, b.height, e);
119993     },
119994
119995     /**
119996      * @private Relay the Tracker's drag event as resizedrag
119997      * @param tracker The Resizer
119998      * @param e The Event
119999      */
120000     onResize: function(tracker, e) {
120001         var me = this,
120002             b = me.target.getBox();
120003         me.forceHandlesHeight();
120004         return me.fireEvent('resizedrag', me, b.width, b.height, e);
120005     },
120006
120007     /**
120008      * @private Relay the Tracker's dragend event as resize
120009      * @param tracker The Resizer
120010      * @param e The Event
120011      */
120012     onResizeEnd: function(tracker, e) {
120013         var me = this,
120014             b = me.target.getBox();
120015         me.forceHandlesHeight();
120016         return me.fireEvent('resize', me, b.width, b.height, e);
120017     },
120018
120019     /**
120020      * Perform a manual resize and fires the 'resize' event.
120021      * @param {Number} width
120022      * @param {Number} height
120023      */
120024     resizeTo : function(width, height){
120025         this.target.setSize(width, height);
120026         this.fireEvent('resize', this, width, height, null);
120027     },
120028
120029     /**
120030      * <p>Returns the element that was configured with the el or target config property.
120031      * If a component was configured with the target property then this will return the
120032      * element of this component.<p>
120033      * <p>Textarea and img elements will be wrapped with an additional div because
120034       * these elements do not support child nodes. The original element can be accessed
120035      * through the originalTarget property.</p>
120036      * @return {Element} element
120037      */
120038     getEl : function() {
120039         return this.el;
120040     },
120041
120042     /**
120043      * <p>Returns the element or component that was configured with the target config property.<p>
120044      * <p>Textarea and img elements will be wrapped with an additional div because
120045       * these elements do not support child nodes. The original element can be accessed
120046      * through the originalTarget property.</p>
120047      * @return {Element/Component}
120048      */
120049     getTarget: function() {
120050         return this.target;
120051     },
120052
120053     destroy: function() {
120054         var h;
120055         for (var i = 0, l = this.handles.length; i < l; i++) {
120056             h = this[this.possiblePositions[this.handles[i]]];
120057             delete h.owner;
120058             Ext.destroy(h);
120059         }
120060     },
120061
120062     /**
120063      * @private
120064      * Fix IE6 handle height issue.
120065      */
120066     forceHandlesHeight : function() {
120067         var me = this,
120068             handle;
120069         if (Ext.isIE6) {
120070             handle = me.east; 
120071             if (handle) {
120072                 handle.setHeight(me.el.getHeight());
120073             }
120074             handle = me.west; 
120075             if (handle) {
120076                 handle.setHeight(me.el.getHeight());
120077             }
120078             me.el.repaint();
120079         }
120080     }
120081 });
120082
120083 /**
120084  * @class Ext.resizer.ResizeTracker
120085  * @extends Ext.dd.DragTracker
120086  */
120087 Ext.define('Ext.resizer.ResizeTracker', {
120088     extend: 'Ext.dd.DragTracker',
120089     dynamic: true,
120090     preserveRatio: false,
120091
120092     // Default to no constraint
120093     constrainTo: null,
120094
120095     constructor: function(config) {
120096         var me = this;
120097
120098         if (!config.el) {
120099             if (config.target.isComponent) {
120100                 me.el = config.target.getEl();
120101             } else {
120102                 me.el = config.target;
120103             }
120104         }
120105         this.callParent(arguments);
120106
120107         // Ensure that if we are preserving aspect ratio, the largest minimum is honoured
120108         if (me.preserveRatio && me.minWidth && me.minHeight) {
120109             var widthRatio = me.minWidth / me.el.getWidth(),
120110                 heightRatio = me.minHeight / me.el.getHeight();
120111
120112             // largest ratio of minimum:size must be preserved.
120113             // So if a 400x200 pixel image has
120114             // minWidth: 50, maxWidth: 50, the maxWidth will be 400 * (50/200)... that is 100
120115             if (heightRatio > widthRatio) {
120116                 me.minWidth = me.el.getWidth() * heightRatio;
120117             } else {
120118                 me.minHeight = me.el.getHeight() * widthRatio;
120119             }
120120         }
120121
120122         // If configured as throttled, create an instance version of resize which calls
120123         // a throttled function to perform the resize operation.
120124         if (me.throttle) {
120125             var throttledResizeFn = Ext.Function.createThrottled(function() {
120126                     Ext.resizer.ResizeTracker.prototype.resize.apply(me, arguments);
120127                 }, me.throttle);
120128
120129             me.resize = function(box, direction, atEnd) {
120130                 if (atEnd) {
120131                     Ext.resizer.ResizeTracker.prototype.resize.apply(me, arguments);
120132                 } else {
120133                     throttledResizeFn.apply(null, arguments);
120134                 }
120135             };
120136         }
120137     },
120138
120139     onBeforeStart: function(e) {
120140         // record the startBox
120141         this.startBox = this.el.getBox();
120142     },
120143
120144     /**
120145      * @private
120146      * Returns the object that will be resized on every mousemove event.
120147      * If dynamic is false, this will be a proxy, otherwise it will be our actual target.
120148      */
120149     getDynamicTarget: function() {
120150         var d = this.target;
120151         if (this.dynamic) {
120152             return d;
120153         } else if (!this.proxy) {
120154             this.proxy = d.isComponent ? d.getProxy().addCls(Ext.baseCSSPrefix + 'resizable-proxy') : d.createProxy({tag: 'div', cls: Ext.baseCSSPrefix + 'resizable-proxy', id: d.id + '-rzproxy'}, Ext.getBody());
120155             this.proxy.removeCls(Ext.baseCSSPrefix + 'proxy-el');
120156         }
120157         this.proxy.show();
120158         return this.proxy;
120159     },
120160
120161     onStart: function(e) {
120162         // returns the Ext.ResizeHandle that the user started dragging
120163         this.activeResizeHandle = Ext.getCmp(this.getDragTarget().id);
120164
120165         // If we are using a proxy, ensure it is sized.
120166         if (!this.dynamic) {
120167             this.resize(this.startBox, {
120168                 horizontal: 'none',
120169                 vertical: 'none'
120170             });
120171         }
120172     },
120173
120174     onDrag: function(e) {
120175         // dynamic resizing, update dimensions during resize
120176         if (this.dynamic || this.proxy) {
120177             this.updateDimensions(e);
120178         }
120179     },
120180
120181     updateDimensions: function(e, atEnd) {
120182         var me = this,
120183             region = me.activeResizeHandle.region,
120184             offset = me.getOffset(me.constrainTo ? 'dragTarget' : null),
120185             box = me.startBox,
120186             ratio,
120187             widthAdjust = 0,
120188             heightAdjust = 0,
120189             adjustX = 0,
120190             adjustY = 0,
120191             dragRatio,
120192             horizDir = offset[0] < 0 ? 'right' : 'left',
120193             vertDir = offset[1] < 0 ? 'down' : 'up',
120194             oppositeCorner,
120195             axis; // 1 = x, 2 = y, 3 = x and y.
120196
120197         switch (region) {
120198             case 'south':
120199                 heightAdjust = offset[1];
120200                 axis = 2;
120201                 break;
120202             case 'north':
120203                 heightAdjust = -offset[1];
120204                 adjustY = -heightAdjust;
120205                 axis = 2;
120206                 break;
120207             case 'east':
120208                 widthAdjust = offset[0];
120209                 axis = 1;
120210                 break;
120211             case 'west':
120212                 widthAdjust = -offset[0];
120213                 adjustX = -widthAdjust;
120214                 axis = 1;
120215                 break;
120216             case 'northeast':
120217                 heightAdjust = -offset[1];
120218                 adjustY = -heightAdjust;
120219                 widthAdjust = offset[0];
120220                 oppositeCorner = [box.x, box.y + box.height];
120221                 axis = 3;
120222                 break;
120223             case 'southeast':
120224                 heightAdjust = offset[1];
120225                 widthAdjust = offset[0];
120226                 oppositeCorner = [box.x, box.y];
120227                 axis = 3;
120228                 break;
120229             case 'southwest':
120230                 widthAdjust = -offset[0];
120231                 adjustX = -widthAdjust;
120232                 heightAdjust = offset[1];
120233                 oppositeCorner = [box.x + box.width, box.y];
120234                 axis = 3;
120235                 break;
120236             case 'northwest':
120237                 heightAdjust = -offset[1];
120238                 adjustY = -heightAdjust;
120239                 widthAdjust = -offset[0];
120240                 adjustX = -widthAdjust;
120241                 oppositeCorner = [box.x + box.width, box.y + box.height];
120242                 axis = 3;
120243                 break;
120244         }
120245
120246         var newBox = {
120247             width: box.width + widthAdjust,
120248             height: box.height + heightAdjust,
120249             x: box.x + adjustX,
120250             y: box.y + adjustY
120251         };
120252
120253         // out of bounds
120254         if (newBox.width < me.minWidth || newBox.width > me.maxWidth) {
120255             newBox.width = Ext.Number.constrain(newBox.width, me.minWidth, me.maxWidth);
120256             newBox.x = me.lastX || newBox.x;
120257         } else {
120258             me.lastX = newBox.x;
120259         }
120260         if (newBox.height < me.minHeight || newBox.height > me.maxHeight) {
120261             newBox.height = Ext.Number.constrain(newBox.height, me.minHeight, me.maxHeight);
120262             newBox.y = me.lastY || newBox.y;
120263         } else {
120264             me.lastY = newBox.y;
120265         }
120266
120267         // If this is configured to preserve the aspect ratio, or they are dragging using the shift key
120268         if (me.preserveRatio || e.shiftKey) {
120269             var newHeight,
120270                 newWidth;
120271
120272             ratio = me.startBox.width / me.startBox.height;
120273
120274             // Calculate aspect ratio constrained values.
120275             newHeight = Math.min(Math.max(me.minHeight, newBox.width / ratio), me.maxHeight);
120276             newWidth = Math.min(Math.max(me.minWidth, newBox.height * ratio), me.maxWidth);
120277
120278             // X axis: width-only change, height must obey
120279             if (axis == 1) {
120280                 newBox.height = newHeight;
120281             }
120282
120283             // Y axis: height-only change, width must obey
120284             else if (axis == 2) {
120285                 newBox.width = newWidth;
120286             }
120287
120288             // Corner drag.
120289             else {
120290                 // Drag ratio is the ratio of the mouse point from the opposite corner.
120291                 // Basically what edge we are dragging, a horizontal edge or a vertical edge.
120292                 dragRatio = Math.abs(oppositeCorner[0] - this.lastXY[0]) / Math.abs(oppositeCorner[1] - this.lastXY[1]);
120293
120294                 // If drag ratio > aspect ratio then width is dominant and height must obey
120295                 if (dragRatio > ratio) {
120296                     newBox.height = newHeight;
120297                 } else {
120298                     newBox.width = newWidth;
120299                 }
120300
120301                 // Handle dragging start coordinates
120302                 if (region == 'northeast') {
120303                     newBox.y = box.y - (newBox.height - box.height);
120304                 } else if (region == 'northwest') {
120305                     newBox.y = box.y - (newBox.height - box.height);
120306                     newBox.x = box.x - (newBox.width - box.width);
120307                 } else if (region == 'southwest') {
120308                     newBox.x = box.x - (newBox.width - box.width);
120309                 }
120310             }
120311         }
120312
120313         if (heightAdjust === 0) {
120314             vertDir = 'none';
120315         }
120316         if (widthAdjust === 0) {
120317             horizDir = 'none';
120318         }
120319         me.resize(newBox, {
120320             horizontal: horizDir,
120321             vertical: vertDir
120322         }, atEnd);
120323     },
120324
120325     getResizeTarget: function(atEnd) {
120326         return atEnd ? this.target : this.getDynamicTarget();
120327     },
120328
120329     resize: function(box, direction, atEnd) {
120330         var target = this.getResizeTarget(atEnd);
120331         if (target.isComponent) {
120332             if (target.floating) {
120333                 target.setPagePosition(box.x, box.y);
120334             }
120335             target.setSize(box.width, box.height);
120336         } else {
120337             target.setBox(box);
120338             // update the originalTarget if this was wrapped.
120339             if (this.originalTarget) {
120340                 this.originalTarget.setBox(box);
120341             }
120342         }
120343     },
120344
120345     onEnd: function(e) {
120346         this.updateDimensions(e, true);
120347         if (this.proxy) {
120348             this.proxy.hide();
120349         }
120350     }
120351 });
120352
120353 /**
120354  * @class Ext.resizer.SplitterTracker
120355  * @extends Ext.dd.DragTracker
120356  * Private utility class for Ext.Splitter.
120357  * @private
120358  */
120359 Ext.define('Ext.resizer.SplitterTracker', {
120360     extend: 'Ext.dd.DragTracker',
120361     requires: ['Ext.util.Region'],
120362     enabled: true,
120363
120364     getPrevCmp: function() {
120365         var splitter = this.getSplitter();
120366         return splitter.previousSibling();
120367     },
120368
120369     getNextCmp: function() {
120370         var splitter = this.getSplitter();
120371         return splitter.nextSibling();
120372     },
120373
120374     // ensure the tracker is enabled, store boxes of previous and next
120375     // components and calculate the constrain region
120376     onBeforeStart: function(e) {
120377         var prevCmp = this.getPrevCmp(),
120378             nextCmp = this.getNextCmp();
120379
120380         // SplitterTracker is disabled if any of its adjacents are collapsed.
120381         if (nextCmp.collapsed || prevCmp.collapsed) {
120382             return false;
120383         }
120384         // store boxes of previous and next
120385         this.prevBox  = prevCmp.getEl().getBox();
120386         this.nextBox  = nextCmp.getEl().getBox();
120387         this.constrainTo = this.calculateConstrainRegion();
120388     },
120389
120390     // We move the splitter el. Add the proxy class.
120391     onStart: function(e) {
120392         var splitter = this.getSplitter();
120393         splitter.addCls(splitter.baseCls + '-active');
120394     },
120395
120396     // calculate the constrain Region in which the splitter el may be moved.
120397     calculateConstrainRegion: function() {
120398         var splitter   = this.getSplitter(),
120399             topPad     = 0,
120400             bottomPad  = 0,
120401             splitWidth = splitter.getWidth(),
120402             defaultMin = splitter.defaultSplitMin,
120403             orient     = splitter.orientation,
120404             prevBox    = this.prevBox,
120405             prevCmp    = this.getPrevCmp(),
120406             nextBox    = this.nextBox,
120407             nextCmp    = this.getNextCmp(),
120408             // prev and nextConstrainRegions are the maximumBoxes minus the
120409             // minimumBoxes. The result is always the intersection
120410             // of these two boxes.
120411             prevConstrainRegion, nextConstrainRegion;
120412
120413         // vertical splitters, so resizing left to right
120414         if (orient === 'vertical') {
120415
120416             // Region constructor accepts (top, right, bottom, left)
120417             // anchored/calculated from the left
120418             prevConstrainRegion = Ext.create('Ext.util.Region',
120419                 prevBox.y,
120420                 // Right boundary is x + maxWidth if there IS a maxWidth.
120421                 // Otherwise it is calculated based upon the minWidth of the next Component
120422                 (prevCmp.maxWidth ? prevBox.x + prevCmp.maxWidth : nextBox.right - (nextCmp.minWidth || defaultMin)) + splitWidth,
120423                 prevBox.bottom,
120424                 prevBox.x + (prevCmp.minWidth || defaultMin)
120425             );
120426             // anchored/calculated from the right
120427             nextConstrainRegion = Ext.create('Ext.util.Region',
120428                 nextBox.y,
120429                 nextBox.right - (nextCmp.minWidth || defaultMin),
120430                 nextBox.bottom,
120431                 // Left boundary is right - maxWidth if there IS a maxWidth.
120432                 // Otherwise it is calculated based upon the minWidth of the previous Component
120433                 (nextCmp.maxWidth ? nextBox.right - nextCmp.maxWidth : prevBox.x + (prevBox.minWidth || defaultMin)) - splitWidth
120434             );
120435         } else {
120436             // anchored/calculated from the top
120437             prevConstrainRegion = Ext.create('Ext.util.Region',
120438                 prevBox.y + (prevCmp.minHeight || defaultMin),
120439                 prevBox.right,
120440                 // Bottom boundary is y + maxHeight if there IS a maxHeight.
120441                 // Otherwise it is calculated based upon the minWidth of the next Component
120442                 (prevCmp.maxHeight ? prevBox.y + prevCmp.maxHeight : nextBox.bottom - (nextCmp.minHeight || defaultMin)) + splitWidth,
120443                 prevBox.x
120444             );
120445             // anchored/calculated from the bottom
120446             nextConstrainRegion = Ext.create('Ext.util.Region',
120447                 // Top boundary is bottom - maxHeight if there IS a maxHeight.
120448                 // Otherwise it is calculated based upon the minHeight of the previous Component
120449                 (nextCmp.maxHeight ? nextBox.bottom - nextCmp.maxHeight : prevBox.y + (prevCmp.minHeight || defaultMin)) - splitWidth,
120450                 nextBox.right,
120451                 nextBox.bottom - (nextCmp.minHeight || defaultMin),
120452                 nextBox.x
120453             );
120454         }
120455
120456         // intersection of the two regions to provide region draggable
120457         return  prevConstrainRegion.intersect(nextConstrainRegion);
120458     },
120459
120460     // Performs the actual resizing of the previous and next components
120461     performResize: function(e) {
120462         var offset   = this.getOffset('dragTarget'),
120463             splitter = this.getSplitter(),
120464             orient   = splitter.orientation,
120465             prevCmp  = this.getPrevCmp(),
120466             nextCmp  = this.getNextCmp(),
120467             owner    = splitter.ownerCt,
120468             layout   = owner.getLayout();
120469
120470         // Inhibit automatic container layout caused by setSize calls below.
120471         owner.suspendLayout = true;
120472
120473         if (orient === 'vertical') {
120474             if (prevCmp) {
120475                 if (!prevCmp.maintainFlex) {
120476                     delete prevCmp.flex;
120477                     prevCmp.setSize(this.prevBox.width + offset[0], prevCmp.getHeight());
120478                 }
120479             }
120480             if (nextCmp) {
120481                 if (!nextCmp.maintainFlex) {
120482                     delete nextCmp.flex;
120483                     nextCmp.setSize(this.nextBox.width - offset[0], nextCmp.getHeight());
120484                 }
120485             }
120486         // verticals
120487         } else {
120488             if (prevCmp) {
120489                 if (!prevCmp.maintainFlex) {
120490                     delete prevCmp.flex;
120491                     prevCmp.setSize(prevCmp.getWidth(), this.prevBox.height + offset[1]);
120492                 }
120493             }
120494             if (nextCmp) {
120495                 if (!nextCmp.maintainFlex) {
120496                     delete nextCmp.flex;
120497                     nextCmp.setSize(prevCmp.getWidth(), this.nextBox.height - offset[1]);
120498                 }
120499             }
120500         }
120501         delete owner.suspendLayout;
120502         layout.onLayout();
120503     },
120504
120505     // perform the resize and remove the proxy class from the splitter el
120506     onEnd: function(e) {
120507         var splitter = this.getSplitter();
120508         splitter.removeCls(splitter.baseCls + '-active');
120509         this.performResize();
120510     },
120511
120512     // Track the proxy and set the proper XY coordinates
120513     // while constraining the drag
120514     onDrag: function(e) {
120515         var offset    = this.getOffset('dragTarget'),
120516             splitter  = this.getSplitter(),
120517             splitEl   = splitter.getEl(),
120518             orient    = splitter.orientation;
120519
120520         if (orient === "vertical") {
120521             splitEl.setX(this.startRegion.left + offset[0]);
120522         } else {
120523             splitEl.setY(this.startRegion.top + offset[1]);
120524         }
120525     },
120526
120527     getSplitter: function() {
120528         return Ext.getCmp(this.getDragCt().id);
120529     }
120530 });
120531 /**
120532  * @class Ext.selection.CellModel
120533  * @extends Ext.selection.Model
120534  * @private
120535  */
120536 Ext.define('Ext.selection.CellModel', {
120537     extend: 'Ext.selection.Model',
120538     alias: 'selection.cellmodel',
120539     requires: ['Ext.util.KeyNav'],
120540     
120541     /**
120542      * @cfg {Boolean} enableKeyNav
120543      * Turns on/off keyboard navigation within the grid. Defaults to true.
120544      */
120545     enableKeyNav: true,
120546     
120547     /**
120548      * @cfg {Boolean} preventWrap
120549      * Set this configuration to true to prevent wrapping around of selection as
120550      * a user navigates to the first or last column. Defaults to false.
120551      */
120552     preventWrap: false,
120553
120554     constructor: function(){
120555         this.addEvents(
120556             /**
120557              * @event deselect
120558              * Fired after a cell is deselected
120559              * @param {Ext.selection.CellModel} this
120560              * @param {Ext.data.Model} record The record of the deselected cell
120561              * @param {Number} row The row index deselected
120562              * @param {Number} column The column index deselected
120563              */
120564             'deselect',
120565             
120566             /**
120567              * @event select
120568              * Fired after a cell is selected
120569              * @param {Ext.selection.CellModel} this
120570              * @param {Ext.data.Model} record The record of the selected cell
120571              * @param {Number} row The row index selected
120572              * @param {Number} column The column index selected
120573              */
120574             'select'
120575         );
120576         this.callParent(arguments);    
120577     },
120578
120579     bindComponent: function(view) {
120580         var me = this;
120581         me.primaryView = view;
120582         me.views = me.views || [];
120583         me.views.push(view);
120584         me.bind(view.getStore(), true);
120585
120586         view.on({
120587             cellmousedown: me.onMouseDown,
120588             refresh: me.onViewRefresh,
120589             scope: me
120590         });
120591
120592         if (me.enableKeyNav) {
120593             me.initKeyNav(view);
120594         }
120595     },
120596
120597     initKeyNav: function(view) {
120598         var me = this;
120599         
120600         if (!view.rendered) {
120601             view.on('render', Ext.Function.bind(me.initKeyNav, me, [view], 0), me, {single: true});
120602             return;
120603         }
120604
120605         view.el.set({
120606             tabIndex: -1
120607         });
120608
120609         // view.el has tabIndex -1 to allow for
120610         // keyboard events to be passed to it.
120611         me.keyNav = Ext.create('Ext.util.KeyNav', view.el, {
120612             up: me.onKeyUp,
120613             down: me.onKeyDown,
120614             right: me.onKeyRight,
120615             left: me.onKeyLeft,
120616             tab: me.onKeyTab,
120617             scope: me
120618         });
120619     },
120620     
120621     getHeaderCt: function() {
120622         return this.primaryView.headerCt;
120623     },
120624
120625     onKeyUp: function(e, t) {
120626         this.move('up', e);
120627     },
120628
120629     onKeyDown: function(e, t) {
120630         this.move('down', e);
120631     },
120632
120633     onKeyLeft: function(e, t) {
120634         this.move('left', e);
120635     },
120636     
120637     onKeyRight: function(e, t) {
120638         this.move('right', e);
120639     },
120640     
120641     move: function(dir, e) {
120642         var me = this,
120643             pos = me.primaryView.walkCells(me.getCurrentPosition(), dir, e, me.preventWrap);
120644         if (pos) {
120645             me.setCurrentPosition(pos);
120646         }
120647         return pos;
120648     },
120649
120650     /**
120651      * Returns the current position in the format {row: row, column: column}
120652      */
120653     getCurrentPosition: function() {
120654         return this.position;
120655     },
120656     
120657     /**
120658      * Sets the current position
120659      * @param {Object} position The position to set.
120660      */
120661     setCurrentPosition: function(pos) {
120662         var me = this;
120663         
120664         if (me.position) {
120665             me.onCellDeselect(me.position);
120666         }
120667         if (pos) {
120668             me.onCellSelect(pos);
120669         }
120670         me.position = pos;
120671     },
120672
120673     /**
120674      * Set the current position based on where the user clicks.
120675      * @private
120676      */
120677     onMouseDown: function(view, cell, cellIndex, record, row, rowIndex, e) {
120678         this.setCurrentPosition({
120679             row: rowIndex,
120680             column: cellIndex
120681         });
120682     },
120683
120684     // notify the view that the cell has been selected to update the ui
120685     // appropriately and bring the cell into focus
120686     onCellSelect: function(position) {
120687         var me = this,
120688             store = me.view.getStore(),
120689             record = store.getAt(position.row);
120690
120691         me.doSelect(record);
120692         me.primaryView.onCellSelect(position);
120693         // TODO: Remove temporary cellFocus call here.
120694         me.primaryView.onCellFocus(position);
120695         me.fireEvent('select', me, record, position.row, position.column);
120696     },
120697
120698     // notify view that the cell has been deselected to update the ui
120699     // appropriately
120700     onCellDeselect: function(position) {
120701         var me = this,
120702             store = me.view.getStore(),
120703             record = store.getAt(position.row);
120704
120705         me.doDeselect(record);
120706         me.primaryView.onCellDeselect(position);
120707         me.fireEvent('deselect', me, record, position.row, position.column);
120708     },
120709
120710     onKeyTab: function(e, t) {
120711         var me = this,
120712             direction = e.shiftKey ? 'left' : 'right',
120713             editingPlugin = me.view.editingPlugin,
120714             position = me.move(direction, e);
120715
120716         if (editingPlugin && position && me.wasEditing) {
120717             editingPlugin.startEditByPosition(position);
120718         }
120719         delete me.wasEditing;
120720     },
120721
120722     onEditorTab: function(editingPlugin, e) {
120723         var me = this,
120724             direction = e.shiftKey ? 'left' : 'right',
120725             position  = me.move(direction, e);
120726
120727         if (position) {
120728             editingPlugin.startEditByPosition(position);
120729             me.wasEditing = true;
120730         }
120731     },
120732
120733     refresh: function() {
120734         var pos = this.getCurrentPosition();
120735         if (pos) {
120736             this.onCellSelect(pos);
120737         }
120738     },
120739
120740     onViewRefresh: function() {
120741         var pos = this.getCurrentPosition();
120742         if (pos) {
120743             this.onCellDeselect(pos);
120744             this.setCurrentPosition(null);
120745         }
120746     },
120747
120748     selectByPosition: function(position) {
120749         this.setCurrentPosition(position);
120750     }
120751 });
120752 /**
120753  * @class Ext.selection.RowModel
120754  * @extends Ext.selection.Model
120755  * 
120756  * Implement row based navigation via keyboard.
120757  *
120758  * Must synchronize across grid sections
120759  */
120760 Ext.define('Ext.selection.RowModel', {
120761     extend: 'Ext.selection.Model',
120762     alias: 'selection.rowmodel',
120763     requires: ['Ext.util.KeyNav'],
120764     
120765     /**
120766      * @private
120767      * Number of pixels to scroll to the left/right when pressing
120768      * left/right keys.
120769      */
120770     deltaScroll: 5,
120771     
120772     /**
120773      * @cfg {Boolean} enableKeyNav
120774      * 
120775      * Turns on/off keyboard navigation within the grid. Defaults to true.
120776      */
120777     enableKeyNav: true,
120778     
120779     constructor: function(){
120780         this.addEvents(
120781             /**
120782              * @event deselect
120783              * Fired after a record is deselected
120784              * @param {Ext.selection.RowSelectionModel} this
120785              * @param {Ext.data.Model} record The deselected record
120786              * @param {Number} index The row index deselected
120787              */
120788             'deselect',
120789             
120790             /**
120791              * @event select
120792              * Fired after a record is selected
120793              * @param {Ext.selection.RowSelectionModel} this
120794              * @param {Ext.data.Model} record The selected record
120795              * @param {Number} index The row index selected
120796              */
120797             'select'
120798         );
120799         this.callParent(arguments);    
120800     },
120801
120802     bindComponent: function(view) {
120803         var me = this;
120804         
120805         me.views = me.views || [];
120806         me.views.push(view);
120807         me.bind(view.getStore(), true);
120808
120809         view.on({
120810             itemmousedown: me.onRowMouseDown,
120811             scope: me
120812         });
120813
120814         if (me.enableKeyNav) {
120815             me.initKeyNav(view);
120816         }
120817     },
120818
120819     initKeyNav: function(view) {
120820         var me = this;
120821         
120822         if (!view.rendered) {
120823             view.on('render', Ext.Function.bind(me.initKeyNav, me, [view], 0), me, {single: true});
120824             return;
120825         }
120826
120827         view.el.set({
120828             tabIndex: -1
120829         });
120830
120831         // view.el has tabIndex -1 to allow for
120832         // keyboard events to be passed to it.
120833         me.keyNav = new Ext.util.KeyNav(view.el, {
120834             up: me.onKeyUp,
120835             down: me.onKeyDown,
120836             right: me.onKeyRight,
120837             left: me.onKeyLeft,
120838             pageDown: me.onKeyPageDown,
120839             pageUp: me.onKeyPageUp,
120840             home: me.onKeyHome,
120841             end: me.onKeyEnd,
120842             scope: me
120843         });
120844         view.el.on(Ext.EventManager.getKeyEvent(), me.onKeyPress, me);
120845     },
120846
120847     // Returns the number of rows currently visible on the screen or
120848     // false if there were no rows. This assumes that all rows are
120849     // of the same height and the first view is accurate.
120850     getRowsVisible: function() {
120851         var rowsVisible = false,
120852             view = this.views[0],
120853             row = view.getNode(0),
120854             rowHeight, gridViewHeight;
120855
120856         if (row) {
120857             rowHeight = Ext.fly(row).getHeight();
120858             gridViewHeight = view.el.getHeight();
120859             rowsVisible = Math.floor(gridViewHeight / rowHeight);
120860         }
120861
120862         return rowsVisible;
120863     },
120864
120865     // go to last visible record in grid.
120866     onKeyEnd: function(e, t) {
120867         var me = this,
120868             last = me.store.getAt(me.store.getCount() - 1);
120869             
120870         if (last) {
120871             if (e.shiftKey) {
120872                 me.selectRange(last, me.lastFocused || 0);
120873                 me.setLastFocused(last);
120874             } else if (e.ctrlKey) {
120875                 me.setLastFocused(last);
120876             } else {
120877                 me.doSelect(last);
120878             }
120879         }
120880     },
120881
120882     // go to first visible record in grid.
120883     onKeyHome: function(e, t) {
120884         var me = this,
120885             first = me.store.getAt(0);
120886             
120887         if (first) {
120888             if (e.shiftKey) {
120889                 me.selectRange(first, me.lastFocused || 0);
120890                 me.setLastFocused(first);
120891             } else if (e.ctrlKey) {
120892                 me.setLastFocused(first);
120893             } else {
120894                 me.doSelect(first, false);
120895             }
120896         }
120897     },
120898
120899     // Go one page up from the lastFocused record in the grid.
120900     onKeyPageUp: function(e, t) {
120901         var me = this,
120902             rowsVisible = me.getRowsVisible(),
120903             selIdx,
120904             prevIdx,
120905             prevRecord,
120906             currRec;
120907             
120908         if (rowsVisible) {
120909             selIdx = me.lastFocused ? me.store.indexOf(me.lastFocused) : 0;
120910             prevIdx = selIdx - rowsVisible;
120911             if (prevIdx < 0) {
120912                 prevIdx = 0;
120913             }
120914             prevRecord = me.store.getAt(prevIdx);
120915             if (e.shiftKey) {
120916                 currRec = me.store.getAt(selIdx);
120917                 me.selectRange(prevRecord, currRec, e.ctrlKey, 'up');
120918                 me.setLastFocused(prevRecord);
120919             } else if (e.ctrlKey) {
120920                 e.preventDefault();
120921                 me.setLastFocused(prevRecord);
120922             } else {
120923                 me.doSelect(prevRecord);
120924             }
120925
120926         }
120927     },
120928
120929     // Go one page down from the lastFocused record in the grid.
120930     onKeyPageDown: function(e, t) {
120931         var me = this,
120932             rowsVisible = me.getRowsVisible(),
120933             selIdx,
120934             nextIdx,
120935             nextRecord,
120936             currRec;
120937             
120938         if (rowsVisible) {
120939             selIdx = me.lastFocused ? me.store.indexOf(me.lastFocused) : 0;
120940             nextIdx = selIdx + rowsVisible;
120941             if (nextIdx >= me.store.getCount()) {
120942                 nextIdx = me.store.getCount() - 1;
120943             }
120944             nextRecord = me.store.getAt(nextIdx);
120945             if (e.shiftKey) {
120946                 currRec = me.store.getAt(selIdx);
120947                 me.selectRange(nextRecord, currRec, e.ctrlKey, 'down');
120948                 me.setLastFocused(nextRecord);
120949             } else if (e.ctrlKey) {
120950                 // some browsers, this means go thru browser tabs
120951                 // attempt to stop.
120952                 e.preventDefault();
120953                 me.setLastFocused(nextRecord);
120954             } else {
120955                 me.doSelect(nextRecord);
120956             }
120957         }
120958     },
120959
120960     // Select/Deselect based on pressing Spacebar.
120961     // Assumes a SIMPLE selectionmode style
120962     onKeyPress: function(e, t) {
120963         if (e.getKey() === e.SPACE) {
120964             e.stopEvent();
120965             var me = this,
120966                 record = me.lastFocused;
120967                 
120968             if (record) {
120969                 if (me.isSelected(record)) {
120970                     me.doDeselect(record, false);
120971                 } else {
120972                     me.doSelect(record, true);
120973                 }
120974             }
120975         }
120976     },
120977
120978     // Navigate one record up. This could be a selection or
120979     // could be simply focusing a record for discontiguous
120980     // selection. Provides bounds checking.
120981     onKeyUp: function(e, t) {
120982         var me = this,
120983             view = me.views[0],
120984             idx  = me.store.indexOf(me.lastFocused),
120985             record;
120986             
120987         if (idx > 0) {
120988             // needs to be the filtered count as thats what
120989             // will be visible.
120990             record = me.store.getAt(idx - 1);
120991             if (e.shiftKey && me.lastFocused) {
120992                 if (me.isSelected(me.lastFocused) && me.isSelected(record)) {
120993                     me.doDeselect(me.lastFocused, true);
120994                     me.setLastFocused(record);
120995                 } else if (!me.isSelected(me.lastFocused)) {
120996                     me.doSelect(me.lastFocused, true);
120997                     me.doSelect(record, true);
120998                 } else {
120999                     me.doSelect(record, true);
121000                 }
121001             } else if (e.ctrlKey) {
121002                 me.setLastFocused(record);
121003             } else {
121004                 me.doSelect(record);
121005                 //view.focusRow(idx - 1);
121006             }
121007         }
121008         // There was no lastFocused record, and the user has pressed up
121009         // Ignore??
121010         //else if (this.selected.getCount() == 0) {
121011         //    
121012         //    this.doSelect(record);
121013         //    //view.focusRow(idx - 1);
121014         //}
121015     },
121016
121017     // Navigate one record down. This could be a selection or
121018     // could be simply focusing a record for discontiguous
121019     // selection. Provides bounds checking.
121020     onKeyDown: function(e, t) {
121021         var me = this,
121022             view = me.views[0],
121023             idx  = me.store.indexOf(me.lastFocused),
121024             record;
121025             
121026         // needs to be the filtered count as thats what
121027         // will be visible.
121028         if (idx + 1 < me.store.getCount()) {
121029             record = me.store.getAt(idx + 1);
121030             if (me.selected.getCount() === 0) {
121031                 me.doSelect(record);
121032                 //view.focusRow(idx + 1);
121033             } else if (e.shiftKey && me.lastFocused) {
121034                 if (me.isSelected(me.lastFocused) && me.isSelected(record)) {
121035                     me.doDeselect(me.lastFocused, true);
121036                     me.setLastFocused(record);
121037                 } else if (!me.isSelected(me.lastFocused)) {
121038                     me.doSelect(me.lastFocused, true);
121039                     me.doSelect(record, true);
121040                 } else {
121041                     me.doSelect(record, true);
121042                 }
121043             } else if (e.ctrlKey) {
121044                 me.setLastFocused(record);
121045             } else {
121046                 me.doSelect(record);
121047                 //view.focusRow(idx + 1);
121048             }
121049         }
121050     },
121051     
121052     scrollByDeltaX: function(delta) {
121053         var view    = this.views[0],
121054             section = view.up(),
121055             hScroll = section.horizontalScroller;
121056             
121057         if (hScroll) {
121058             hScroll.scrollByDeltaX(delta);
121059         }
121060     },
121061     
121062     onKeyLeft: function(e, t) {
121063         this.scrollByDeltaX(-this.deltaScroll);
121064     },
121065     
121066     onKeyRight: function(e, t) {
121067         this.scrollByDeltaX(this.deltaScroll);
121068     },
121069
121070     // Select the record with the event included so that
121071     // we can take into account ctrlKey, shiftKey, etc
121072     onRowMouseDown: function(view, record, item, index, e) {
121073         view.el.focus();
121074         this.selectWithEvent(record, e);
121075     },
121076
121077     // Allow the GridView to update the UI by
121078     // adding/removing a CSS class from the row.
121079     onSelectChange: function(record, isSelected, suppressEvent) {
121080         var me      = this,
121081             views   = me.views,
121082             viewsLn = views.length,
121083             store   = me.store,
121084             rowIdx  = store.indexOf(record),
121085             i = 0;
121086             
121087         for (; i < viewsLn; i++) {
121088             if (isSelected) {
121089                 views[i].onRowSelect(rowIdx, suppressEvent);
121090                 if (!suppressEvent) {
121091                     me.fireEvent('select', me, record, rowIdx);
121092                 }
121093             } else {
121094                 views[i].onRowDeselect(rowIdx, suppressEvent);
121095                 if (!suppressEvent) {
121096                     me.fireEvent('deselect', me, record, rowIdx);
121097                 }
121098             }
121099         }
121100     },
121101
121102     // Provide indication of what row was last focused via
121103     // the gridview.
121104     onLastFocusChanged: function(oldFocused, newFocused, supressFocus) {
121105         var views   = this.views,
121106             viewsLn = views.length,
121107             store   = this.store,
121108             rowIdx,
121109             i = 0;
121110             
121111         if (oldFocused) {
121112             rowIdx = store.indexOf(oldFocused);
121113             if (rowIdx != -1) {
121114                 for (; i < viewsLn; i++) {
121115                     views[i].onRowFocus(rowIdx, false);
121116                 }
121117             }
121118         }
121119
121120         if (newFocused) {
121121             rowIdx = store.indexOf(newFocused);
121122             if (rowIdx != -1) {
121123                 for (i = 0; i < viewsLn; i++) {
121124                     views[i].onRowFocus(rowIdx, true, supressFocus);
121125                 }
121126             }
121127         }
121128     },
121129     
121130     onEditorTab: function(editingPlugin, e) {
121131         var me = this,
121132             view = me.views[0],
121133             record = editingPlugin.getActiveRecord(),
121134             header = editingPlugin.getActiveColumn(),
121135             position = view.getPosition(record, header),
121136             direction = e.shiftKey ? 'left' : 'right',
121137             newPosition  = view.walkCells(position, direction, e, this.preventWrap);
121138             
121139         if (newPosition) {
121140             editingPlugin.startEditByPosition(newPosition);
121141         }
121142     },
121143     
121144     selectByPosition: function(position) {
121145         var record = this.store.getAt(position.row);
121146         this.select(record);
121147     }
121148 });
121149 /**
121150  * @class Ext.selection.CheckboxModel
121151  * @extends Ext.selection.RowModel
121152  *
121153  * A selection model that renders a column of checkboxes that can be toggled to
121154  * select or deselect rows. The default mode for this selection model is MULTI.
121155  *
121156  * The selection model will inject a header for the checkboxes in the first view
121157  * and according to the 'injectCheckbox' configuration.
121158  */
121159 Ext.define('Ext.selection.CheckboxModel', {
121160     extend: 'Ext.selection.RowModel',
121161
121162     /**
121163      * @cfg {String} mode
121164      * Modes of selection.
121165      * Valid values are SINGLE, SIMPLE, and MULTI. Defaults to 'MULTI'
121166      */
121167     mode: 'MULTI',
121168
121169     /**
121170      * @cfg {Mixed} injectCheckbox
121171      * Instructs the SelectionModel whether or not to inject the checkbox header
121172      * automatically or not. (Note: By not placing the checkbox in manually, the
121173      * grid view will need to be rendered 2x on initial render.)
121174      * Supported values are a Number index, false and the strings 'first' and 'last'.
121175      * Default is 0.
121176      */
121177     injectCheckbox: 0,
121178
121179     /**
121180      * @cfg {Boolean} checkOnly <tt>true</tt> if rows can only be selected by clicking on the
121181      * checkbox column (defaults to <tt>false</tt>).
121182      */
121183     checkOnly: false,
121184
121185     // private
121186     checkerOnCls: Ext.baseCSSPrefix + 'grid-hd-checker-on',
121187
121188     bindComponent: function() {
121189         this.sortable = false;
121190         this.callParent(arguments);
121191
121192         var view     = this.views[0],
121193             headerCt = view.headerCt;
121194
121195         if (this.injectCheckbox !== false) {
121196             if (this.injectCheckbox == 'first') {
121197                 this.injectCheckbox = 0;
121198             } else if (this.injectCheckbox == 'last') {
121199                 this.injectCheckbox = headerCt.getColumnCount();
121200             }
121201             headerCt.add(this.injectCheckbox,  this.getHeaderConfig());
121202         }
121203         headerCt.on('headerclick', this.onHeaderClick, this);
121204     },
121205
121206     /**
121207      * Toggle the ui header between checked and unchecked state.
121208      * @param {Boolean} isChecked
121209      * @private
121210      */
121211     toggleUiHeader: function(isChecked) {
121212         var view     = this.views[0],
121213             headerCt = view.headerCt,
121214             checkHd  = headerCt.child('gridcolumn[isCheckerHd]');
121215
121216         if (checkHd) {
121217             if (isChecked) {
121218                 checkHd.el.addCls(this.checkerOnCls);
121219             } else {
121220                 checkHd.el.removeCls(this.checkerOnCls);
121221             }
121222         }
121223     },
121224
121225     /**
121226      * Toggle between selecting all and deselecting all when clicking on
121227      * a checkbox header.
121228      */
121229     onHeaderClick: function(headerCt, header, e) {
121230         if (header.isCheckerHd) {
121231             e.stopEvent();
121232             var isChecked = header.el.hasCls(Ext.baseCSSPrefix + 'grid-hd-checker-on');
121233             if (isChecked) {
121234                 // We have to supress the event or it will scrollTo the change
121235                 this.deselectAll(true);
121236             } else {
121237                 // We have to supress the event or it will scrollTo the change
121238                 this.selectAll(true);
121239             }
121240         }
121241     },
121242
121243     /**
121244      * Retrieve a configuration to be used in a HeaderContainer.
121245      * This should be used when injectCheckbox is set to false.
121246      */
121247     getHeaderConfig: function() {
121248         return {
121249             isCheckerHd: true,
121250             text : '&#160;',
121251             width: 24,
121252             sortable: false,
121253             fixed: true,
121254             hideable: false,
121255             menuDisabled: true,
121256             dataIndex: '',
121257             cls: Ext.baseCSSPrefix + 'column-header-checkbox ',
121258             renderer: Ext.Function.bind(this.renderer, this)
121259         };
121260     },
121261
121262     /**
121263      * Generates the HTML to be rendered in the injected checkbox column for each row.
121264      * Creates the standard checkbox markup by default; can be overridden to provide custom rendering.
121265      * See {@link Ext.grid.column.Column#renderer} for description of allowed parameters.
121266      */
121267     renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
121268         metaData.tdCls = Ext.baseCSSPrefix + 'grid-cell-special';
121269         return '<div class="' + Ext.baseCSSPrefix + 'grid-row-checker">&#160;</div>';
121270     },
121271
121272     // override
121273     onRowMouseDown: function(view, record, item, index, e) {
121274         view.el.focus();
121275         var me = this,
121276             checker = e.getTarget('.' + Ext.baseCSSPrefix + 'grid-row-checker');
121277
121278         // checkOnly set, but we didn't click on a checker.
121279         if (me.checkOnly && !checker) {
121280             return;
121281         }
121282
121283         if (checker) {
121284             var mode = me.getSelectionMode();
121285             // dont change the mode if its single otherwise
121286             // we would get multiple selection
121287             if (mode !== 'SINGLE') {
121288                 me.setSelectionMode('SIMPLE');
121289             }
121290             me.selectWithEvent(record, e);
121291             me.setSelectionMode(mode);
121292         } else {
121293             me.selectWithEvent(record, e);
121294         }
121295     },
121296
121297     /**
121298      * Synchronize header checker value as selection changes.
121299      * @private
121300      */
121301     onSelectChange: function(record, isSelected) {
121302         this.callParent([record, isSelected]);
121303         // check to see if all records are selected
121304         var hdSelectStatus = this.selected.getCount() === this.store.getCount();
121305         this.toggleUiHeader(hdSelectStatus);
121306     }
121307 });
121308
121309 /**
121310  * @class Ext.selection.TreeModel
121311  * @extends Ext.selection.RowModel
121312  *
121313  * Adds custom behavior for left/right keyboard navigation for use with a tree.
121314  * Depends on the view having an expand and collapse method which accepts a
121315  * record.
121316  * 
121317  * @private
121318  */
121319 Ext.define('Ext.selection.TreeModel', {
121320     extend: 'Ext.selection.RowModel',
121321     alias: 'selection.treemodel',
121322     
121323     // typically selection models prune records from the selection
121324     // model when they are removed, because the TreeView constantly
121325     // adds/removes records as they are expanded/collapsed
121326     pruneRemoved: false,
121327     
121328     onKeyRight: function(e, t) {
121329         var focused = this.getLastFocused(),
121330             view    = this.view;
121331             
121332         if (focused) {
121333             // tree node is already expanded, go down instead
121334             // this handles both the case where we navigate to firstChild and if
121335             // there are no children to the nextSibling
121336             if (focused.isExpanded()) {
121337                 this.onKeyDown(e, t);
121338             // if its not a leaf node, expand it
121339             } else if (!focused.isLeaf()) {
121340                 view.expand(focused);
121341             }
121342         }
121343     },
121344     
121345     onKeyLeft: function(e, t) {
121346         var focused = this.getLastFocused(),
121347             view    = this.view,
121348             viewSm  = view.getSelectionModel(),
121349             parentNode, parentRecord;
121350
121351         if (focused) {
121352             parentNode = focused.parentNode;
121353             // if focused node is already expanded, collapse it
121354             if (focused.isExpanded()) {
121355                 view.collapse(focused);
121356             // has a parentNode and its not root
121357             // TODO: this needs to cover the case where the root isVisible
121358             } else if (parentNode && !parentNode.isRoot()) {
121359                 // Select a range of records when doing multiple selection.
121360                 if (e.shiftKey) {
121361                     viewSm.selectRange(parentNode, focused, e.ctrlKey, 'up');
121362                     viewSm.setLastFocused(parentNode);
121363                 // just move focus, not selection
121364                 } else if (e.ctrlKey) {
121365                     viewSm.setLastFocused(parentNode);
121366                 // select it
121367                 } else {
121368                     viewSm.select(parentNode);
121369                 }
121370             }
121371         }
121372     },
121373     
121374     onKeyPress: function(e, t) {
121375         var selected, checked;
121376         
121377         if (e.getKey() === e.SPACE || e.getKey() === e.ENTER) {
121378             e.stopEvent();
121379             selected = this.getLastSelected();
121380             if (selected && selected.isLeaf()) {
121381                 checked = selected.get('checked');
121382                 if (Ext.isBoolean(checked)) {
121383                     selected.set('checked', !checked);
121384                 }
121385             }
121386         } else {
121387             this.callParent(arguments);
121388         }
121389     }
121390 });
121391
121392 /**
121393  * @private
121394  * @class Ext.slider.Thumb
121395  * @extends Ext.Base
121396  * @private
121397  * Represents a single thumb element on a Slider. This would not usually be created manually and would instead
121398  * be created internally by an {@link Ext.slider.Multi Ext.Slider}.
121399  */
121400 Ext.define('Ext.slider.Thumb', {
121401     requires: ['Ext.dd.DragTracker', 'Ext.util.Format'],
121402     /**
121403      * @private
121404      * @property topThumbZIndex
121405      * @type Number
121406      * The number used internally to set the z index of the top thumb (see promoteThumb for details)
121407      */
121408     topZIndex: 10000,
121409     /**
121410      * @constructor
121411      * @cfg {Ext.slider.MultiSlider} slider The Slider to render to (required)
121412      */
121413     constructor: function(config) {
121414         var me = this;
121415         
121416         /**
121417          * @property slider
121418          * @type Ext.slider.MultiSlider
121419          * The slider this thumb is contained within
121420          */
121421         Ext.apply(me, config || {}, {
121422             cls: Ext.baseCSSPrefix + 'slider-thumb',
121423
121424             /**
121425              * @cfg {Boolean} constrain True to constrain the thumb so that it cannot overlap its siblings
121426              */
121427             constrain: false
121428         });
121429         me.callParent([config]);
121430
121431         if (me.slider.vertical) {
121432             Ext.apply(me, Ext.slider.Thumb.Vertical);
121433         }
121434     },
121435
121436     /**
121437      * Renders the thumb into a slider
121438      */
121439     render: function() {
121440         var me = this;
121441         
121442         me.el = me.slider.innerEl.insertFirst({cls: me.cls});
121443         if (me.disabled) {
121444             me.disable();
121445         }
121446         me.initEvents();
121447     },
121448     
121449     /**
121450      * @private
121451      * move the thumb
121452      */
121453     move: function(v, animate){
121454         if(!animate){
121455             this.el.setLeft(v);
121456         }else{
121457             Ext.create('Ext.fx.Anim', {
121458                 target: this.el,
121459                 duration: 350,
121460                 to: {
121461                     left: v
121462                 }
121463             });
121464         }
121465     },
121466
121467     /**
121468      * @private
121469      * Bring thumb dom element to front.
121470      */
121471     bringToFront: function() {
121472         this.el.setStyle('zIndex', this.topZIndex);
121473     },
121474     
121475     /**
121476      * @private
121477      * Send thumb dom element to back.
121478      */
121479     sendToBack: function() {
121480         this.el.setStyle('zIndex', '');
121481     },
121482     
121483     /**
121484      * Enables the thumb if it is currently disabled
121485      */
121486     enable: function() {
121487         var me = this;
121488         
121489         me.disabled = false;
121490         if (me.el) {
121491             me.el.removeCls(me.slider.disabledCls);
121492         }
121493     },
121494
121495     /**
121496      * Disables the thumb if it is currently enabled
121497      */
121498     disable: function() {
121499         var me = this;
121500         
121501         me.disabled = true;
121502         if (me.el) {
121503             me.el.addCls(me.slider.disabledCls);
121504         }
121505     },
121506
121507     /**
121508      * Sets up an Ext.dd.DragTracker for this thumb
121509      */
121510     initEvents: function() {
121511         var me = this,
121512             el = me.el;
121513
121514         me.tracker = Ext.create('Ext.dd.DragTracker', {
121515             onBeforeStart: Ext.Function.bind(me.onBeforeDragStart, me),
121516             onStart      : Ext.Function.bind(me.onDragStart, me),
121517             onDrag       : Ext.Function.bind(me.onDrag, me),
121518             onEnd        : Ext.Function.bind(me.onDragEnd, me),
121519             tolerance    : 3,
121520             autoStart    : 300,
121521             overCls      : Ext.baseCSSPrefix + 'slider-thumb-over'
121522         });
121523
121524         me.tracker.initEl(el);
121525     },
121526
121527     /**
121528      * @private
121529      * This is tied into the internal Ext.dd.DragTracker. If the slider is currently disabled,
121530      * this returns false to disable the DragTracker too.
121531      * @return {Boolean} False if the slider is currently disabled
121532      */
121533     onBeforeDragStart : function(e) {
121534         if (this.disabled) {
121535             return false;
121536         } else {
121537             this.slider.promoteThumb(this);
121538             return true;
121539         }
121540     },
121541
121542     /**
121543      * @private
121544      * This is tied into the internal Ext.dd.DragTracker's onStart template method. Adds the drag CSS class
121545      * to the thumb and fires the 'dragstart' event
121546      */
121547     onDragStart: function(e){
121548         var me = this;
121549         
121550         me.el.addCls(Ext.baseCSSPrefix + 'slider-thumb-drag');
121551         me.dragging = true;
121552         me.dragStartValue = me.value;
121553
121554         me.slider.fireEvent('dragstart', me.slider, e, me);
121555     },
121556
121557     /**
121558      * @private
121559      * This is tied into the internal Ext.dd.DragTracker's onDrag template method. This is called every time
121560      * the DragTracker detects a drag movement. It updates the Slider's value using the position of the drag
121561      */
121562     onDrag: function(e) {
121563         var me       = this,
121564             slider   = me.slider,
121565             index    = me.index,
121566             newValue = me.getNewValue(),
121567             above,
121568             below;
121569
121570         if (me.constrain) {
121571             above = slider.thumbs[index + 1];
121572             below = slider.thumbs[index - 1];
121573
121574             if (below !== undefined && newValue <= below.value) {
121575                 newValue = below.value;
121576             }
121577             
121578             if (above !== undefined && newValue >= above.value) {
121579                 newValue = above.value;
121580             }
121581         }
121582
121583         slider.setValue(index, newValue, false);
121584         slider.fireEvent('drag', slider, e, me);
121585     },
121586
121587     getNewValue: function() {
121588         var slider = this.slider,
121589             pos = slider.innerEl.translatePoints(this.tracker.getXY());
121590
121591         return Ext.util.Format.round(slider.reverseValue(pos.left), slider.decimalPrecision);
121592     },
121593
121594     /**
121595      * @private
121596      * This is tied to the internal Ext.dd.DragTracker's onEnd template method. Removes the drag CSS class and
121597      * fires the 'changecomplete' event with the new value
121598      */
121599     onDragEnd: function(e) {
121600         var me     = this,
121601             slider = me.slider,
121602             value  = me.value;
121603
121604         me.el.removeCls(Ext.baseCSSPrefix + 'slider-thumb-drag');
121605
121606         me.dragging = false;
121607         slider.fireEvent('dragend', slider, e);
121608
121609         if (me.dragStartValue != value) {
121610             slider.fireEvent('changecomplete', slider, value, me);
121611         }
121612     },
121613
121614     destroy: function() {
121615         Ext.destroy(this.tracker);
121616     },
121617     statics: {
121618         // Method overrides to support vertical dragging of thumb within slider
121619         Vertical: {
121620             getNewValue: function() {
121621                 var slider   = this.slider,
121622                     innerEl  = slider.innerEl,
121623                     pos      = innerEl.translatePoints(this.tracker.getXY()),
121624                     bottom   = innerEl.getHeight() - pos.top;
121625
121626                 return Ext.util.Format.round(slider.reverseValue(bottom), slider.decimalPrecision);
121627             },
121628             move: function(v, animate) {
121629                 if (!animate) {
121630                     this.el.setBottom(v);
121631                 } else {
121632                     Ext.create('Ext.fx.Anim', {
121633                         target: this.el,
121634                         duration: 350,
121635                         to: {
121636                             bottom: v
121637                         }
121638                     });
121639                 }
121640             }
121641         }
121642     }
121643 });
121644
121645 /**
121646  * @class Ext.slider.Tip
121647  * @extends Ext.tip.Tip
121648  * Simple plugin for using an Ext.tip.Tip with a slider to show the slider value. In general this
121649  * class is not created directly, instead pass the {@link Ext.slider.Multi#useTips} and 
121650  * {@link Ext.slider.Multi#tipText} configuration options to the slider directly.
121651  * {@img Ext.slider.Tip/Ext.slider.Tip1.png Ext.slider.Tip component}
121652  * Example usage:
121653 <pre>
121654     Ext.create('Ext.slider.Single', {
121655         width: 214,
121656         minValue: 0,
121657         maxValue: 100,
121658         useTips: true,
121659         renderTo: Ext.getBody()
121660     });   
121661 </pre>
121662  * Optionally provide your own tip text by passing tipText:
121663  <pre>
121664  new Ext.slider.Single({
121665      width: 214,
121666      minValue: 0,
121667      maxValue: 100,
121668      useTips: true,
121669      tipText: function(thumb){
121670          return Ext.String.format('<b>{0}% complete</b>', thumb.value);
121671      }
121672  });
121673  </pre>
121674  * @xtype slidertip
121675  */
121676 Ext.define('Ext.slider.Tip', {
121677     extend: 'Ext.tip.Tip',
121678     minWidth: 10,
121679     alias: 'widget.slidertip',
121680     offsets : [0, -10],
121681     
121682     isSliderTip: true,
121683
121684     init: function(slider) {
121685         var me = this;
121686         
121687         slider.on({
121688             scope    : me,
121689             dragstart: me.onSlide,
121690             drag     : me.onSlide,
121691             dragend  : me.hide,
121692             destroy  : me.destroy
121693         });
121694     },
121695     /**
121696      * @private
121697      * Called whenever a dragstart or drag event is received on the associated Thumb. 
121698      * Aligns the Tip with the Thumb's new position.
121699      * @param {Ext.slider.MultiSlider} slider The slider
121700      * @param {Ext.EventObject} e The Event object
121701      * @param {Ext.slider.Thumb} thumb The thumb that the Tip is attached to
121702      */
121703     onSlide : function(slider, e, thumb) {
121704         var me = this;
121705         me.show();
121706         me.update(me.getText(thumb));
121707         me.doComponentLayout();
121708         me.el.alignTo(thumb.el, 'b-t?', me.offsets);
121709     },
121710
121711     /**
121712      * Used to create the text that appears in the Tip's body. By default this just returns
121713      * the value of the Slider Thumb that the Tip is attached to. Override to customize.
121714      * @param {Ext.slider.Thumb} thumb The Thumb that the Tip is attached to
121715      * @return {String} The text to display in the tip
121716      */
121717     getText : function(thumb) {
121718         return String(thumb.value);
121719     }
121720 });
121721 /**
121722  * @class Ext.slider.Multi
121723  * @extends Ext.form.field.Base
121724  * <p>Slider which supports vertical or horizontal orientation, keyboard adjustments, configurable snapping, axis
121725  * clicking and animation. Can be added as an item to any container. In addition,  
121726  * {@img Ext.slider.Multi/Ext.slider.Multi.png Ext.slider.Multi component}
121727  * <p>Example usage:</p>
121728  * Sliders can be created with more than one thumb handle by passing an array of values instead of a single one:
121729 <pre>
121730     Ext.create('Ext.slider.Multi', {
121731         width: 200,
121732         values: [25, 50, 75],
121733         increment: 5,
121734         minValue: 0,
121735         maxValue: 100,
121736
121737         //this defaults to true, setting to false allows the thumbs to pass each other
121738         {@link #constrainThumbs}: false,
121739         renderTo: Ext.getBody()
121740     });  
121741 </pre>
121742  * @xtype multislider
121743  */
121744 Ext.define('Ext.slider.Multi', {
121745     extend: 'Ext.form.field.Base',
121746     alias: 'widget.multislider',
121747     alternateClassName: 'Ext.slider.MultiSlider',
121748
121749     requires: [
121750         'Ext.slider.Thumb',
121751         'Ext.slider.Tip',
121752         'Ext.Number',
121753         'Ext.util.Format',
121754         'Ext.Template',
121755         'Ext.layout.component.field.Slider'
121756     ],
121757
121758     fieldSubTpl: [
121759         '<div class="' + Ext.baseCSSPrefix + 'slider {fieldCls} {vertical}" aria-valuemin="{minValue}" aria-valuemax="{maxValue}" aria-valuenow="{value}" aria-valuetext="{value}">',
121760             '<div class="' + Ext.baseCSSPrefix + 'slider-end" role="presentation">',
121761                 '<div class="' + Ext.baseCSSPrefix + 'slider-inner" role="presentation">',
121762                     '<a class="' + Ext.baseCSSPrefix + 'slider-focus" href="#" tabIndex="-1" hidefocus="on" role="presentation"></a>',
121763                 '</div>',
121764             '</div>',
121765         '</div>',
121766         {
121767             disableFormats: true,
121768             compiled: true
121769         }
121770     ],
121771
121772     /**
121773      * @cfg {Number} value
121774      * A value with which to initialize the slider. Defaults to minValue. Setting this will only
121775      * result in the creation of a single slider thumb; if you want multiple thumbs then use the
121776      * {@link #values} config instead.
121777      */
121778
121779     /**
121780      * @cfg {Array} values
121781      * Array of Number values with which to initalize the slider. A separate slider thumb will be created for
121782      * each value in this array. This will take precedence over the single {@link #value} config.
121783      */
121784
121785     /**
121786      * @cfg {Boolean} vertical Orient the Slider vertically rather than horizontally, defaults to false.
121787      */
121788     vertical: false,
121789     /**
121790      * @cfg {Number} minValue The minimum value for the Slider. Defaults to 0.
121791      */
121792     minValue: 0,
121793     /**
121794      * @cfg {Number} maxValue The maximum value for the Slider. Defaults to 100.
121795      */
121796     maxValue: 100,
121797     /**
121798      * @cfg {Number/Boolean} decimalPrecision.
121799      * <p>The number of decimal places to which to round the Slider's value. Defaults to 0.</p>
121800      * <p>To disable rounding, configure as <tt><b>false</b></tt>.</p>
121801      */
121802     decimalPrecision: 0,
121803     /**
121804      * @cfg {Number} keyIncrement How many units to change the Slider when adjusting with keyboard navigation. Defaults to 1. If the increment config is larger, it will be used instead.
121805      */
121806     keyIncrement: 1,
121807     /**
121808      * @cfg {Number} increment How many units to change the slider when adjusting by drag and drop. Use this option to enable 'snapping'.
121809      */
121810     increment: 0,
121811
121812     /**
121813      * @private
121814      * @property clickRange
121815      * @type Array
121816      * Determines whether or not a click to the slider component is considered to be a user request to change the value. Specified as an array of [top, bottom],
121817      * the click event's 'top' property is compared to these numbers and the click only considered a change request if it falls within them. e.g. if the 'top'
121818      * value of the click event is 4 or 16, the click is not considered a change request as it falls outside of the [5, 15] range
121819      */
121820     clickRange: [5,15],
121821
121822     /**
121823      * @cfg {Boolean} clickToChange Determines whether or not clicking on the Slider axis will change the slider. Defaults to true
121824      */
121825     clickToChange : true,
121826     /**
121827      * @cfg {Boolean} animate Turn on or off animation. Defaults to true
121828      */
121829     animate: true,
121830
121831     /**
121832      * True while the thumb is in a drag operation
121833      * @type Boolean
121834      */
121835     dragging: false,
121836
121837     /**
121838      * @cfg {Boolean} constrainThumbs True to disallow thumbs from overlapping one another. Defaults to true
121839      */
121840     constrainThumbs: true,
121841
121842     componentLayout: 'sliderfield',
121843
121844     /**
121845      * @cfg {Boolean} useTips
121846      * True to use an Ext.slider.Tip to display tips for the value. Defaults to <tt>true</tt>.
121847      */
121848     useTips : true,
121849
121850     /**
121851      * @cfg {Function} tipText
121852      * A function used to display custom text for the slider tip. Defaults to <tt>null</tt>, which will
121853      * use the default on the plugin.
121854      */
121855     tipText : null,
121856
121857     ariaRole: 'slider',
121858
121859     // private override
121860     initValue: function() {
121861         var me = this,
121862             extValue = Ext.value,
121863             // Fallback for initial values: values config -> value config -> minValue config -> 0
121864             values = extValue(me.values, [extValue(me.value, extValue(me.minValue, 0))]),
121865             i = 0,
121866             len = values.length;
121867
121868         // Store for use in dirty check
121869         me.originalValue = values;
121870
121871         // Add a thumb for each value
121872         for (; i < len; i++) {
121873             me.addThumb(values[i]);
121874         }
121875     },
121876
121877     // private override
121878     initComponent : function() {
121879         var me = this,
121880             tipPlug,
121881             hasTip;
121882         
121883         /**
121884          * @property thumbs
121885          * @type Array
121886          * Array containing references to each thumb
121887          */
121888         me.thumbs = [];
121889
121890         me.keyIncrement = Math.max(me.increment, me.keyIncrement);
121891
121892         me.addEvents(
121893             /**
121894              * @event beforechange
121895              * Fires before the slider value is changed. By returning false from an event handler,
121896              * you can cancel the event and prevent the slider from changing.
121897              * @param {Ext.slider.Multi} slider The slider
121898              * @param {Number} newValue The new value which the slider is being changed to.
121899              * @param {Number} oldValue The old value which the slider was previously.
121900              */
121901             'beforechange',
121902
121903             /**
121904              * @event change
121905              * Fires when the slider value is changed.
121906              * @param {Ext.slider.Multi} slider The slider
121907              * @param {Number} newValue The new value which the slider has been changed to.
121908              * @param {Ext.slider.Thumb} thumb The thumb that was changed
121909              */
121910             'change',
121911
121912             /**
121913              * @event changecomplete
121914              * Fires when the slider value is changed by the user and any drag operations have completed.
121915              * @param {Ext.slider.Multi} slider The slider
121916              * @param {Number} newValue The new value which the slider has been changed to.
121917              * @param {Ext.slider.Thumb} thumb The thumb that was changed
121918              */
121919             'changecomplete',
121920
121921             /**
121922              * @event dragstart
121923              * Fires after a drag operation has started.
121924              * @param {Ext.slider.Multi} slider The slider
121925              * @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
121926              */
121927             'dragstart',
121928
121929             /**
121930              * @event drag
121931              * Fires continuously during the drag operation while the mouse is moving.
121932              * @param {Ext.slider.Multi} slider The slider
121933              * @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
121934              */
121935             'drag',
121936
121937             /**
121938              * @event dragend
121939              * Fires after the drag operation has completed.
121940              * @param {Ext.slider.Multi} slider The slider
121941              * @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
121942              */
121943             'dragend'
121944         );
121945
121946         if (me.vertical) {
121947             Ext.apply(me, Ext.slider.Multi.Vertical);
121948         }
121949
121950         me.callParent();
121951
121952         // only can use it if it exists.
121953         if (me.useTips) {
121954             tipPlug = me.tipText ? {getText: me.tipText} : {};
121955             me.plugins = me.plugins || [];
121956             Ext.each(me.plugins, function(plug){
121957                 if (plug.isSliderTip) {
121958                     hasTip = true;
121959                     return false;
121960                 }
121961             });
121962             if (!hasTip) {
121963                 me.plugins.push(Ext.create('Ext.slider.Tip', tipPlug));
121964             }
121965         }
121966     },
121967
121968     /**
121969      * Creates a new thumb and adds it to the slider
121970      * @param {Number} value The initial value to set on the thumb. Defaults to 0
121971      * @return {Ext.slider.Thumb} The thumb
121972      */
121973     addThumb: function(value) {
121974         var me = this,
121975             thumb = Ext.create('Ext.slider.Thumb', {
121976             value    : value,
121977             slider   : me,
121978             index    : me.thumbs.length,
121979             constrain: me.constrainThumbs
121980         });
121981         me.thumbs.push(thumb);
121982
121983         //render the thumb now if needed
121984         if (me.rendered) {
121985             thumb.render();
121986         }
121987
121988         return thumb;
121989     },
121990
121991     /**
121992      * @private
121993      * Moves the given thumb above all other by increasing its z-index. This is called when as drag
121994      * any thumb, so that the thumb that was just dragged is always at the highest z-index. This is
121995      * required when the thumbs are stacked on top of each other at one of the ends of the slider's
121996      * range, which can result in the user not being able to move any of them.
121997      * @param {Ext.slider.Thumb} topThumb The thumb to move to the top
121998      */
121999     promoteThumb: function(topThumb) {
122000         var thumbs = this.thumbs,
122001             ln = thumbs.length,
122002             zIndex, thumb, i;
122003             
122004         for (i = 0; i < ln; i++) {
122005             thumb = thumbs[i];
122006
122007             if (thumb == topThumb) {
122008                 thumb.bringToFront();
122009             } else {
122010                 thumb.sendToBack();
122011             }
122012         }
122013     },
122014
122015     // private override
122016     onRender : function() {
122017         var me = this,
122018             i = 0,
122019             thumbs = me.thumbs,
122020             len = thumbs.length,
122021             thumb;
122022
122023         Ext.applyIf(me.subTplData, {
122024             vertical: me.vertical ? Ext.baseCSSPrefix + 'slider-vert' : Ext.baseCSSPrefix + 'slider-horz',
122025             minValue: me.minValue,
122026             maxValue: me.maxValue,
122027             value: me.value
122028         });
122029
122030         Ext.applyIf(me.renderSelectors, {
122031             endEl: '.' + Ext.baseCSSPrefix + 'slider-end',
122032             innerEl: '.' + Ext.baseCSSPrefix + 'slider-inner',
122033             focusEl: '.' + Ext.baseCSSPrefix + 'slider-focus'
122034         });
122035
122036         me.callParent(arguments);
122037
122038         //render each thumb
122039         for (; i < len; i++) {
122040             thumbs[i].render();
122041         }
122042
122043         //calculate the size of half a thumb
122044         thumb = me.innerEl.down('.' + Ext.baseCSSPrefix + 'slider-thumb');
122045         me.halfThumb = (me.vertical ? thumb.getHeight() : thumb.getWidth()) / 2;
122046
122047     },
122048
122049     /**
122050      * Utility method to set the value of the field when the slider changes.
122051      * @param {Object} slider The slider object.
122052      * @param {Object} v The new value.
122053      * @private
122054      */
122055     onChange : function(slider, v) {
122056         this.setValue(v, undefined, true);
122057     },
122058
122059     /**
122060      * @private
122061      * Adds keyboard and mouse listeners on this.el. Ignores click events on the internal focus element.
122062      */
122063     initEvents : function() {
122064         var me = this;
122065         
122066         me.mon(me.el, {
122067             scope    : me,
122068             mousedown: me.onMouseDown,
122069             keydown  : me.onKeyDown,
122070             change : me.onChange
122071         });
122072
122073         me.focusEl.swallowEvent("click", true);
122074     },
122075
122076     /**
122077      * @private
122078      * Mousedown handler for the slider. If the clickToChange is enabled and the click was not on the draggable 'thumb',
122079      * this calculates the new value of the slider and tells the implementation (Horizontal or Vertical) to move the thumb
122080      * @param {Ext.EventObject} e The click event
122081      */
122082     onMouseDown : function(e) {
122083         var me = this,
122084             thumbClicked = false,
122085             i = 0,
122086             thumbs = me.thumbs,
122087             len = thumbs.length,
122088             local;
122089             
122090         if (me.disabled) {
122091             return;
122092         }
122093
122094         //see if the click was on any of the thumbs
122095         for (; i < len; i++) {
122096             thumbClicked = thumbClicked || e.target == thumbs[i].el.dom;
122097         }
122098
122099         if (me.clickToChange && !thumbClicked) {
122100             local = me.innerEl.translatePoints(e.getXY());
122101             me.onClickChange(local);
122102         }
122103         me.focus();
122104     },
122105
122106     /**
122107      * @private
122108      * Moves the thumb to the indicated position. Note that a Vertical implementation is provided in Ext.slider.Multi.Vertical.
122109      * Only changes the value if the click was within this.clickRange.
122110      * @param {Object} local Object containing top and left values for the click event.
122111      */
122112     onClickChange : function(local) {
122113         var me = this,
122114             thumb, index;
122115             
122116         if (local.top > me.clickRange[0] && local.top < me.clickRange[1]) {
122117             //find the nearest thumb to the click event
122118             thumb = me.getNearest(local, 'left');
122119             if (!thumb.disabled) {
122120                 index = thumb.index;
122121                 me.setValue(index, Ext.util.Format.round(me.reverseValue(local.left), me.decimalPrecision), undefined, true);
122122             }
122123         }
122124     },
122125
122126     /**
122127      * @private
122128      * Returns the nearest thumb to a click event, along with its distance
122129      * @param {Object} local Object containing top and left values from a click event
122130      * @param {String} prop The property of local to compare on. Use 'left' for horizontal sliders, 'top' for vertical ones
122131      * @return {Object} The closest thumb object and its distance from the click event
122132      */
122133     getNearest: function(local, prop) {
122134         var me = this,
122135             localValue = prop == 'top' ? me.innerEl.getHeight() - local[prop] : local[prop],
122136             clickValue = me.reverseValue(localValue),
122137             nearestDistance = (me.maxValue - me.minValue) + 5, //add a small fudge for the end of the slider
122138             index = 0,
122139             nearest = null,
122140             thumbs = me.thumbs,
122141             i = 0,
122142             len = thumbs.length,
122143             thumb,
122144             value,
122145             dist;
122146
122147         for (; i < len; i++) {
122148             thumb = me.thumbs[i];
122149             value = thumb.value;
122150             dist  = Math.abs(value - clickValue);
122151
122152             if (Math.abs(dist <= nearestDistance)) {
122153                 nearest = thumb;
122154                 index = i;
122155                 nearestDistance = dist;
122156             }
122157         }
122158         return nearest;
122159     },
122160
122161     /**
122162      * @private
122163      * Handler for any keypresses captured by the slider. If the key is UP or RIGHT, the thumb is moved along to the right
122164      * by this.keyIncrement. If DOWN or LEFT it is moved left. Pressing CTRL moves the slider to the end in either direction
122165      * @param {Ext.EventObject} e The Event object
122166      */
122167     onKeyDown : function(e) {
122168         /*
122169          * The behaviour for keyboard handling with multiple thumbs is currently undefined.
122170          * There's no real sane default for it, so leave it like this until we come up
122171          * with a better way of doing it.
122172          */
122173         var me = this,
122174             k,
122175             val;
122176         
122177         if(me.disabled || me.thumbs.length !== 1) {
122178             e.preventDefault();
122179             return;
122180         }
122181         k = e.getKey();
122182         
122183         switch(k) {
122184             case e.UP:
122185             case e.RIGHT:
122186                 e.stopEvent();
122187                 val = e.ctrlKey ? me.maxValue : me.getValue(0) + me.keyIncrement;
122188                 me.setValue(0, val, undefined, true);
122189             break;
122190             case e.DOWN:
122191             case e.LEFT:
122192                 e.stopEvent();
122193                 val = e.ctrlKey ? me.minValue : me.getValue(0) - me.keyIncrement;
122194                 me.setValue(0, val, undefined, true);
122195             break;
122196             default:
122197                 e.preventDefault();
122198         }
122199     },
122200
122201     /**
122202      * @private
122203      * If using snapping, this takes a desired new value and returns the closest snapped
122204      * value to it
122205      * @param {Number} value The unsnapped value
122206      * @return {Number} The value of the nearest snap target
122207      */
122208     doSnap : function(value) {
122209         var newValue = value,
122210             inc = this.increment,
122211             m;
122212             
122213         if (!(inc && value)) {
122214             return value;
122215         }
122216         m = value % inc;
122217         if (m !== 0) {
122218             newValue -= m;
122219             if (m * 2 >= inc) {
122220                 newValue += inc;
122221             } else if (m * 2 < -inc) {
122222                 newValue -= inc;
122223             }
122224         }
122225         return Ext.Number.constrain(newValue, this.minValue,  this.maxValue);
122226     },
122227
122228     // private
122229     afterRender : function() {
122230         var me = this,
122231             i = 0,
122232             thumbs = me.thumbs,
122233             len = thumbs.length,
122234             thumb,
122235             v;
122236             
122237         me.callParent(arguments);
122238
122239         for (; i < len; i++) {
122240             thumb = thumbs[i];
122241
122242             if (thumb.value !== undefined) {
122243                 v = me.normalizeValue(thumb.value);
122244                 if (v !== thumb.value) {
122245                     // delete this.value;
122246                     me.setValue(i, v, false);
122247                 } else {
122248                     thumb.move(me.translateValue(v), false);
122249                 }
122250             }
122251         }
122252     },
122253
122254     /**
122255      * @private
122256      * Returns the ratio of pixels to mapped values. e.g. if the slider is 200px wide and maxValue - minValue is 100,
122257      * the ratio is 2
122258      * @return {Number} The ratio of pixels to mapped values
122259      */
122260     getRatio : function() {
122261         var w = this.innerEl.getWidth(),
122262             v = this.maxValue - this.minValue;
122263         return v === 0 ? w : (w/v);
122264     },
122265
122266     /**
122267      * @private
122268      * Returns a snapped, constrained value when given a desired value
122269      * @param {Number} value Raw number value
122270      * @return {Number} The raw value rounded to the correct d.p. and constrained within the set max and min values
122271      */
122272     normalizeValue : function(v) {
122273         var me = this;
122274         
122275         v = me.doSnap(v);
122276         v = Ext.util.Format.round(v, me.decimalPrecision);
122277         v = Ext.Number.constrain(v, me.minValue, me.maxValue);
122278         return v;
122279     },
122280
122281     /**
122282      * Sets the minimum value for the slider instance. If the current value is less than the
122283      * minimum value, the current value will be changed.
122284      * @param {Number} val The new minimum value
122285      */
122286     setMinValue : function(val) {
122287         var me = this,
122288             i = 0,
122289             thumbs = me.thumbs,
122290             len = thumbs.length,
122291             t;
122292             
122293         me.minValue = val;
122294         me.inputEl.dom.setAttribute('aria-valuemin', val);
122295
122296         for (; i < len; ++i) {
122297             t = thumbs[i];
122298             t.value = t.value < val ? val : t.value;
122299         }
122300         me.syncThumbs();
122301     },
122302
122303     /**
122304      * Sets the maximum value for the slider instance. If the current value is more than the
122305      * maximum value, the current value will be changed.
122306      * @param {Number} val The new maximum value
122307      */
122308     setMaxValue : function(val) {
122309         var me = this,
122310             i = 0,
122311             thumbs = me.thumbs,
122312             len = thumbs.length,
122313             t;
122314             
122315         me.maxValue = val;
122316         me.inputEl.dom.setAttribute('aria-valuemax', val);
122317
122318         for (; i < len; ++i) {
122319             t = thumbs[i];
122320             t.value = t.value > val ? val : t.value;
122321         }
122322         me.syncThumbs();
122323     },
122324
122325     /**
122326      * Programmatically sets the value of the Slider. Ensures that the value is constrained within
122327      * the minValue and maxValue.
122328      * @param {Number} index Index of the thumb to move
122329      * @param {Number} value The value to set the slider to. (This will be constrained within minValue and maxValue)
122330      * @param {Boolean} animate Turn on or off animation, defaults to true
122331      */
122332     setValue : function(index, value, animate, changeComplete) {
122333         var me = this,
122334             thumb = me.thumbs[index];
122335
122336         // ensures value is contstrained and snapped
122337         value = me.normalizeValue(value);
122338
122339         if (value !== thumb.value && me.fireEvent('beforechange', me, value, thumb.value, thumb) !== false) {
122340             thumb.value = value;
122341             if (me.rendered) {
122342                 // TODO this only handles a single value; need a solution for exposing multiple values to aria.
122343                 // Perhaps this should go on each thumb element rather than the outer element.
122344                 me.inputEl.set({
122345                     'aria-valuenow': value,
122346                     'aria-valuetext': value
122347                 });
122348
122349                 thumb.move(me.translateValue(value), Ext.isDefined(animate) ? animate !== false : me.animate);
122350
122351                 me.fireEvent('change', me, value, thumb);
122352                 if (changeComplete) {
122353                     me.fireEvent('changecomplete', me, value, thumb);
122354                 }
122355             }
122356         }
122357     },
122358
122359     /**
122360      * @private
122361      */
122362     translateValue : function(v) {
122363         var ratio = this.getRatio();
122364         return (v * ratio) - (this.minValue * ratio) - this.halfThumb;
122365     },
122366
122367     /**
122368      * @private
122369      * Given a pixel location along the slider, returns the mapped slider value for that pixel.
122370      * E.g. if we have a slider 200px wide with minValue = 100 and maxValue = 500, reverseValue(50)
122371      * returns 200
122372      * @param {Number} pos The position along the slider to return a mapped value for
122373      * @return {Number} The mapped value for the given position
122374      */
122375     reverseValue : function(pos) {
122376         var ratio = this.getRatio();
122377         return (pos + (this.minValue * ratio)) / ratio;
122378     },
122379
122380     // private
122381     focus : function() {
122382         this.focusEl.focus(10);
122383     },
122384
122385     //private
122386     onDisable: function() {
122387         var me = this,
122388             i = 0,
122389             thumbs = me.thumbs,
122390             len = thumbs.length,
122391             thumb,
122392             el,
122393             xy;
122394             
122395         me.callParent();
122396
122397         for (; i < len; i++) {
122398             thumb = thumbs[i];
122399             el = thumb.el;
122400
122401             thumb.disable();
122402
122403             if(Ext.isIE) {
122404                 //IE breaks when using overflow visible and opacity other than 1.
122405                 //Create a place holder for the thumb and display it.
122406                 xy = el.getXY();
122407                 el.hide();
122408
122409                 me.innerEl.addCls(me.disabledCls).dom.disabled = true;
122410
122411                 if (!me.thumbHolder) {
122412                     me.thumbHolder = me.endEl.createChild({cls: Ext.baseCSSPrefix + 'slider-thumb ' + me.disabledCls});
122413                 }
122414
122415                 me.thumbHolder.show().setXY(xy);
122416             }
122417         }
122418     },
122419
122420     //private
122421     onEnable: function() {
122422         var me = this,
122423             i = 0,
122424             thumbs = me.thumbs,
122425             len = thumbs.length,
122426             thumb,
122427             el;
122428             
122429         this.callParent();
122430
122431         for (; i < len; i++) {
122432             thumb = thumbs[i];
122433             el = thumb.el;
122434
122435             thumb.enable();
122436
122437             if (Ext.isIE) {
122438                 me.innerEl.removeCls(me.disabledCls).dom.disabled = false;
122439
122440                 if (me.thumbHolder) {
122441                     me.thumbHolder.hide();
122442                 }
122443
122444                 el.show();
122445                 me.syncThumbs();
122446             }
122447         }
122448     },
122449
122450     /**
122451      * Synchronizes thumbs position to the proper proportion of the total component width based
122452      * on the current slider {@link #value}.  This will be called automatically when the Slider
122453      * is resized by a layout, but if it is rendered auto width, this method can be called from
122454      * another resize handler to sync the Slider if necessary.
122455      */
122456     syncThumbs : function() {
122457         if (this.rendered) {
122458             var thumbs = this.thumbs,
122459                 length = thumbs.length,
122460                 i = 0;
122461
122462             for (; i < length; i++) {
122463                 thumbs[i].move(this.translateValue(thumbs[i].value));
122464             }
122465         }
122466     },
122467
122468     /**
122469      * Returns the current value of the slider
122470      * @param {Number} index The index of the thumb to return a value for
122471      * @return {Number/Array} The current value of the slider at the given index, or an array of
122472      * all thumb values if no index is given.
122473      */
122474     getValue : function(index) {
122475         return Ext.isNumber(index) ? this.thumbs[index].value : this.getValues();
122476     },
122477
122478     /**
122479      * Returns an array of values - one for the location of each thumb
122480      * @return {Array} The set of thumb values
122481      */
122482     getValues: function() {
122483         var values = [],
122484             i = 0,
122485             thumbs = this.thumbs,
122486             len = thumbs.length;
122487
122488         for (; i < len; i++) {
122489             values.push(thumbs[i].value);
122490         }
122491
122492         return values;
122493     },
122494
122495     getSubmitValue: function() {
122496         var me = this;
122497         return (me.disabled || !me.submitValue) ? null : me.getValue();
122498     },
122499
122500     reset: function() {
122501         var me = this,
122502             Array = Ext.Array;
122503         Array.forEach(Array.from(me.originalValue), function(val, i) {
122504             me.setValue(i, val);
122505         });
122506         me.clearInvalid();
122507         // delete here so we reset back to the original state
122508         delete me.wasValid;
122509     },
122510
122511     // private
122512     beforeDestroy : function() {
122513         var me = this;
122514         
122515         Ext.destroyMembers(me.innerEl, me.endEl, me.focusEl);
122516         Ext.each(me.thumbs, function(thumb) {
122517             Ext.destroy(thumb);
122518         }, me);
122519
122520         me.callParent();
122521     },
122522
122523     statics: {
122524         // Method overrides to support slider with vertical orientation
122525         Vertical: {
122526             getRatio : function() {
122527                 var h = this.innerEl.getHeight(),
122528                     v = this.maxValue - this.minValue;
122529                 return h/v;
122530             },
122531
122532             onClickChange : function(local) {
122533                 var me = this,
122534                     thumb, index, bottom;
122535
122536                 if (local.left > me.clickRange[0] && local.left < me.clickRange[1]) {
122537                     thumb = me.getNearest(local, 'top');
122538                     if (!thumb.disabled) {
122539                         index = thumb.index;
122540                         bottom =  me.reverseValue(me.innerEl.getHeight() - local.top);
122541
122542                         me.setValue(index, Ext.util.Format.round(me.minValue + bottom, me.decimalPrecision), undefined, true);
122543                     }
122544                 }
122545             }
122546         }
122547     }
122548 });
122549
122550 /**
122551  * @class Ext.slider.Single
122552  * @extends Ext.slider.Multi
122553  * Slider which supports vertical or horizontal orientation, keyboard adjustments,
122554  * configurable snapping, axis clicking and animation. Can be added as an item to
122555  * any container. 
122556  * {@img Ext.slider.Single/Ext.slider.Single.png Ext.slider.Single component}
122557  * Example usage:
122558 <pre><code>
122559     Ext.create('Ext.slider.Single', {
122560         width: 200,
122561         value: 50,
122562         increment: 10,
122563         minValue: 0,
122564         maxValue: 100,
122565         renderTo: Ext.getBody()
122566     });
122567 </code></pre>
122568  * The class Ext.slider.Single is aliased to Ext.Slider for backwards compatibility.
122569  * @xtype slider
122570  */
122571 Ext.define('Ext.slider.Single', {
122572     extend: 'Ext.slider.Multi',
122573     alias: ['widget.slider', 'widget.sliderfield'],
122574     alternateClassName: ['Ext.Slider', 'Ext.form.SliderField', 'Ext.slider.SingleSlider', 'Ext.slider.Slider'],
122575
122576     /**
122577      * Returns the current value of the slider
122578      * @return {Number} The current value of the slider
122579      */
122580     getValue: function() {
122581         //just returns the value of the first thumb, which should be the only one in a single slider
122582         return this.callParent([0]);
122583     },
122584
122585     /**
122586      * Programmatically sets the value of the Slider. Ensures that the value is constrained within
122587      * the minValue and maxValue.
122588      * @param {Number} value The value to set the slider to. (This will be constrained within minValue and maxValue)
122589      * @param {Boolean} animate Turn on or off animation, defaults to true
122590      */
122591     setValue: function(value, animate) {
122592         var args = Ext.toArray(arguments),
122593             len  = args.length;
122594
122595         //this is to maintain backwards compatiblity for sliders with only one thunb. Usually you must pass the thumb
122596         //index to setValue, but if we only have one thumb we inject the index here first if given the multi-slider
122597         //signature without the required index. The index will always be 0 for a single slider
122598         if (len == 1 || (len <= 3 && typeof arguments[1] != 'number')) {
122599             args.unshift(0);
122600         }
122601
122602         return this.callParent(args);
122603     },
122604
122605     // private
122606     getNearest : function(){
122607         // Since there's only 1 thumb, it's always the nearest
122608         return this.thumbs[0];
122609     }
122610 });
122611
122612 /**
122613  * @author Ed Spencer
122614  * @class Ext.tab.Tab
122615  * @extends Ext.button.Button
122616  * 
122617  * <p>Represents a single Tab in a {@link Ext.tab.Panel TabPanel}. A Tab is simply a slightly customized {@link Ext.button.Button Button}, 
122618  * styled to look like a tab. Tabs are optionally closable, and can also be disabled. 99% of the time you will not
122619  * need to create Tabs manually as the framework does so automatically when you use a {@link Ext.tab.Panel TabPanel}</p>
122620  *
122621  * @xtype tab
122622  */
122623 Ext.define('Ext.tab.Tab', {
122624     extend: 'Ext.button.Button',
122625     alias: 'widget.tab',
122626     
122627     requires: [
122628         'Ext.layout.component.Tab',
122629         'Ext.util.KeyNav'
122630     ],
122631
122632     componentLayout: 'tab',
122633
122634     isTab: true,
122635
122636     baseCls: Ext.baseCSSPrefix + 'tab',
122637
122638     /**
122639      * @cfg {String} activeCls
122640      * The CSS class to be applied to a Tab when it is active. Defaults to 'x-tab-active'.
122641      * Providing your own CSS for this class enables you to customize the active state.
122642      */
122643     activeCls: 'active',
122644     
122645     /**
122646      * @cfg {String} disabledCls
122647      * The CSS class to be applied to a Tab when it is disabled. Defaults to 'x-tab-disabled'.
122648      */
122649
122650     /**
122651      * @cfg {String} closableCls
122652      * The CSS class which is added to the tab when it is closable
122653      */
122654     closableCls: 'closable',
122655
122656     /**
122657      * @cfg {Boolean} closable True to make the Tab start closable (the close icon will be visible). Defaults to true
122658      */
122659     closable: true,
122660
122661     /**
122662      * @cfg {String} closeText 
122663      * The accessible text label for the close button link; only used when {@link #closable} = true.
122664      * Defaults to 'Close Tab'.
122665      */
122666     closeText: 'Close Tab',
122667
122668     /**
122669      * @property Boolean
122670      * Read-only property indicating that this tab is currently active. This is NOT a public configuration.
122671      */
122672     active: false,
122673
122674     /**
122675      * @property closable
122676      * @type Boolean
122677      * True if the tab is currently closable
122678      */
122679
122680     scale: false,
122681
122682     position: 'top',
122683     
122684     initComponent: function() {
122685         var me = this;
122686
122687         me.addEvents(
122688             /**
122689              * @event activate
122690              * @param {Ext.tab.Tab} this
122691              */
122692             'activate',
122693
122694             /**
122695              * @event deactivate
122696              * @param {Ext.tab.Tab} this
122697              */
122698             'deactivate',
122699
122700             /**
122701              * @event beforeclose
122702              * Fires if the user clicks on the Tab's close button, but before the {@link #close} event is fired. Return
122703              * false from any listener to stop the close event being fired
122704              * @param {Ext.tab.Tab} tab The Tab object
122705              */
122706             'beforeclose',
122707
122708             /**
122709              * @event beforeclose
122710              * Fires to indicate that the tab is to be closed, usually because the user has clicked the close button.
122711              * @param {Ext.tab.Tab} tab The Tab object
122712              */
122713             'close'
122714         );
122715         
122716         me.callParent(arguments);
122717
122718         if (me.card) {
122719             me.setCard(me.card);
122720         }
122721     },
122722
122723     /**
122724      * @ignore
122725      */
122726     onRender: function() {
122727         var me = this;
122728         
122729         me.addClsWithUI(me.position);
122730         
122731         // Set all the state classNames, as they need to include the UI
122732         // me.disabledCls = me.getClsWithUIs('disabled');
122733
122734         me.syncClosableUI();
122735
122736         me.callParent(arguments);
122737         
122738         if (me.active) {
122739             me.activate(true);
122740         }
122741
122742         me.syncClosableElements();
122743         
122744         me.keyNav = Ext.create('Ext.util.KeyNav', me.el, {
122745             enter: me.onEnterKey,
122746             del: me.onDeleteKey,
122747             scope: me
122748         });
122749     },
122750     
122751     // inherit docs
122752     enable : function(silent) {
122753         var me = this;
122754
122755         me.callParent(arguments);
122756         
122757         me.removeClsWithUI(me.position + '-disabled');
122758
122759         return me;
122760     },
122761
122762     // inherit docs
122763     disable : function(silent) {
122764         var me = this;
122765         
122766         me.callParent(arguments);
122767         
122768         me.addClsWithUI(me.position + '-disabled');
122769
122770         return me;
122771     },
122772     
122773     /**
122774      * @ignore
122775      */
122776     onDestroy: function() {
122777         var me = this;
122778
122779         if (me.closeEl) {
122780             me.closeEl.un('click', Ext.EventManager.preventDefault);
122781             me.closeEl = null;
122782         }
122783
122784         Ext.destroy(me.keyNav);
122785         delete me.keyNav;
122786
122787         me.callParent(arguments);
122788     },
122789
122790     /**
122791      * Sets the tab as either closable or not
122792      * @param {Boolean} closable Pass false to make the tab not closable. Otherwise the tab will be made closable (eg a
122793      * close button will appear on the tab)
122794      */
122795     setClosable: function(closable) {
122796         var me = this;
122797
122798         // Closable must be true if no args
122799         closable = (!arguments.length || !!closable);
122800
122801         if (me.closable != closable) {
122802             me.closable = closable;
122803
122804             // set property on the user-facing item ('card'):
122805             if (me.card) {
122806                 me.card.closable = closable;
122807             }
122808
122809             me.syncClosableUI();
122810
122811             if (me.rendered) {
122812                 me.syncClosableElements();
122813
122814                 // Tab will change width to accommodate close icon
122815                 me.doComponentLayout();
122816                 if (me.ownerCt) {
122817                     me.ownerCt.doLayout();
122818                 }
122819             }
122820         }
122821     },
122822
122823     /**
122824      * This method ensures that the closeBtn element exists or not based on 'closable'.
122825      * @private
122826      */
122827     syncClosableElements: function () {
122828         var me = this;
122829
122830         if (me.closable) {
122831             if (!me.closeEl) {
122832                 me.closeEl = me.el.createChild({
122833                     tag: 'a',
122834                     cls: me.baseCls + '-close-btn',
122835                     href: '#',
122836                     html: me.closeText,
122837                     title: me.closeText
122838                 }).on('click', Ext.EventManager.preventDefault);  // mon ???
122839             }
122840         } else {
122841             var closeEl = me.closeEl;
122842             if (closeEl) {
122843                 closeEl.un('click', Ext.EventManager.preventDefault);
122844                 closeEl.remove();
122845                 me.closeEl = null;
122846             }
122847         }
122848     },
122849
122850     /**
122851      * This method ensures that the UI classes are added or removed based on 'closable'.
122852      * @private
122853      */
122854     syncClosableUI: function () {
122855         var me = this, classes = [me.closableCls, me.closableCls + '-' + me.position];
122856
122857         if (me.closable) {
122858             me.addClsWithUI(classes);
122859         } else {
122860             me.removeClsWithUI(classes);
122861         }
122862     },
122863
122864     /**
122865      * Sets this tab's attached card. Usually this is handled automatically by the {@link Ext.tab.Panel} that this Tab
122866      * belongs to and would not need to be done by the developer
122867      * @param {Ext.Component} card The card to set
122868      */
122869     setCard: function(card) {
122870         var me = this;
122871
122872         me.card = card;
122873         me.setText(me.title || card.title);
122874         me.setIconCls(me.iconCls || card.iconCls);
122875     },
122876
122877     /**
122878      * @private
122879      * Listener attached to click events on the Tab's close button
122880      */
122881     onCloseClick: function() {
122882         var me = this;
122883
122884         if (me.fireEvent('beforeclose', me) !== false) {
122885             if (me.tabBar) {
122886                 me.tabBar.closeTab(me);
122887             }
122888
122889             me.fireEvent('close', me);
122890         }
122891     },
122892     
122893     /**
122894      * @private
122895      */
122896     onEnterKey: function(e) {
122897         var me = this;
122898         
122899         if (me.tabBar) {
122900             me.tabBar.onClick(e, me.el);
122901         }
122902     },
122903     
122904    /**
122905      * @private
122906      */
122907     onDeleteKey: function(e) {
122908         var me = this;
122909         
122910         if (me.closable) {
122911             me.onCloseClick();
122912         }
122913     },
122914     
122915     // @private
122916     activate : function(supressEvent) {
122917         var me = this;
122918         
122919         me.active = true;
122920         me.addClsWithUI([me.activeCls, me.position + '-' + me.activeCls]);
122921
122922         if (supressEvent !== true) {
122923             me.fireEvent('activate', me);
122924         }
122925     },
122926
122927     // @private
122928     deactivate : function(supressEvent) {
122929         var me = this;
122930         
122931         me.active = false;
122932         me.removeClsWithUI([me.activeCls, me.position + '-' + me.activeCls]);
122933         
122934         if (supressEvent !== true) {
122935             me.fireEvent('deactivate', me);
122936         }
122937     }
122938 });
122939
122940 /**
122941  * @author Ed Spencer
122942  * @class Ext.tab.Bar
122943  * @extends Ext.panel.Header
122944  * <p>TabBar is used internally by a {@link Ext.tab.Panel TabPanel} and wouldn't usually need to be created manually.</p>
122945  *
122946  * @xtype tabbar
122947  */
122948 Ext.define('Ext.tab.Bar', {
122949     extend: 'Ext.panel.Header',
122950     alias: 'widget.tabbar',
122951     baseCls: Ext.baseCSSPrefix + 'tab-bar',
122952
122953     requires: [
122954         'Ext.tab.Tab',
122955         'Ext.FocusManager'
122956     ],
122957
122958     // @private
122959     defaultType: 'tab',
122960
122961     /**
122962      * @cfg Boolean plain
122963      * True to not show the full background on the tabbar
122964      */
122965     plain: false,
122966
122967     // @private
122968     renderTpl: [
122969         '<div class="{baseCls}-body<tpl if="ui"> {baseCls}-body-{ui}<tpl for="uiCls"> {parent.baseCls}-body-{parent.ui}-{.}</tpl></tpl>"<tpl if="bodyStyle"> style="{bodyStyle}"</tpl>></div>',
122970         '<div class="{baseCls}-strip<tpl if="ui"> {baseCls}-strip-{ui}<tpl for="uiCls"> {parent.baseCls}-strip-{parent.ui}-{.}</tpl></tpl>"></div>'
122971     ],
122972
122973     /**
122974      * @cfg {Number} minTabWidth The minimum width for each tab. Defaults to <tt>30</tt>.
122975      */
122976     minTabWidth: 30,
122977
122978     /**
122979      * @cfg {Number} maxTabWidth The maximum width for each tab. Defaults to <tt>undefined</tt>.
122980      */
122981     maxTabWidth: undefined,
122982
122983     // @private
122984     initComponent: function() {
122985         var me = this,
122986             keys;
122987
122988         if (me.plain) {
122989             me.setUI(me.ui + '-plain');
122990         }
122991         
122992         me.addClsWithUI(me.dock);
122993
122994         me.addEvents(
122995             /**
122996              * @event change
122997              * Fired when the currently-active tab has changed
122998              * @param {Ext.tab.Bar} tabBar The TabBar
122999              * @param {Ext.Tab} tab The new Tab
123000              * @param {Ext.Component} card The card that was just shown in the TabPanel
123001              */
123002             'change'
123003         );
123004
123005         Ext.applyIf(this.renderSelectors, {
123006             body : '.' + this.baseCls + '-body',
123007             strip: '.' + this.baseCls + '-strip'
123008         });
123009         me.callParent(arguments);
123010
123011         // TabBar must override the Header's align setting.
123012         me.layout.align = (me.orientation == 'vertical') ? 'left' : 'top';
123013         me.layout.overflowHandler = Ext.create('Ext.layout.container.boxOverflow.Scroller', me.layout);
123014         me.items.removeAt(me.items.getCount() - 1);
123015         me.items.removeAt(me.items.getCount() - 1);
123016         
123017         // Subscribe to Ext.FocusManager for key navigation
123018         keys = me.orientation == 'vertical' ? ['up', 'down'] : ['left', 'right'];
123019         Ext.FocusManager.subscribe(me, {
123020             keys: keys
123021         });
123022     },
123023
123024     // @private
123025     onAdd: function(tab) {
123026         var me = this,
123027             tabPanel = me.tabPanel,
123028             hasOwner = !!tabPanel;
123029
123030         me.callParent(arguments);
123031         tab.position = me.dock;
123032         if (hasOwner) {
123033             tab.minWidth = tabPanel.minTabWidth;
123034         }
123035         else {
123036             tab.minWidth = me.minTabWidth + (tab.iconCls ? 25 : 0);
123037         }
123038         tab.maxWidth = me.maxTabWidth || (hasOwner ? tabPanel.maxTabWidth : undefined);
123039     },
123040
123041     // @private
123042     afterRender: function() {
123043         var me = this;
123044
123045         me.mon(me.el, {
123046             scope: me,
123047             click: me.onClick,
123048             delegate: '.' + Ext.baseCSSPrefix + 'tab'
123049         });
123050         me.callParent(arguments);
123051         
123052     },
123053
123054     afterComponentLayout : function() {
123055         var me = this;
123056         
123057         me.callParent(arguments);
123058         me.strip.setWidth(me.el.getWidth());
123059     },
123060
123061     // @private
123062     onClick: function(e, target) {
123063         // The target might not be a valid tab el.
123064         var tab = Ext.getCmp(target.id),
123065             tabPanel = this.tabPanel;
123066
123067         target = e.getTarget();
123068
123069         if (tab && tab.isDisabled && !tab.isDisabled()) {
123070             if (tab.closable && target === tab.closeEl.dom) {
123071                 tab.onCloseClick();
123072             } else {
123073                 this.setActiveTab(tab);
123074                 if (tabPanel) {
123075                     tabPanel.setActiveTab(tab.card);
123076                 }
123077                 tab.focus();
123078             }
123079         }
123080     },
123081
123082     /**
123083      * @private
123084      * Closes the given tab by removing it from the TabBar and removing the corresponding card from the TabPanel
123085      * @param {Ext.Tab} tab The tab to close
123086      */
123087     closeTab: function(tab) {
123088         var card    = tab.card,
123089             tabPanel = this.tabPanel,
123090             nextTab;
123091
123092         if (tab.active && this.items.getCount() > 1) {
123093             nextTab = tab.next('tab') || this.items.items[0];
123094             this.setActiveTab(nextTab);
123095             if (tabPanel) {
123096                 tabPanel.setActiveTab(nextTab.card);
123097             }
123098         }
123099         this.remove(tab);
123100
123101         if (tabPanel && card) {
123102             tabPanel.remove(card);
123103         }
123104         
123105         if (nextTab) {
123106             nextTab.focus();
123107         }
123108     },
123109
123110     /**
123111      * @private
123112      * Marks the given tab as active
123113      * @param {Ext.Tab} tab The tab to mark active
123114      */
123115     setActiveTab: function(tab) {
123116         if (tab.disabled) {
123117             return;
123118         }
123119         var me = this;
123120         if (me.activeTab) {
123121             me.activeTab.deactivate();
123122         }
123123         tab.activate();
123124         
123125         if (me.rendered) {
123126             me.layout.layout();
123127             tab.el.scrollIntoView(me.layout.getRenderTarget());
123128         }
123129         me.activeTab = tab;
123130         me.fireEvent('change', me, tab, tab.card);
123131     }
123132 });
123133 /**
123134  * @author Ed Spencer, Tommy Maintz, Brian Moeskau
123135  * @class Ext.tab.Panel
123136  * @extends Ext.panel.Panel
123137
123138 A basic tab container. TabPanels can be used exactly like a standard {@link Ext.panel.Panel} for layout purposes, but also 
123139 have special support for containing child Components (`{@link Ext.container.Container#items items}`) that are managed 
123140 using a {@link Ext.layout.container.Card CardLayout layout manager}, and displayed as separate tabs.
123141
123142 __Note:__
123143
123144 By default, a tab's close tool _destroys_ the child tab Component and all its descendants. This makes the child tab 
123145 Component, and all its descendants __unusable__. To enable re-use of a tab, configure the TabPanel with `{@link #autoDestroy autoDestroy: false}`.
123146
123147 __TabPanel's layout:__
123148
123149 TabPanels use a Dock layout to position the {@link Ext.tab.Bar TabBar} at the top of the widget. Panels added to the TabPanel will have their 
123150 header hidden by default because the Tab will automatically take the Panel's configured title and icon.
123151
123152 TabPanels use their {@link Ext.panel.Panel#header header} or {@link Ext.panel.Panel#footer footer} element (depending on the {@link #tabPosition} 
123153 configuration) to accommodate the tab selector buttons. This means that a TabPanel will not display any configured title, and will not display any 
123154 configured header {@link Ext.panel.Panel#tools tools}.
123155
123156 To display a header, embed the TabPanel in a {@link Ext.panel.Panel Panel} which uses `{@link Ext.container.Container#layout layout:'fit'}`.
123157
123158 __Examples:__
123159
123160 Here is a basic TabPanel rendered to the body. This also shows the useful configuration {@link #activeTab}, which allows you to set the active tab on render. 
123161 If you do not set an {@link #activeTab}, no tabs will be active by default.
123162 {@img Ext.tab.Panel/Ext.tab.Panel1.png TabPanel component}
123163 Example usage:
123164
123165     Ext.create('Ext.tab.Panel', {
123166         width: 300,
123167         height: 200,
123168         activeTab: 0,
123169         items: [
123170             {
123171                 title: 'Tab 1',
123172                 bodyPadding: 10,
123173                 html : 'A simple tab'
123174             },
123175             {
123176                 title: 'Tab 2',
123177                 html : 'Another one'
123178             }
123179         ],
123180         renderTo : Ext.getBody()
123181     }); 
123182     
123183 It is easy to control the visibility of items in the tab bar. Specify hidden: true to have the
123184 tab button hidden initially. Items can be subsequently hidden and show by accessing the
123185 tab property on the child item.
123186
123187 Example usage:
123188     
123189     var tabs = Ext.create('Ext.tab.Panel', {
123190         width: 400,
123191         height: 400,
123192         renderTo: document.body,
123193         items: [{
123194             title: 'Home',
123195             html: 'Home',
123196             itemId: 'home'
123197         }, {
123198             title: 'Users',
123199             html: 'Users',
123200             itemId: 'users',
123201             hidden: true
123202         }, {
123203             title: 'Tickets',
123204             html: 'Tickets',
123205             itemId: 'tickets'
123206         }]    
123207     });
123208     
123209     setTimeout(function(){
123210         tabs.child('#home').tab.hide();
123211         var users = tabs.child('#users');
123212         users.tab.show();
123213         tabs.setActiveTab(users);
123214     }, 1000);
123215
123216 You can remove the background of the TabBar by setting the {@link #plain} property to `false`.
123217
123218 Example usage:
123219
123220     Ext.create('Ext.tab.Panel', {
123221         width: 300,
123222         height: 200,
123223         activeTab: 0,
123224         plain: true,
123225         items: [
123226             {
123227                 title: 'Tab 1',
123228                 bodyPadding: 10,
123229                 html : 'A simple tab'
123230             },
123231             {
123232                 title: 'Tab 2',
123233                 html : 'Another one'
123234             }
123235         ],
123236         renderTo : Ext.getBody()
123237     }); 
123238
123239 Another useful configuration of TabPanel is {@link #tabPosition}. This allows you to change the position where the tabs are displayed. The available 
123240 options for this are `'top'` (default) and `'bottom'`.
123241 {@img Ext.tab.Panel/Ext.tab.Panel2.png TabPanel component}
123242 Example usage:
123243
123244     Ext.create('Ext.tab.Panel', {
123245         width: 300,
123246         height: 200,
123247         activeTab: 0,
123248         bodyPadding: 10,        
123249         tabPosition: 'bottom',
123250         items: [
123251             {
123252                 title: 'Tab 1',
123253                 html : 'A simple tab'
123254             },
123255             {
123256                 title: 'Tab 2',
123257                 html : 'Another one'
123258             }
123259         ],
123260         renderTo : Ext.getBody()
123261     }); 
123262
123263 The {@link #setActiveTab} is a very useful method in TabPanel which will allow you to change the current active tab. You can either give it an index or 
123264 an instance of a tab.
123265
123266 Example usage:
123267
123268     var tabs = Ext.create('Ext.tab.Panel', {
123269         items: [
123270             {
123271                 id   : 'my-tab',
123272                 title: 'Tab 1',
123273                 html : 'A simple tab'
123274             },
123275             {
123276                 title: 'Tab 2',
123277                 html : 'Another one'
123278             }
123279         ],
123280         renderTo : Ext.getBody()
123281     });
123282     
123283     var tab = Ext.getCmp('my-tab');
123284     
123285     Ext.create('Ext.button.Button', {
123286         renderTo: Ext.getBody(),
123287         text    : 'Select the first tab',
123288         scope   : this,
123289         handler : function() {
123290             tabs.setActiveTab(tab);
123291         }
123292     });
123293     
123294     Ext.create('Ext.button.Button', {
123295         text    : 'Select the second tab',
123296         scope   : this,
123297         handler : function() {
123298             tabs.setActiveTab(1);
123299         },
123300         renderTo : Ext.getBody()        
123301     });
123302
123303 The {@link #getActiveTab} is a another useful method in TabPanel which will return the current active tab.
123304
123305 Example usage:
123306
123307     var tabs = Ext.create('Ext.tab.Panel', {
123308         items: [
123309             {
123310                 title: 'Tab 1',
123311                 html : 'A simple tab'
123312             },
123313             {
123314                 title: 'Tab 2',
123315                 html : 'Another one'
123316             }
123317         ],
123318         renderTo : Ext.getBody()        
123319     });
123320     
123321     Ext.create('Ext.button.Button', {
123322         text    : 'Get active tab',
123323         scope   : this,
123324         handler : function() {
123325             var tab = tabs.getActiveTab();
123326             alert('Current tab: ' + tab.title);
123327         },
123328         renderTo : Ext.getBody()        
123329     });
123330
123331 Adding a new tab is very simple with a TabPanel. You simple call the {@link #add} method with an config object for a panel.
123332
123333 Example usage:
123334
123335     var tabs = Ext.Create('Ext.tab.Panel', {
123336         items: [
123337             {
123338                 title: 'Tab 1',
123339                 html : 'A simple tab'
123340             },
123341             {
123342                 title: 'Tab 2',
123343                 html : 'Another one'
123344             }
123345         ],
123346         renderTo : Ext.getBody()        
123347     });
123348     
123349     Ext.create('Ext.button.Button', {
123350         text    : 'New tab',
123351         scope   : this,
123352         handler : function() {
123353             var tab = tabs.add({
123354                 title: 'Tab ' + (tabs.items.length + 1), //we use the tabs.items property to get the length of current items/tabs
123355                 html : 'Another one'
123356             });
123357             
123358             tabs.setActiveTab(tab);
123359         },
123360         renderTo : Ext.getBody()
123361     });
123362
123363 Additionally, removing a tab is very also simple with a TabPanel. You simple call the {@link #remove} method with an config object for a panel.
123364
123365 Example usage:
123366
123367     var tabs = Ext.Create('Ext.tab.Panel', {        
123368         items: [
123369             {
123370                 title: 'Tab 1',
123371                 html : 'A simple tab'
123372             },
123373             {
123374                 id   : 'remove-this-tab',
123375                 title: 'Tab 2',
123376                 html : 'Another one'
123377             }
123378         ],
123379         renderTo : Ext.getBody()
123380     });
123381     
123382     Ext.Create('Ext.button.Button', {
123383         text    : 'Remove tab',
123384         scope   : this,
123385         handler : function() {
123386             var tab = Ext.getCmp('remove-this-tab');
123387             tabs.remove(tab);
123388         },
123389         renderTo : Ext.getBody()
123390     });
123391
123392  * @extends Ext.Panel
123393  * @constructor
123394  * @param {Object} config The configuration options
123395  * @xtype tabpanel
123396  * @markdown
123397  */
123398 Ext.define('Ext.tab.Panel', {
123399     extend: 'Ext.panel.Panel',
123400     alias: 'widget.tabpanel',
123401     alternateClassName: ['Ext.TabPanel'],
123402
123403     requires: ['Ext.layout.container.Card', 'Ext.tab.Bar'],
123404
123405     /**
123406      * @cfg {String} tabPosition The position where the tab strip should be rendered (defaults to <code>'top'</code>).
123407      * In 4.0, The only other supported value is <code>'bottom'</code>.
123408      */
123409     tabPosition : 'top',
123410     
123411     /**
123412      * @cfg {Object} tabBar Optional configuration object for the internal {@link Ext.tab.Bar}. If present, this is 
123413      * passed straight through to the TabBar's constructor
123414      */
123415
123416     /**
123417      * @cfg {Object} layout Optional configuration object for the internal {@link Ext.layout.container.Card card layout}.
123418      * If present, this is passed straight through to the layout's constructor
123419      */
123420
123421     /**
123422      * @cfg {Boolean} removePanelHeader True to instruct each Panel added to the TabContainer to not render its header 
123423      * element. This is to ensure that the title of the panel does not appear twice. Defaults to true.
123424      */
123425     removePanelHeader: true,
123426
123427     /**
123428      * @cfg Boolean plain
123429      * True to not show the full background on the TabBar
123430      */
123431     plain: false,
123432
123433     /**
123434      * @cfg {String} itemCls The class added to each child item of this TabPanel. Defaults to 'x-tabpanel-child'.
123435      */
123436     itemCls: 'x-tabpanel-child',
123437
123438     /**
123439      * @cfg {Number} minTabWidth The minimum width for a tab in the {@link #tabBar}. Defaults to <code>30</code>.
123440      */
123441
123442     /**
123443      * @cfg {Boolean} deferredRender
123444      * <p><tt>true</tt> by default to defer the rendering of child <tt>{@link Ext.container.Container#items items}</tt>
123445      * to the browsers DOM until a tab is activated. <tt>false</tt> will render all contained
123446      * <tt>{@link Ext.container.Container#items items}</tt> as soon as the {@link Ext.layout.container.Card layout}
123447      * is rendered. If there is a significant amount of content or a lot of heavy controls being
123448      * rendered into panels that are not displayed by default, setting this to <tt>true</tt> might
123449      * improve performance.</p>
123450      * <br><p>The <tt>deferredRender</tt> property is internally passed to the layout manager for
123451      * TabPanels ({@link Ext.layout.container.Card}) as its {@link Ext.layout.container.Card#deferredRender}
123452      * configuration value.</p>
123453      * <br><p><b>Note</b>: leaving <tt>deferredRender</tt> as <tt>true</tt> means that the content
123454      * within an unactivated tab will not be available</p>
123455      */
123456     deferredRender : true,
123457
123458     //inherit docs
123459     initComponent: function() {
123460         var me = this,
123461             dockedItems = me.dockedItems || [],
123462             activeTab = me.activeTab || 0;
123463
123464         me.layout = Ext.create('Ext.layout.container.Card', Ext.apply({
123465             owner: me,
123466             deferredRender: me.deferredRender,
123467             itemCls: me.itemCls
123468         }, me.layout));
123469
123470         /**
123471          * @property tabBar
123472          * @type Ext.TabBar
123473          * Internal reference to the docked TabBar
123474          */
123475         me.tabBar = Ext.create('Ext.tab.Bar', Ext.apply({}, me.tabBar, {
123476             dock: me.tabPosition,
123477             plain: me.plain,
123478             border: me.border,
123479             cardLayout: me.layout,
123480             tabPanel: me
123481         }));
123482
123483         if (dockedItems && !Ext.isArray(dockedItems)) {
123484             dockedItems = [dockedItems];
123485         }
123486
123487         dockedItems.push(me.tabBar);
123488         me.dockedItems = dockedItems;
123489
123490         me.addEvents(
123491             /**
123492              * @event beforetabchange
123493              * Fires before a tab change (activated by {@link #setActiveTab}). Return false in any listener to cancel
123494              * the tabchange
123495              * @param {Ext.tab.Panel} tabPanel The TabPanel
123496              * @param {Ext.Component} newCard The card that is about to be activated
123497              * @param {Ext.Component} oldCard The card that is currently active
123498              */
123499             'beforetabchange',
123500
123501             /**
123502              * @event tabchange
123503              * Fires when a new tab has been activated (activated by {@link #setActiveTab}).
123504              * @param {Ext.tab.Panel} tabPanel The TabPanel
123505              * @param {Ext.Component} newCard The newly activated item
123506              * @param {Ext.Component} oldCard The previously active item
123507              */
123508             'tabchange'
123509         );
123510         me.callParent(arguments);
123511
123512         //set the active tab
123513         me.setActiveTab(activeTab);
123514         //set the active tab after initial layout
123515         me.on('afterlayout', me.afterInitialLayout, me, {single: true});
123516     },
123517
123518     /**
123519      * @private
123520      * We have to wait until after the initial layout to visually activate the activeTab (if set).
123521      * The active tab has different margins than normal tabs, so if the initial layout happens with
123522      * a tab active, its layout will be offset improperly due to the active margin style. Waiting
123523      * until after the initial layout avoids this issue.
123524      */
123525     afterInitialLayout: function() {
123526         var me = this,
123527             card = me.getComponent(me.activeTab);
123528             
123529         if (card) {
123530             me.layout.setActiveItem(card);
123531         }
123532     },
123533
123534     /**
123535      * Makes the given card active (makes it the visible card in the TabPanel's CardLayout and highlights the Tab)
123536      * @param {Ext.Component} card The card to make active
123537      */
123538     setActiveTab: function(card) {
123539         var me = this,
123540             previous;
123541
123542         card = me.getComponent(card);
123543         if (card) {
123544             previous = me.getActiveTab();
123545             
123546             if (previous && previous !== card && me.fireEvent('beforetabchange', me, card, previous) === false) {
123547                 return false;
123548             }
123549             
123550             me.tabBar.setActiveTab(card.tab);
123551             me.activeTab = card;
123552             if (me.rendered) {
123553                 me.layout.setActiveItem(card);
123554             }
123555             
123556             if (previous && previous !== card) {
123557                 me.fireEvent('tabchange', me, card, previous);
123558             }
123559         }
123560     },
123561
123562     /**
123563      * Returns the item that is currently active inside this TabPanel. Note that before the TabPanel first activates a
123564      * child component this will return whatever was configured in the {@link #activeTab} config option 
123565      * @return {Ext.Component/Integer} The currently active item
123566      */
123567     getActiveTab: function() {
123568         return this.activeTab;
123569     },
123570
123571     /**
123572      * Returns the {@link Ext.tab.Bar} currently used in this TabPanel
123573      * @return {Ext.TabBar} The TabBar
123574      */
123575     getTabBar: function() {
123576         return this.tabBar;
123577     },
123578
123579     /**
123580      * @ignore
123581      * Makes sure we have a Tab for each item added to the TabPanel
123582      */
123583     onAdd: function(item, index) {
123584         var me = this;
123585
123586         item.tab = me.tabBar.insert(index, {
123587             xtype: 'tab',
123588             card: item,
123589             disabled: item.disabled,
123590             closable: item.closable,
123591             hidden: item.hidden,
123592             tabBar: me.tabBar
123593         });
123594         
123595         item.on({
123596             scope : me,
123597             enable: me.onItemEnable,
123598             disable: me.onItemDisable,
123599             beforeshow: me.onItemBeforeShow,
123600             iconchange: me.onItemIconChange,
123601             titlechange: me.onItemTitleChange
123602         });
123603
123604         if (item.isPanel) {
123605             if (me.removePanelHeader) {
123606                 item.preventHeader = true;
123607                 if (item.rendered) {
123608                     item.updateHeader();
123609                 }
123610             }
123611             if (item.isPanel && me.border) {
123612                 item.setBorder(false);
123613             }
123614         }
123615
123616         // ensure that there is at least one active tab
123617         if (this.rendered && me.items.getCount() === 1) {
123618             me.setActiveTab(0);
123619         }
123620     },
123621     
123622     /**
123623      * @private
123624      * Enable corresponding tab when item is enabled.
123625      */
123626     onItemEnable: function(item){
123627         item.tab.enable();
123628     },
123629
123630     /**
123631      * @private
123632      * Disable corresponding tab when item is enabled.
123633      */    
123634     onItemDisable: function(item){
123635         item.tab.disable();
123636     },
123637     
123638     /**
123639      * @private
123640      * Sets activeTab before item is shown.
123641      */
123642     onItemBeforeShow: function(item) {
123643         if (item !== this.activeTab) {
123644             this.setActiveTab(item);
123645             return false;
123646         }    
123647     },
123648     
123649     /**
123650      * @private
123651      * Update the tab iconCls when panel iconCls has been set or changed.
123652      */
123653     onItemIconChange: function(item, newIconCls) {
123654         item.tab.setIconCls(newIconCls);
123655         this.getTabBar().doLayout();
123656     },
123657     
123658     /**
123659      * @private
123660      * Update the tab title when panel title has been set or changed.
123661      */
123662     onItemTitleChange: function(item, newTitle) {
123663         item.tab.setText(newTitle);
123664         this.getTabBar().doLayout();
123665     },
123666
123667
123668     /**
123669      * @ignore
123670      * If we're removing the currently active tab, activate the nearest one. The item is removed when we call super,
123671      * so we can do preprocessing before then to find the card's index
123672      */
123673     doRemove: function(item, autoDestroy) {
123674         var me = this,
123675             items = me.items,
123676             /**
123677              * At this point the item hasn't been removed from the items collection.
123678              * As such, if we want to check if there are no more tabs left, we have to
123679              * check for one, as opposed to 0.
123680              */
123681             hasItemsLeft = items.getCount() > 1;
123682
123683         if (me.destroying || !hasItemsLeft) {
123684             me.activeTab = null;
123685         } else if (item === me.activeTab) {
123686              me.setActiveTab(item.next() || items.getAt(0)); 
123687         }
123688         me.callParent(arguments);
123689
123690         // Remove the two references
123691         delete item.tab.card;
123692         delete item.tab;
123693     },
123694
123695     /**
123696      * @ignore
123697      * Makes sure we remove the corresponding Tab when an item is removed
123698      */
123699     onRemove: function(item, autoDestroy) {
123700         var me = this;
123701         
123702         item.un({
123703             scope : me,
123704             enable: me.onItemEnable,
123705             disable: me.onItemDisable,
123706             beforeshow: me.onItemBeforeShow
123707         });
123708         if (!me.destroying && item.tab.ownerCt == me.tabBar) {
123709             me.tabBar.remove(item.tab);
123710         }
123711     }
123712 });
123713
123714 /**
123715  * @class Ext.toolbar.Spacer
123716  * @extends Ext.toolbar.Item
123717  * A simple element that adds extra horizontal space between items in a toolbar.
123718  * By default a 2px wide space is added via css specification:
123719  * <pre><code>
123720     .x-toolbar .x-toolbar-spacer {
123721         width:2px;
123722     }
123723  * </code></pre>
123724  * <p>Example usage:</p>
123725  * {@img Ext.toolbar.Spacer/Ext.toolbar.Spacer.png Toolbar Spacer}
123726  * <pre><code>
123727     Ext.create('Ext.panel.Panel', {
123728         title: 'Toolbar Spacer Example',
123729         width: 300,
123730         height: 200,
123731         tbar : [
123732             'Item 1',
123733             {xtype: 'tbspacer'}, // or ' '
123734             'Item 2',
123735             // space width is also configurable via javascript
123736             {xtype: 'tbspacer', width: 50}, // add a 50px space
123737             'Item 3'
123738         ],
123739         renderTo: Ext.getBody()
123740     });   
123741 </code></pre>
123742  * @constructor
123743  * Creates a new Spacer
123744  * @xtype tbspacer
123745  */
123746 Ext.define('Ext.toolbar.Spacer', {
123747     extend: 'Ext.Component',
123748     alias: 'widget.tbspacer',
123749     alternateClassName: 'Ext.Toolbar.Spacer',
123750     baseCls: Ext.baseCSSPrefix + 'toolbar-spacer',
123751     focusable: false
123752 });
123753 /**
123754  * @class Ext.tree.Column
123755  * @extends Ext.grid.column.Column
123756  * 
123757  * Provides indentation and folder structure markup for a Tree taking into account
123758  * depth and position within the tree hierarchy.
123759  * 
123760  * @private
123761  */
123762 Ext.define('Ext.tree.Column', {
123763     extend: 'Ext.grid.column.Column',
123764     alias: 'widget.treecolumn',
123765
123766     initComponent: function() {
123767         var origRenderer = this.renderer || this.defaultRenderer,
123768             origScope    = this.scope || window;
123769
123770         this.renderer = function(value, metaData, record, rowIdx, colIdx, store, view) {
123771             var buf   = [],
123772                 format = Ext.String.format,
123773                 depth = record.getDepth(),
123774                 treePrefix  = Ext.baseCSSPrefix + 'tree-',
123775                 elbowPrefix = treePrefix + 'elbow-',
123776                 expanderCls = treePrefix + 'expander',
123777                 imgText     = '<img src="{1}" class="{0}" />',
123778                 checkboxText= '<input type="button" role="checkbox" class="{0}" {1} />',
123779                 formattedValue = origRenderer.apply(origScope, arguments),
123780                 href = record.get('href'),
123781                 target = record.get('hrefTarget');
123782
123783             while (record) {
123784                 if (!record.isRoot() || (record.isRoot() && view.rootVisible)) {
123785                     if (record.getDepth() === depth) {
123786                         buf.unshift(format(imgText,
123787                             treePrefix + 'icon ' + 
123788                             treePrefix + 'icon' + (record.get('icon') ? '-inline ' : (record.isLeaf() ? '-leaf ' : '-parent ')) +
123789                             (record.get('iconCls') || ''),
123790                             record.get('icon') || Ext.BLANK_IMAGE_URL
123791                         ));
123792                         if (record.get('checked') !== null) {
123793                             buf.unshift(format(
123794                                 checkboxText,
123795                                 (treePrefix + 'checkbox') + (record.get('checked') ? ' ' + treePrefix + 'checkbox-checked' : ''),
123796                                 record.get('checked') ? 'aria-checked="true"' : ''
123797                             ));
123798                             if (record.get('checked')) {
123799                                 metaData.tdCls += (' ' + Ext.baseCSSPrefix + 'tree-checked');
123800                             }
123801                         }
123802                         if (record.isLast()) {
123803                             if (record.isLeaf() || (record.isLoaded() && !record.hasChildNodes())) {
123804                                 buf.unshift(format(imgText, (elbowPrefix + 'end'), Ext.BLANK_IMAGE_URL));
123805                             } else {
123806                                 buf.unshift(format(imgText, (elbowPrefix + 'end-plus ' + expanderCls), Ext.BLANK_IMAGE_URL));
123807                             }
123808                             
123809                         } else {
123810                             if (record.isLeaf() || (record.isLoaded() && !record.hasChildNodes())) {
123811                                 buf.unshift(format(imgText, (treePrefix + 'elbow'), Ext.BLANK_IMAGE_URL));
123812                             } else {
123813                                 buf.unshift(format(imgText, (elbowPrefix + 'plus ' + expanderCls), Ext.BLANK_IMAGE_URL));
123814                             }
123815                         }
123816                     } else {
123817                         if (record.isLast() || record.getDepth() === 0) {
123818                             buf.unshift(format(imgText, (elbowPrefix + 'empty'), Ext.BLANK_IMAGE_URL));
123819                         } else if (record.getDepth() !== 0) {
123820                             buf.unshift(format(imgText, (elbowPrefix + 'line'), Ext.BLANK_IMAGE_URL));
123821                         }                      
123822                     }
123823                 }
123824                 record = record.parentNode;
123825             }
123826             if (href) {
123827                 formattedValue = format('<a href="{0}" target="{1}">{2}</a>', href, target, formattedValue);
123828             }
123829             return buf.join("") + formattedValue;
123830         };
123831         this.callParent(arguments);
123832     },
123833
123834     defaultRenderer: function(value) {
123835         return value;
123836     }
123837 });
123838 /**
123839  * @class Ext.tree.View
123840  * @extends Ext.view.Table
123841  */
123842 Ext.define('Ext.tree.View', {
123843     extend: 'Ext.view.Table',
123844     alias: 'widget.treeview',
123845
123846     loadingCls: Ext.baseCSSPrefix + 'grid-tree-loading',
123847     expandedCls: Ext.baseCSSPrefix + 'grid-tree-node-expanded',
123848
123849     expanderSelector: '.' + Ext.baseCSSPrefix + 'tree-expander',
123850     checkboxSelector: '.' + Ext.baseCSSPrefix + 'tree-checkbox',
123851     expanderIconOverCls: Ext.baseCSSPrefix + 'tree-expander-over',
123852
123853     blockRefresh: true,
123854
123855     /** 
123856      * @cfg {Boolean} rootVisible <tt>false</tt> to hide the root node (defaults to <tt>true</tt>)
123857      */
123858     rootVisible: true,
123859
123860     /** 
123861      * @cfg {Boolean} animate <tt>true</tt> to enable animated expand/collapse (defaults to the value of {@link Ext#enableFx Ext.enableFx})
123862      */
123863
123864     expandDuration: 250,
123865     collapseDuration: 250,
123866     
123867     toggleOnDblClick: true,
123868
123869     initComponent: function() {
123870         var me = this;
123871         
123872         if (me.initialConfig.animate === undefined) {
123873             me.animate = Ext.enableFx;
123874         }
123875         
123876         me.store = Ext.create('Ext.data.NodeStore', {
123877             recursive: true,
123878             rootVisible: me.rootVisible,
123879             listeners: {
123880                 beforeexpand: me.onBeforeExpand,
123881                 expand: me.onExpand,
123882                 beforecollapse: me.onBeforeCollapse,
123883                 collapse: me.onCollapse,
123884                 scope: me
123885             }
123886         });
123887         
123888         if (me.node) {
123889             me.setRootNode(me.node);
123890         }
123891         me.animQueue = {};
123892         me.callParent(arguments);
123893     },
123894     
123895     onClear: function(){
123896         this.store.removeAll();    
123897     },
123898
123899     setRootNode: function(node) {
123900         var me = this;        
123901         me.store.setNode(node);
123902         me.node = node;
123903         if (!me.rootVisible) {
123904             node.expand();
123905         }
123906     },
123907     
123908     onRender: function() {
123909         var me = this,
123910             opts = {delegate: me.expanderSelector},
123911             el;
123912
123913         me.callParent(arguments);
123914
123915         el = me.el;
123916         el.on({
123917             scope: me,
123918             delegate: me.expanderSelector,
123919             mouseover: me.onExpanderMouseOver,
123920             mouseout: me.onExpanderMouseOut
123921         });
123922         el.on({
123923             scope: me,
123924             delegate: me.checkboxSelector,
123925             click: me.onCheckboxChange
123926         });
123927     },
123928
123929     onCheckboxChange: function(e, t) {
123930         var item = e.getTarget(this.getItemSelector(), this.getTargetEl()),
123931             record, value;
123932             
123933         if (item) {
123934             record = this.getRecord(item);
123935             value = !record.get('checked');
123936             record.set('checked', value);
123937             this.fireEvent('checkchange', record, value);
123938         }
123939     },
123940
123941     getChecked: function() {
123942         var checked = [];
123943         this.node.cascadeBy(function(rec){
123944             if (rec.get('checked')) {
123945                 checked.push(rec);
123946             }
123947         });
123948         return checked;
123949     },
123950     
123951     isItemChecked: function(rec){
123952         return rec.get('checked');
123953     },
123954
123955     createAnimWrap: function(record, index) {
123956         var thHtml = '',
123957             headerCt = this.panel.headerCt,
123958             headers = headerCt.getGridColumns(),
123959             i = 0, len = headers.length, item,
123960             node = this.getNode(record),
123961             tmpEl, nodeEl;
123962
123963         for (; i < len; i++) {
123964             item = headers[i];
123965             thHtml += '<th style="width: ' + (item.hidden ? 0 : item.getDesiredWidth()) + 'px; height: 0px;"></th>';
123966         }
123967
123968         nodeEl = Ext.get(node);        
123969         tmpEl = nodeEl.insertSibling({
123970             tag: 'tr',
123971             html: [
123972                 '<td colspan="' + headerCt.getColumnCount() + '">',
123973                     '<div class="' + Ext.baseCSSPrefix + 'tree-animator-wrap' + '">',
123974                         '<table class="' + Ext.baseCSSPrefix + 'grid-table" style="width: ' + headerCt.getFullWidth() + 'px;"><tbody>',
123975                             thHtml,
123976                         '</tbody></table>',
123977                     '</div>',
123978                 '</td>'
123979             ].join('')
123980         }, 'after');
123981
123982         return {
123983             record: record,
123984             node: node,
123985             el: tmpEl,
123986             expanding: false,
123987             collapsing: false,
123988             animating: false,
123989             animateEl: tmpEl.down('div'),
123990             targetEl: tmpEl.down('tbody')
123991         };
123992     },
123993
123994     getAnimWrap: function(parent) {
123995         if (!this.animate) {
123996             return null;
123997         }
123998
123999         // We are checking to see which parent is having the animation wrap
124000         while (parent) {
124001             if (parent.animWrap) {
124002                 return parent.animWrap;
124003             }
124004             parent = parent.parentNode;
124005         }
124006         return null;
124007     },
124008
124009     doAdd: function(nodes, records, index) {
124010         // If we are adding records which have a parent that is currently expanding
124011         // lets add them to the animation wrap
124012         var me = this,
124013             record = records[0],
124014             parent = record.parentNode,
124015             a = me.all.elements,
124016             relativeIndex = 0,
124017             animWrap = me.getAnimWrap(parent),
124018             targetEl, children, len;
124019
124020         if (!animWrap || !animWrap.expanding) {
124021             me.resetScrollers();
124022             return me.callParent(arguments);
124023         }
124024
124025         // We need the parent that has the animWrap, not the nodes parent
124026         parent = animWrap.record;
124027         
124028         // If there is an anim wrap we do our special magic logic
124029         targetEl = animWrap.targetEl;
124030         children = targetEl.dom.childNodes;
124031         
124032         // We subtract 1 from the childrens length because we have a tr in there with the th'es
124033         len = children.length - 1;
124034         
124035         // The relative index is the index in the full flat collection minus the index of the wraps parent
124036         relativeIndex = index - me.indexOf(parent) - 1;
124037         
124038         // If we are adding records to the wrap that have a higher relative index then there are currently children
124039         // it means we have to append the nodes to the wrap
124040         if (!len || relativeIndex >= len) {
124041             targetEl.appendChild(nodes);
124042         }
124043         // If there are already more children then the relative index it means we are adding child nodes of
124044         // some expanded node in the anim wrap. In this case we have to insert the nodes in the right location
124045         else {
124046             // +1 because of the tr with th'es that is already there
124047             Ext.fly(children[relativeIndex + 1]).insertSibling(nodes, 'before', true);
124048         }
124049         
124050         // We also have to update the CompositeElementLite collection of the DataView
124051         if (index < a.length) {
124052             a.splice.apply(a, [index, 0].concat(nodes));
124053         }
124054         else {            
124055             a.push.apply(a, nodes);
124056         }
124057         
124058         // If we were in an animation we need to now change the animation
124059         // because the targetEl just got higher.
124060         if (animWrap.isAnimating) {
124061             me.onExpand(parent);
124062         }
124063     },
124064     
124065     doRemove: function(record, index) {
124066         // If we are adding records which have a parent that is currently expanding
124067         // lets add them to the animation wrap
124068         var me = this,
124069             parent = record.parentNode,
124070             all = me.all,
124071             animWrap = me.getAnimWrap(record),
124072             node = all.item(index).dom;
124073
124074         if (!animWrap || !animWrap.collapsing) {
124075             me.resetScrollers();
124076             return me.callParent(arguments);
124077         }
124078
124079         animWrap.targetEl.appendChild(node);
124080         all.removeElement(index);
124081     },
124082
124083     onBeforeExpand: function(parent, records, index) {
124084         var me = this,
124085             animWrap;
124086             
124087         if (!me.animate) {
124088             return;
124089         }
124090
124091         if (me.getNode(parent)) {
124092             animWrap = me.getAnimWrap(parent);
124093             if (!animWrap) {
124094                 animWrap = parent.animWrap = me.createAnimWrap(parent);
124095                 animWrap.animateEl.setHeight(0);
124096             }
124097             else if (animWrap.collapsing) {
124098                 // If we expand this node while it is still expanding then we
124099                 // have to remove the nodes from the animWrap.
124100                 animWrap.targetEl.select(me.itemSelector).remove();
124101             } 
124102             animWrap.expanding = true;
124103             animWrap.collapsing = false;
124104         }
124105     },
124106
124107     onExpand: function(parent) {
124108         var me = this,
124109             queue = me.animQueue,
124110             id = parent.getId(),
124111             animWrap,
124112             animateEl, 
124113             targetEl,
124114             queueItem;        
124115         
124116         if (me.singleExpand) {
124117             me.ensureSingleExpand(parent);
124118         }
124119         
124120         animWrap = me.getAnimWrap(parent);
124121
124122         if (!animWrap) {
124123             me.resetScrollers();
124124             return;
124125         }
124126         
124127         animateEl = animWrap.animateEl;
124128         targetEl = animWrap.targetEl;
124129
124130         animateEl.stopAnimation();
124131         // @TODO: we are setting it to 1 because quirks mode on IE seems to have issues with 0
124132         queue[id] = true;
124133         animateEl.slideIn('t', {
124134             duration: me.expandDuration,
124135             listeners: {
124136                 scope: me,
124137                 lastframe: function() {
124138                     // Move all the nodes out of the anim wrap to their proper location
124139                     animWrap.el.insertSibling(targetEl.query(me.itemSelector), 'before');
124140                     animWrap.el.remove();
124141                     me.resetScrollers();
124142                     delete animWrap.record.animWrap;
124143                     delete queue[id];
124144                 }
124145             }
124146         });
124147         
124148         animWrap.isAnimating = true;
124149     },
124150     
124151     resetScrollers: function(){
124152         var panel = this.panel;
124153         
124154         panel.determineScrollbars();
124155         panel.invalidateScroller();
124156     },
124157
124158     onBeforeCollapse: function(parent, records, index) {
124159         var me = this,
124160             animWrap;
124161             
124162         if (!me.animate) {
124163             return;
124164         }
124165
124166         if (me.getNode(parent)) {
124167             animWrap = me.getAnimWrap(parent);
124168             if (!animWrap) {
124169                 animWrap = parent.animWrap = me.createAnimWrap(parent, index);
124170             }
124171             else if (animWrap.expanding) {
124172                 // If we collapse this node while it is still expanding then we
124173                 // have to remove the nodes from the animWrap.
124174                 animWrap.targetEl.select(this.itemSelector).remove();
124175             }
124176             animWrap.expanding = false;
124177             animWrap.collapsing = true;
124178         }
124179     },
124180     
124181     onCollapse: function(parent) {
124182         var me = this,
124183             queue = me.animQueue,
124184             id = parent.getId(),
124185             animWrap = me.getAnimWrap(parent),
124186             animateEl, targetEl;
124187
124188         if (!animWrap) {
124189             me.resetScrollers();
124190             return;
124191         }
124192         
124193         animateEl = animWrap.animateEl;
124194         targetEl = animWrap.targetEl;
124195
124196         queue[id] = true;
124197         
124198         // @TODO: we are setting it to 1 because quirks mode on IE seems to have issues with 0
124199         animateEl.stopAnimation();
124200         animateEl.slideOut('t', {
124201             duration: me.collapseDuration,
124202             listeners: {
124203                 scope: me,
124204                 lastframe: function() {
124205                     animWrap.el.remove();
124206                     delete animWrap.record.animWrap;
124207                     me.resetScrollers();
124208                     delete queue[id];
124209                 }             
124210             }
124211         });
124212         animWrap.isAnimating = true;
124213     },
124214     
124215     /**
124216      * Checks if a node is currently undergoing animation
124217      * @private
124218      * @param {Ext.data.Model} node The node
124219      * @return {Boolean} True if the node is animating
124220      */
124221     isAnimating: function(node) {
124222         return !!this.animQueue[node.getId()];    
124223     },
124224     
124225     collectData: function(records) {
124226         var data = this.callParent(arguments),
124227             rows = data.rows,
124228             len = rows.length,
124229             i = 0,
124230             row, record;
124231             
124232         for (; i < len; i++) {
124233             row = rows[i];
124234             record = records[i];
124235             if (record.get('qtip')) {
124236                 row.rowAttr = 'data-qtip="' + record.get('qtip') + '"';
124237                 if (record.get('qtitle')) {
124238                     row.rowAttr += ' ' + 'data-qtitle="' + record.get('qtitle') + '"';
124239                 }
124240             }
124241             if (record.isExpanded()) {
124242                 row.rowCls = (row.rowCls || '') + ' ' + this.expandedCls;
124243             }
124244             if (record.isLoading()) {
124245                 row.rowCls = (row.rowCls || '') + ' ' + this.loadingCls;
124246             }
124247         }
124248         
124249         return data;
124250     },
124251     
124252     /**
124253      * Expand a record that is loaded in the view.
124254      * @param {Ext.data.Model} record The record to expand
124255      * @param {Boolean} deep (optional) True to expand nodes all the way down the tree hierarchy.
124256      * @param {Function} callback (optional) The function to run after the expand is completed
124257      * @param {Object} scope (optional) The scope of the callback function.
124258      */
124259     expand: function(record, deep, callback, scope) {
124260         return record.expand(deep, callback, scope);
124261     },
124262     
124263     /**
124264      * Collapse a record that is loaded in the view.
124265      * @param {Ext.data.Model} record The record to collapse
124266      * @param {Boolean} deep (optional) True to collapse nodes all the way up the tree hierarchy.
124267      * @param {Function} callback (optional) The function to run after the collapse is completed
124268      * @param {Object} scope (optional) The scope of the callback function.
124269      */
124270     collapse: function(record, deep, callback, scope) {
124271         return record.collapse(deep, callback, scope);
124272     },
124273     
124274     /**
124275      * Toggle a record between expanded and collapsed.
124276      * @param {Ext.data.Record} recordInstance
124277      */
124278     toggle: function(record) {
124279         this[record.isExpanded() ? 'collapse' : 'expand'](record);
124280     },
124281     
124282     onItemDblClick: function(record, item, index) {
124283         this.callParent(arguments);
124284         if (this.toggleOnDblClick) {
124285             this.toggle(record);
124286         }
124287     },
124288     
124289     onBeforeItemMouseDown: function(record, item, index, e) {
124290         if (e.getTarget(this.expanderSelector, item)) {
124291             return false;
124292         }
124293         return this.callParent(arguments);
124294     },
124295     
124296     onItemClick: function(record, item, index, e) {
124297         if (e.getTarget(this.expanderSelector, item)) {
124298             this.toggle(record);
124299             return false;
124300         }
124301         return this.callParent(arguments);
124302     },
124303     
124304     onExpanderMouseOver: function(e, t) {
124305         e.getTarget(this.cellSelector, 10, true).addCls(this.expanderIconOverCls);
124306     },
124307     
124308     onExpanderMouseOut: function(e, t) {
124309         e.getTarget(this.cellSelector, 10, true).removeCls(this.expanderIconOverCls);
124310     },
124311     
124312     /**
124313      * Gets the base TreeStore from the bound TreePanel.
124314      */
124315     getTreeStore: function() {
124316         return this.panel.store;
124317     },    
124318     
124319     ensureSingleExpand: function(node) {
124320         var parent = node.parentNode;
124321         if (parent) {
124322             parent.eachChild(function(child) {
124323                 if (child !== node && child.isExpanded()) {
124324                     child.collapse();
124325                 }
124326             });
124327         }
124328     }
124329 });
124330 /**
124331  * @class Ext.tree.Panel
124332  * @extends Ext.panel.Table
124333  * 
124334  * The TreePanel provides tree-structured UI representation of tree-structured data.
124335  * A TreePanel must be bound to a {@link Ext.data.TreeStore}. TreePanel's support
124336  * multiple columns through the {@link columns} configuration. 
124337  * 
124338  * Simple TreePanel using inline data.
124339  *
124340  * {@img Ext.tree.Panel/Ext.tree.Panel1.png Ext.tree.Panel component}
124341  * 
124342  * ## Simple Tree Panel (no columns)
124343  *
124344  *     var store = Ext.create('Ext.data.TreeStore', {
124345  *         root: {
124346  *             expanded: true, 
124347  *             text:"",
124348  *             user:"",
124349  *             status:"", 
124350  *             children: [
124351  *                 { text:"detention", leaf: true },
124352  *                 { text:"homework", expanded: true, 
124353  *                     children: [
124354  *                         { text:"book report", leaf: true },
124355  *                         { text:"alegrbra", leaf: true}
124356  *                     ]
124357  *                 },
124358  *                 { text: "buy lottery tickets", leaf:true }
124359  *             ]
124360  *         }
124361  *     });     
124362  *             
124363  *     Ext.create('Ext.tree.Panel', {
124364  *         title: 'Simple Tree',
124365  *         width: 200,
124366  *         height: 150,
124367  *         store: store,
124368  *         rootVisible: false,        
124369  *         renderTo: Ext.getBody()
124370  *     });
124371  *
124372  * @xtype treepanel
124373  */
124374 Ext.define('Ext.tree.Panel', {
124375     extend: 'Ext.panel.Table',
124376     alias: 'widget.treepanel',
124377     alternateClassName: ['Ext.tree.TreePanel', 'Ext.TreePanel'],
124378     requires: ['Ext.tree.View', 'Ext.selection.TreeModel', 'Ext.tree.Column'],
124379     viewType: 'treeview',
124380     selType: 'treemodel',
124381     
124382     treeCls: Ext.baseCSSPrefix + 'tree-panel',
124383     
124384     /**
124385      * @cfg {Boolean} lines false to disable tree lines (defaults to true)
124386      */
124387     lines: true,
124388     
124389     /**
124390      * @cfg {Boolean} useArrows true to use Vista-style arrows in the tree (defaults to false)
124391      */
124392     useArrows: false,
124393     
124394     /**
124395      * @cfg {Boolean} singleExpand <tt>true</tt> if only 1 node per branch may be expanded
124396      */
124397     singleExpand: false,
124398     
124399     ddConfig: {
124400         enableDrag: true,
124401         enableDrop: true
124402     },
124403     
124404     /** 
124405      * @cfg {Boolean} animate <tt>true</tt> to enable animated expand/collapse (defaults to the value of {@link Ext#enableFx Ext.enableFx})
124406      */
124407             
124408     /** 
124409      * @cfg {Boolean} rootVisible <tt>false</tt> to hide the root node (defaults to <tt>true</tt>)
124410      */
124411     rootVisible: true,
124412     
124413     /** 
124414      * @cfg {Boolean} displayField The field inside the model that will be used as the node's text. (defaults to <tt>text</tt>)
124415      */    
124416     displayField: 'text',
124417
124418     /** 
124419      * @cfg {Boolean} root Allows you to not specify a store on this TreePanel. This is useful for creating a simple
124420      * tree with preloaded data without having to specify a TreeStore and Model. A store and model will be created and
124421      * root will be passed to that store.
124422      */
124423     root: null,
124424     
124425     // Required for the Lockable Mixin. These are the configurations which will be copied to the
124426     // normal and locked sub tablepanels
124427     normalCfgCopy: ['displayField', 'root', 'singleExpand', 'useArrows', 'lines', 'rootVisible', 'scroll'],
124428     lockedCfgCopy: ['displayField', 'root', 'singleExpand', 'useArrows', 'lines', 'rootVisible'],
124429
124430     /**
124431      * @cfg {Boolean} hideHeaders
124432      * Specify as <code>true</code> to hide the headers.
124433      */
124434     
124435     /**
124436      * @cfg {Boolean} folderSort Set to true to automatically prepend a leaf sorter to the store (defaults to <tt>undefined</tt>)
124437      */ 
124438     
124439     constructor: function(config) {
124440         config = config || {};
124441         if (config.animate === undefined) {
124442             config.animate = Ext.enableFx;
124443         }
124444         this.enableAnimations = config.animate;
124445         delete config.animate;
124446         
124447         this.callParent([config]);
124448     },
124449     
124450     initComponent: function() {
124451         var me = this,
124452             cls = [me.treeCls];
124453
124454         if (me.useArrows) {
124455             cls.push(Ext.baseCSSPrefix + 'tree-arrows');
124456             me.lines = false;
124457         }
124458         
124459         if (me.lines) {
124460             cls.push(Ext.baseCSSPrefix + 'tree-lines');
124461         } else if (!me.useArrows) {
124462             cls.push(Ext.baseCSSPrefix + 'tree-no-lines');
124463         }
124464
124465         if (!me.store || Ext.isObject(me.store) && !me.store.isStore) {
124466             me.store = Ext.create('Ext.data.TreeStore', Ext.apply({}, me.store || {}, {
124467                 root: me.root,
124468                 fields: me.fields,
124469                 model: me.model,
124470                 folderSort: me.folderSort
124471             }));
124472         }
124473         else if (me.root) {
124474             me.store = Ext.data.StoreManager.lookup(me.store);
124475             me.store.setRootNode(me.root);
124476             if (me.folderSort !== undefined) {
124477                 me.store.folderSort = me.folderSort;
124478                 me.store.sort();
124479             }            
124480         }
124481         
124482         // I'm not sure if we want to this. It might be confusing
124483         // if (me.initialConfig.rootVisible === undefined && !me.getRootNode()) {
124484         //     me.rootVisible = false;
124485         // }
124486         
124487         me.viewConfig = Ext.applyIf(me.viewConfig || {}, {
124488             rootVisible: me.rootVisible,
124489             animate: me.enableAnimations,
124490             singleExpand: me.singleExpand,
124491             node: me.store.getRootNode(),
124492             hideHeaders: me.hideHeaders
124493         });
124494         
124495         me.mon(me.store, {
124496             scope: me,
124497             rootchange: me.onRootChange,
124498             clear: me.onClear
124499         });
124500     
124501         me.relayEvents(me.store, [
124502             /**
124503              * @event beforeload
124504              * Event description
124505              * @param {Ext.data.Store} store This Store
124506              * @param {Ext.data.Operation} operation The Ext.data.Operation object that will be passed to the Proxy to load the Store
124507              */
124508             'beforeload',
124509
124510             /**
124511              * @event load
124512              * Fires whenever the store reads data from a remote data source.
124513              * @param {Ext.data.store} this
124514              * @param {Array} records An array of records
124515              * @param {Boolean} successful True if the operation was successful.
124516              */
124517             'load'   
124518         ]);
124519         
124520         me.store.on({
124521             /**
124522              * @event itemappend
124523              * Fires when a new child node is appended to a node in the tree.
124524              * @param {Tree} tree The owner tree
124525              * @param {Node} parent The parent node
124526              * @param {Node} node The newly appended node
124527              * @param {Number} index The index of the newly appended node
124528              */
124529             append: me.createRelayer('itemappend'),
124530             
124531             /**
124532              * @event itemremove
124533              * Fires when a child node is removed from a node in the tree
124534              * @param {Tree} tree The owner tree
124535              * @param {Node} parent The parent node
124536              * @param {Node} node The child node removed
124537              */
124538             remove: me.createRelayer('itemremove'),
124539             
124540             /**
124541              * @event itemmove
124542              * Fires when a node is moved to a new location in the tree
124543              * @param {Tree} tree The owner tree
124544              * @param {Node} node The node moved
124545              * @param {Node} oldParent The old parent of this node
124546              * @param {Node} newParent The new parent of this node
124547              * @param {Number} index The index it was moved to
124548              */
124549             move: me.createRelayer('itemmove'),
124550             
124551             /**
124552              * @event iteminsert
124553              * Fires when a new child node is inserted in a node in tree
124554              * @param {Tree} tree The owner tree
124555              * @param {Node} parent The parent node
124556              * @param {Node} node The child node inserted
124557              * @param {Node} refNode The child node the node was inserted before
124558              */
124559             insert: me.createRelayer('iteminsert'),
124560             
124561             /**
124562              * @event beforeitemappend
124563              * Fires before a new child is appended to a node in this tree, return false to cancel the append.
124564              * @param {Tree} tree The owner tree
124565              * @param {Node} parent The parent node
124566              * @param {Node} node The child node to be appended
124567              */
124568             beforeappend: me.createRelayer('beforeitemappend'),
124569             
124570             /**
124571              * @event beforeitemremove
124572              * Fires before a child is removed from a node in this tree, return false to cancel the remove.
124573              * @param {Tree} tree The owner tree
124574              * @param {Node} parent The parent node
124575              * @param {Node} node The child node to be removed
124576              */
124577             beforeremove: me.createRelayer('beforeitemremove'),
124578             
124579             /**
124580              * @event beforeitemmove
124581              * Fires before a node is moved to a new location in the tree. Return false to cancel the move.
124582              * @param {Tree} tree The owner tree
124583              * @param {Node} node The node being moved
124584              * @param {Node} oldParent The parent of the node
124585              * @param {Node} newParent The new parent the node is moving to
124586              * @param {Number} index The index it is being moved to
124587              */
124588             beforemove: me.createRelayer('beforeitemmove'),
124589             
124590             /**
124591              * @event beforeiteminsert
124592              * Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
124593              * @param {Tree} tree The owner tree
124594              * @param {Node} parent The parent node
124595              * @param {Node} node The child node to be inserted
124596              * @param {Node} refNode The child node the node is being inserted before
124597              */
124598             beforeinsert: me.createRelayer('beforeiteminsert'),
124599              
124600             /**
124601              * @event itemexpand
124602              * Fires when a node is expanded.
124603              * @param {Node} this The expanding node
124604              */
124605             expand: me.createRelayer('itemexpand'),
124606              
124607             /**
124608              * @event itemcollapse
124609              * Fires when a node is collapsed.
124610              * @param {Node} this The collapsing node
124611              */
124612             collapse: me.createRelayer('itemcollapse'),
124613              
124614             /**
124615              * @event beforeitemexpand
124616              * Fires before a node is expanded.
124617              * @param {Node} this The expanding node
124618              */
124619             beforeexpand: me.createRelayer('beforeitemexpand'),
124620              
124621             /**
124622              * @event beforeitemcollapse
124623              * Fires before a node is collapsed.
124624              * @param {Node} this The collapsing node
124625              */
124626             beforecollapse: me.createRelayer('beforeitemcollapse')
124627         });
124628         
124629         // If the user specifies the headers collection manually then dont inject our own
124630         if (!me.columns) {
124631             if (me.initialConfig.hideHeaders === undefined) {
124632                 me.hideHeaders = true;
124633             }
124634             me.columns = [{
124635                 xtype    : 'treecolumn',
124636                 text     : 'Name',
124637                 flex     : 1,
124638                 dataIndex: me.displayField         
124639             }];
124640         }
124641         
124642         if (me.cls) {
124643             cls.push(me.cls);
124644         }
124645         me.cls = cls.join(' ');
124646         me.callParent();
124647         
124648         me.relayEvents(me.getView(), [
124649             /**
124650              * @event checkchange
124651              * Fires when a node with a checkbox's checked property changes
124652              * @param {Ext.data.Model} node The node who's checked property was changed
124653              * @param {Boolean} checked The node's new checked state
124654              */
124655             'checkchange'
124656         ]);
124657             
124658         // If the root is not visible and there is no rootnode defined, then just lets load the store
124659         if (!me.getView().rootVisible && !me.getRootNode()) {
124660             me.setRootNode({
124661                 expanded: true
124662             });
124663         }
124664     },
124665     
124666     onClear: function(){
124667         this.view.onClear();
124668     },
124669     
124670     setRootNode: function() {
124671         return this.store.setRootNode.apply(this.store, arguments);
124672     },
124673     
124674     getRootNode: function() {
124675         return this.store.getRootNode();
124676     },
124677     
124678     onRootChange: function(root) {
124679         this.view.setRootNode(root);
124680     },
124681
124682     /**
124683      * Retrieve an array of checked records.
124684      * @return {Array} An array containing the checked records
124685      */
124686     getChecked: function() {
124687         return this.getView().getChecked();
124688     },
124689     
124690     isItemChecked: function(rec) {
124691         return rec.get('checked');
124692     },
124693         
124694     /**
124695      * Expand all nodes
124696      * @param {Function} callback (optional) A function to execute when the expand finishes.
124697      * @param {Object} scope (optional) The scope of the callback function
124698      */
124699     expandAll : function(callback, scope) {
124700         var root = this.getRootNode();
124701         if (root) {
124702             root.expand(true, callback, scope);
124703         }
124704     },
124705
124706     /**
124707      * Collapse all nodes
124708      * @param {Function} callback (optional) A function to execute when the collapse finishes.
124709      * @param {Object} scope (optional) The scope of the callback function
124710      */
124711     collapseAll : function(callback, scope) {
124712         var root = this.getRootNode();
124713         if (root) {
124714             if (this.getView().rootVisible) {
124715                 root.collapse(true, callback, scope);
124716             }
124717             else {
124718                 root.collapseChildren(true, callback, scope);
124719             }
124720         }
124721     },
124722
124723     /**
124724      * Expand the tree to the path of a particular node.
124725      * @param {String} path The path to expand
124726      * @param {String} field (optional) The field to get the data from. Defaults to the model idProperty.
124727      * @param {String} separator (optional) A separator to use. Defaults to <tt>'/'</tt>.
124728      * @param {Function} callback (optional) A function to execute when the expand finishes. The callback will be called with
124729      * (success, lastNode) where success is if the expand was successful and lastNode is the last node that was expanded.
124730      * @param {Object} scope (optional) The scope of the callback function
124731      */
124732     expandPath: function(path, field, separator, callback, scope) {
124733         var me = this,
124734             current = me.getRootNode(),
124735             index = 1,
124736             view = me.getView(),
124737             keys,
124738             expander;
124739         
124740         field = field || me.getRootNode().idProperty;
124741         separator = separator || '/';
124742         
124743         if (Ext.isEmpty(path)) {
124744             Ext.callback(callback, scope || me, [false, null]);
124745             return;
124746         }
124747         
124748         keys = path.split(separator);
124749         if (current.get(field) != keys[1]) {
124750             // invalid root
124751             Ext.callback(callback, scope || me, [false, current]);
124752             return;
124753         }
124754         
124755         expander = function(){
124756             if (++index === keys.length) {
124757                 Ext.callback(callback, scope || me, [true, current]);
124758                 return;
124759             }
124760             var node = current.findChild(field, keys[index]);
124761             if (!node) {
124762                 Ext.callback(callback, scope || me, [false, current]);
124763                 return;
124764             }
124765             current = node;
124766             current.expand(false, expander);
124767         };
124768         current.expand(false, expander);
124769     },
124770     
124771     /**
124772      * Expand the tree to the path of a particular node, then selecti t.
124773      * @param {String} path The path to select
124774      * @param {String} field (optional) The field to get the data from. Defaults to the model idProperty.
124775      * @param {String} separator (optional) A separator to use. Defaults to <tt>'/'</tt>.
124776      * @param {Function} callback (optional) A function to execute when the select finishes. The callback will be called with
124777      * (bSuccess, oLastNode) where bSuccess is if the select was successful and oLastNode is the last node that was expanded.
124778      * @param {Object} scope (optional) The scope of the callback function
124779      */
124780     selectPath: function(path, field, separator, callback, scope) {
124781         var me = this,
124782             keys,
124783             last;
124784         
124785         field = field || me.getRootNode().idProperty;
124786         separator = separator || '/';
124787         
124788         keys = path.split(separator);
124789         last = keys.pop();
124790         
124791         me.expandPath(keys.join('/'), field, separator, function(success, node){
124792             var doSuccess = false;
124793             if (success && node) {
124794                 node = node.findChild(field, last);
124795                 if (node) {
124796                     me.getSelectionModel().select(node);
124797                     Ext.callback(callback, scope || me, [true, node]);
124798                     doSuccess = true;
124799                 }
124800             } else if (node === me.getRootNode()) {
124801                 doSuccess = true;
124802             }
124803             Ext.callback(callback, scope || me, [doSuccess, node]);
124804         }, me);
124805     }
124806 });
124807 /**
124808  * @class Ext.view.DragZone
124809  * @extends Ext.dd.DragZone
124810  * @private
124811  */
124812 Ext.define('Ext.view.DragZone', {
124813     extend: 'Ext.dd.DragZone',
124814     containerScroll: false,
124815
124816     constructor: function(config) {
124817         var me = this;
124818
124819         Ext.apply(me, config);
124820
124821         // Create a ddGroup unless one has been configured.
124822         // User configuration of ddGroups allows users to specify which
124823         // DD instances can interact with each other. Using one
124824         // based on the id of the View would isolate it and mean it can only
124825         // interact with a DropZone on the same View also using a generated ID.
124826         if (!me.ddGroup) {
124827             me.ddGroup = 'view-dd-zone-' + me.view.id;
124828         }
124829
124830         // Ext.dd.DragDrop instances are keyed by the ID of their encapsulating element.
124831         // So a View's DragZone cannot use the View's main element because the DropZone must use that
124832         // because the DropZone may need to scroll on hover at a scrolling boundary, and it is the View's
124833         // main element which handles scrolling.
124834         // We use the View's parent element to drag from. Ideally, we would use the internal structure, but that 
124835         // is transient; DataView's recreate the internal structure dynamically as data changes.
124836         // TODO: Ext 5.0 DragDrop must allow multiple DD objects to share the same element.
124837         me.callParent([me.view.el.dom.parentNode]);
124838
124839         me.ddel = Ext.get(document.createElement('div'));
124840         me.ddel.addCls(Ext.baseCSSPrefix + 'grid-dd-wrap');
124841     },
124842
124843     init: function(id, sGroup, config) {
124844         this.initTarget(id, sGroup, config);
124845         this.view.mon(this.view, {
124846             itemmousedown: this.onItemMouseDown,
124847             scope: this
124848         });
124849     },
124850
124851     onItemMouseDown: function(view, record, item, index, e) {
124852         if (!this.isPreventDrag(e, record, item, index)) {
124853             this.handleMouseDown(e);
124854         }
124855     },
124856
124857     // private template method
124858     isPreventDrag: function(e) {
124859         return false;
124860     },
124861
124862     getDragData: function(e) {
124863         var view = this.view,
124864             item = e.getTarget(view.getItemSelector()),
124865             record, selectionModel, records;
124866
124867         if (item) {
124868             record = view.getRecord(item);
124869             selectionModel = view.getSelectionModel();
124870             records = selectionModel.getSelection();
124871             return {
124872                 copy: this.view.copy || (this.view.allowCopy && e.ctrlKey),
124873                 event: new Ext.EventObjectImpl(e),
124874                 view: view,
124875                 ddel: this.ddel,
124876                 item: item,
124877                 records: records,
124878                 fromPosition: Ext.fly(item).getXY()
124879             };
124880         }
124881     },
124882
124883     onInitDrag: function(x, y) {
124884         var me = this,
124885             data = me.dragData,
124886             view = data.view,
124887             selectionModel = view.getSelectionModel(),
124888             record = view.getRecord(data.item),
124889             e = data.event;
124890
124891         // Update the selection to match what would have been selected if the user had
124892         // done a full click on the target node rather than starting a drag from it
124893         if (!selectionModel.isSelected(record) || e.hasModifier()) {
124894             selectionModel.selectWithEvent(record, e);
124895         }
124896         data.records = selectionModel.getSelection();
124897
124898         me.ddel.update(me.getDragText());
124899         me.proxy.update(me.ddel.dom);
124900         me.onStartDrag(x, y);
124901         return true;
124902     },
124903
124904     getDragText: function() {
124905         var count = this.dragData.records.length;
124906         return Ext.String.format(this.dragText, count, count == 1 ? '' : 's');
124907     },
124908
124909     getRepairXY : function(e, data){
124910         return data ? data.fromPosition : false;
124911     }
124912 });
124913 Ext.define('Ext.tree.ViewDragZone', {
124914     extend: 'Ext.view.DragZone',
124915
124916     isPreventDrag: function(e, record) {
124917         return (record.get('allowDrag') === false) || !!e.getTarget(this.view.expanderSelector);
124918     },
124919     
124920     afterRepair: function() {
124921         var me = this,
124922             view = me.view,
124923             selectedRowCls = view.selectedItemCls,
124924             records = me.dragData.records,
124925             fly = Ext.fly;
124926         
124927         if (Ext.enableFx && me.repairHighlight) {
124928             // Roll through all records and highlight all the ones we attempted to drag.
124929             Ext.Array.forEach(records, function(record) {
124930                 // anonymous fns below, don't hoist up unless below is wrapped in
124931                 // a self-executing function passing in item.
124932                 var item = view.getNode(record);
124933                 
124934                 // We must remove the selected row class before animating, because
124935                 // the selected row class declares !important on its background-color.
124936                 fly(item.firstChild).highlight(me.repairHighlightColor, {
124937                     listeners: {
124938                         beforeanimate: function() {
124939                             if (view.isSelected(item)) {
124940                                 fly(item).removeCls(selectedRowCls);
124941                             }
124942                         },
124943                         afteranimate: function() {
124944                             if (view.isSelected(item)) {
124945                                 fly(item).addCls(selectedRowCls);
124946                             }
124947                         }
124948                     }
124949                 });
124950             });
124951         }
124952         me.dragging = false;
124953     }
124954 });
124955 /**
124956  * @class Ext.tree.ViewDropZone
124957  * @extends Ext.view.DropZone
124958  * @private
124959  */
124960 Ext.define('Ext.tree.ViewDropZone', {
124961     extend: 'Ext.view.DropZone',
124962
124963     /**
124964      * @cfg {Boolean} allowParentInsert
124965      * Allow inserting a dragged node between an expanded parent node and its first child that will become a
124966      * sibling of the parent when dropped (defaults to false)
124967      */
124968     allowParentInserts: false,
124969  
124970     /**
124971      * @cfg {String} allowContainerDrop
124972      * True if drops on the tree container (outside of a specific tree node) are allowed (defaults to false)
124973      */
124974     allowContainerDrops: false,
124975
124976     /**
124977      * @cfg {String} appendOnly
124978      * True if the tree should only allow append drops (use for trees which are sorted, defaults to false)
124979      */
124980     appendOnly: false,
124981
124982     /**
124983      * @cfg {String} expandDelay
124984      * The delay in milliseconds to wait before expanding a target tree node while dragging a droppable node
124985      * over the target (defaults to 500)
124986      */
124987     expandDelay : 500,
124988
124989     indicatorCls: 'x-tree-ddindicator',
124990
124991     // private
124992     expandNode : function(node) {
124993         var view = this.view;
124994         if (!node.isLeaf() && !node.isExpanded()) {
124995             view.expand(node);
124996             this.expandProcId = false;
124997         }
124998     },
124999
125000     // private
125001     queueExpand : function(node) {
125002         this.expandProcId = Ext.Function.defer(this.expandNode, this.expandDelay, this, [node]);
125003     },
125004
125005     // private
125006     cancelExpand : function() {
125007         if (this.expandProcId) {
125008             clearTimeout(this.expandProcId);
125009             this.expandProcId = false;
125010         }
125011     },
125012
125013     getPosition: function(e, node) {
125014         var view = this.view,
125015             record = view.getRecord(node),
125016             y = e.getPageY(),
125017             noAppend = record.isLeaf(),
125018             noBelow = false,
125019             region = Ext.fly(node).getRegion(),
125020             fragment;
125021
125022         // If we are dragging on top of the root node of the tree, we always want to append.
125023         if (record.isRoot()) {
125024             return 'append';
125025         }
125026
125027         // Return 'append' if the node we are dragging on top of is not a leaf else return false.
125028         if (this.appendOnly) {
125029             return noAppend ? false : 'append';
125030         }
125031
125032         if (!this.allowParentInsert) {
125033             noBelow = record.hasChildNodes() && record.isExpanded();
125034         }
125035
125036         fragment = (region.bottom - region.top) / (noAppend ? 2 : 3);
125037         if (y >= region.top && y < (region.top + fragment)) {
125038             return 'before';
125039         }
125040         else if (!noBelow && (noAppend || (y >= (region.bottom - fragment) && y <= region.bottom))) {
125041             return 'after';
125042         }
125043         else {
125044             return 'append';
125045         }
125046     },
125047
125048     isValidDropPoint : function(node, position, dragZone, e, data) {
125049         if (!node || !data.item) {
125050             return false;
125051         }
125052
125053         var view = this.view,
125054             targetNode = view.getRecord(node),
125055             draggedRecords = data.records,
125056             dataLength = draggedRecords.length,
125057             ln = draggedRecords.length,
125058             i, record;
125059
125060         // No drop position, or dragged records: invalid drop point
125061         if (!(targetNode && position && dataLength)) {
125062             return false;
125063         }
125064
125065         // If the targetNode is within the folder we are dragging
125066         for (i = 0; i < ln; i++) {
125067             record = draggedRecords[i];
125068             if (record.isNode && record.contains(targetNode)) {
125069                 return false;
125070             }
125071         }
125072         
125073         // Respect the allowDrop field on Tree nodes
125074         if (position === 'append' && targetNode.get('allowDrop') == false) {
125075             return false;
125076         }
125077         else if (position != 'append' && targetNode.parentNode.get('allowDrop') == false) {
125078             return false;
125079         }
125080
125081         // If the target record is in the dragged dataset, then invalid drop
125082         if (Ext.Array.contains(draggedRecords, targetNode)) {
125083              return false;
125084         }
125085
125086         // @TODO: fire some event to notify that there is a valid drop possible for the node you're dragging
125087         // Yes: this.fireViewEvent(blah....) fires an event through the owning View.
125088         return true;
125089     },
125090
125091     onNodeOver : function(node, dragZone, e, data) {
125092         var position = this.getPosition(e, node),
125093             returnCls = this.dropNotAllowed,
125094             view = this.view,
125095             targetNode = view.getRecord(node),
125096             indicator = this.getIndicator(),
125097             indicatorX = 0,
125098             indicatorY = 0;
125099
125100         // auto node expand check
125101         this.cancelExpand();
125102         if (position == 'append' && !this.expandProcId && !Ext.Array.contains(data.records, targetNode) && !targetNode.isLeaf() && !targetNode.isExpanded()) {
125103             this.queueExpand(targetNode);
125104         }
125105             
125106         if (this.isValidDropPoint(node, position, dragZone, e, data)) {
125107             this.valid = true;
125108             this.currentPosition = position;
125109             this.overRecord = targetNode;
125110
125111             indicator.setWidth(Ext.fly(node).getWidth());
125112             indicatorY = Ext.fly(node).getY() - Ext.fly(view.el).getY() - 1;
125113
125114             if (position == 'before') {
125115                 returnCls = targetNode.isFirst() ? Ext.baseCSSPrefix + 'tree-drop-ok-above' : Ext.baseCSSPrefix + 'tree-drop-ok-between';
125116                 indicator.showAt(0, indicatorY);
125117                 indicator.toFront();
125118             }
125119             else if (position == 'after') {
125120                 returnCls = targetNode.isLast() ? Ext.baseCSSPrefix + 'tree-drop-ok-below' : Ext.baseCSSPrefix + 'tree-drop-ok-between';
125121                 indicatorY += Ext.fly(node).getHeight();
125122                 indicator.showAt(0, indicatorY);
125123                 indicator.toFront();
125124             }
125125             else {
125126                 returnCls = Ext.baseCSSPrefix + 'tree-drop-ok-append';
125127                 // @TODO: set a class on the parent folder node to be able to style it
125128                 indicator.hide();
125129             }
125130         }
125131         else {
125132             this.valid = false;
125133         }
125134
125135         this.currentCls = returnCls;
125136         return returnCls;
125137     },
125138
125139     onContainerOver : function(dd, e, data) {
125140         return e.getTarget('.' + this.indicatorCls) ? this.currentCls : this.dropNotAllowed;
125141     },
125142     
125143     notifyOut: function() {
125144         this.callParent(arguments);
125145         this.cancelExpand();
125146     },
125147
125148     handleNodeDrop : function(data, targetNode, position) {
125149         var me = this,
125150             view = me.view,
125151             parentNode = targetNode.parentNode,
125152             store = view.getStore(),
125153             recordDomNodes = [],
125154             records, i, len,
125155             insertionMethod, argList,
125156             needTargetExpand,
125157             transferData,
125158             processDrop;
125159
125160         // If the copy flag is set, create a copy of the Models with the same IDs
125161         if (data.copy) {
125162             records = data.records;
125163             data.records = [];
125164             for (i = 0, len = records.length; i < len; i++) {
125165                 data.records.push(Ext.apply({}, records[i].data));
125166             }
125167         }
125168
125169         // Cancel any pending expand operation
125170         me.cancelExpand();
125171
125172         // Grab a reference to the correct node insertion method.
125173         // Create an arg list array intended for the apply method of the
125174         // chosen node insertion method.
125175         // Ensure the target object for the method is referenced by 'targetNode'
125176         if (position == 'before') {
125177             insertionMethod = parentNode.insertBefore;
125178             argList = [null, targetNode];
125179             targetNode = parentNode;
125180         }
125181         else if (position == 'after') {
125182             if (targetNode.nextSibling) {
125183                 insertionMethod = parentNode.insertBefore;
125184                 argList = [null, targetNode.nextSibling];
125185             }
125186             else {
125187                 insertionMethod = parentNode.appendChild;
125188                 argList = [null];
125189             }
125190             targetNode = parentNode;
125191         }
125192         else {
125193             if (!targetNode.isExpanded()) {
125194                 needTargetExpand = true;
125195             }
125196             insertionMethod = targetNode.appendChild;
125197             argList = [null];
125198         }
125199
125200         // A function to transfer the data into the destination tree
125201         transferData = function() {
125202             var node;
125203             for (i = 0, len = data.records.length; i < len; i++) {
125204                 argList[0] = data.records[i];
125205                 node = insertionMethod.apply(targetNode, argList);
125206                 
125207                 if (Ext.enableFx && me.dropHighlight) {
125208                     recordDomNodes.push(view.getNode(node));
125209                 }
125210             }
125211             
125212             // Kick off highlights after everything's been inserted, so they are
125213             // more in sync without insertion/render overhead.
125214             if (Ext.enableFx && me.dropHighlight) {
125215                 //FIXME: the check for n.firstChild is not a great solution here. Ideally the line should simply read 
125216                 //Ext.fly(n.firstChild) but this yields errors in IE6 and 7. See ticket EXTJSIV-1705 for more details
125217                 Ext.Array.forEach(recordDomNodes, function(n) {
125218                     Ext.fly(n.firstChild ? n.firstChild : n).highlight(me.dropHighlightColor);
125219                 });
125220             }
125221         };
125222
125223         // If dropping right on an unexpanded node, transfer the data after it is expanded.
125224         if (needTargetExpand) {
125225             targetNode.expand(false, transferData);
125226         }
125227         // Otherwise, call the data transfer function immediately
125228         else {
125229             transferData();
125230         }
125231     }
125232 });
125233 /**
125234  * @class Ext.tree.ViewDDPlugin
125235  * @extends Ext.AbstractPlugin
125236  * <p>This plugin provides drag and/or drop functionality for a TreeView.</p>
125237  * <p>It creates a specialized instance of {@link Ext.dd.DragZone DragZone} which knows how to drag out of a {@link Ext.tree.View TreeView}
125238  * and loads the data object which is passed to a cooperating {@link Ext.dd.DragZone DragZone}'s methods with the following properties:<ul>
125239  * <li>copy : Boolean
125240  *  <div class="sub-desc">The value of the TreeView's <code>copy</code> property, or <code>true</code> if the TreeView was configured
125241  *  with <code>allowCopy: true</code> <u>and</u> the control key was pressed when the drag operation was begun.</div></li>
125242  * <li>view : TreeView
125243  *  <div class="sub-desc">The source TreeView from which the drag originated.</div></li>
125244  * <li>ddel : HtmlElement
125245  *  <div class="sub-desc">The drag proxy element which moves with the mouse</div></li>
125246  * <li>item : HtmlElement
125247  *  <div class="sub-desc">The TreeView node upon which the mousedown event was registered.</div></li>
125248  * <li>records : Array
125249  *  <div class="sub-desc">An Array of {@link Ext.data.Model Model}s representing the selected data being dragged from the source TreeView.</div></li>
125250  * </ul></p>
125251  * <p>It also creates a specialized instance of {@link Ext.dd.DropZone} which cooperates with other DropZones which are members of the same
125252  * ddGroup which processes such data objects.</p>
125253  * <p>Adding this plugin to a view means that two new events may be fired from the client TreeView, <code>{@link #event-beforedrop beforedrop}</code> and
125254  * <code>{@link #event-drop drop}</code></p>
125255  */
125256 Ext.define('Ext.tree.plugin.TreeViewDragDrop', {
125257     extend: 'Ext.AbstractPlugin',
125258     alias: 'plugin.treeviewdragdrop',
125259
125260     uses: [
125261         'Ext.tree.ViewDragZone',
125262         'Ext.tree.ViewDropZone'
125263     ],
125264
125265     /**
125266      * @event beforedrop
125267      * <p><b>This event is fired through the TreeView. Add listeners to the TreeView object</b></p>
125268      * <p>Fired when a drop gesture has been triggered by a mouseup event in a valid drop position in the TreeView.
125269      * @param {HtmlElement} node The TreeView node <b>if any</b> over which the mouse was positioned.</p>
125270      * <p>Returning <code>false</code> to this event signals that the drop gesture was invalid, and if the drag proxy
125271      * will animate back to the point from which the drag began.</p>
125272      * <p>Returning <code>0</code> To this event signals that the data transfer operation should not take place, but
125273      * that the gesture was valid, and that the repair operation should not take place.</p>
125274      * <p>Any other return value continues with the data transfer operation.</p>
125275      * @param {Object} data The data object gathered at mousedown time by the cooperating {@link Ext.dd.DragZone DragZone}'s
125276      * {@link Ext.dd.DragZone#getDragData getDragData} method it contains the following properties:<ul>
125277      * <li>copy : Boolean
125278      *  <div class="sub-desc">The value of the TreeView's <code>copy</code> property, or <code>true</code> if the TreeView was configured
125279      *  with <code>allowCopy: true</code> and the control key was pressed when the drag operation was begun</div></li>
125280      * <li>view : TreeView
125281      *  <div class="sub-desc">The source TreeView from which the drag originated.</div></li>
125282      * <li>ddel : HtmlElement
125283      *  <div class="sub-desc">The drag proxy element which moves with the mouse</div></li>
125284      * <li>item : HtmlElement
125285      *  <div class="sub-desc">The TreeView node upon which the mousedown event was registered.</div></li>
125286      * <li>records : Array
125287      *  <div class="sub-desc">An Array of {@link Ext.data.Model Model}s representing the selected data being dragged from the source TreeView.</div></li>
125288      * </ul>
125289      * @param {Ext.data.Model} overModel The Model over which the drop gesture took place.
125290      * @param {String} dropPosition <code>"before"</code>, <code>"after"</code> or <code>"append"</code> depending on whether the mouse is above or below the midline of the node,
125291      * or the node is a branch node which accepts new child nodes.
125292      * @param {Function} dropFunction <p>A function to call to complete the data transfer operation and either move or copy Model instances from the source
125293      * View's Store to the destination View's Store.</p>
125294      * <p>This is useful when you want to perform some kind of asynchronous processing before confirming
125295      * the drop, such as an {@link Ext.window.MessageBox#confirm confirm} call, or an Ajax request.</p>
125296      * <p>Return <code>0</code> from this event handler, and call the <code>dropFunction</code> at any time to perform the data transfer.</p>
125297      */
125298
125299     /**
125300      * @event drop
125301      * <b>This event is fired through the TreeView. Add listeners to the TreeView object</b>
125302      * Fired when a drop operation has been completed and the data has been moved or copied.
125303      * @param {HtmlElement} node The TreeView node <b>if any</b> over which the mouse was positioned.
125304      * @param {Object} data The data object gathered at mousedown time by the cooperating {@link Ext.dd.DragZone DragZone}'s
125305      * {@link Ext.dd.DragZone#getDragData getDragData} method it contains the following properties:<ul>
125306      * <li>copy : Boolean
125307      *  <div class="sub-desc">The value of the TreeView's <code>copy</code> property, or <code>true</code> if the TreeView was configured
125308      *  with <code>allowCopy: true</code> and the control key was pressed when the drag operation was begun</div></li>
125309      * <li>view : TreeView
125310      *  <div class="sub-desc">The source TreeView from which the drag originated.</div></li>
125311      * <li>ddel : HtmlElement
125312      *  <div class="sub-desc">The drag proxy element which moves with the mouse</div></li>
125313      * <li>item : HtmlElement
125314      *  <div class="sub-desc">The TreeView node upon which the mousedown event was registered.</div></li>
125315      * <li>records : Array
125316      *  <div class="sub-desc">An Array of {@link Ext.data.Model Model}s representing the selected data being dragged from the source TreeView.</div></li>
125317      * </ul>
125318      * @param {Ext.data.Model} overModel The Model over which the drop gesture took place.
125319      * @param {String} dropPosition <code>"before"</code>, <code>"after"</code> or <code>"append"</code> depending on whether the mouse is above or below the midline of the node,
125320      * or the node is a branch node which accepts new child nodes.
125321      */
125322
125323     dragText : '{0} selected node{1}',
125324
125325     /**
125326      * @cfg {Boolean} allowParentInsert
125327      * Allow inserting a dragged node between an expanded parent node and its first child that will become a
125328      * sibling of the parent when dropped (defaults to false)
125329      */
125330     allowParentInserts: false,
125331
125332     /**
125333      * @cfg {String} allowContainerDrop
125334      * True if drops on the tree container (outside of a specific tree node) are allowed (defaults to false)
125335      */
125336     allowContainerDrops: false,
125337
125338     /**
125339      * @cfg {String} appendOnly
125340      * True if the tree should only allow append drops (use for trees which are sorted, defaults to false)
125341      */
125342     appendOnly: false,
125343
125344     /**
125345      * @cfg {String} ddGroup
125346      * A named drag drop group to which this object belongs.  If a group is specified, then both the DragZones and DropZone
125347      * used by this plugin will only interact with other drag drop objects in the same group (defaults to 'TreeDD').
125348      */
125349     ddGroup : "TreeDD",
125350
125351     /**
125352      * @cfg {String} dragGroup
125353      * <p>The ddGroup to which the DragZone will belong.</p>
125354      * <p>This defines which other DropZones the DragZone will interact with. Drag/DropZones only interact with other Drag/DropZones
125355      * which are members of the same ddGroup.</p>
125356      */
125357
125358     /**
125359      * @cfg {String} dropGroup
125360      * <p>The ddGroup to which the DropZone will belong.</p>
125361      * <p>This defines which other DragZones the DropZone will interact with. Drag/DropZones only interact with other Drag/DropZones
125362      * which are members of the same ddGroup.</p>
125363      */
125364
125365     /**
125366      * @cfg {String} expandDelay
125367      * The delay in milliseconds to wait before expanding a target tree node while dragging a droppable node
125368      * over the target (defaults to 1000)
125369      */
125370     expandDelay : 1000,
125371
125372     /**
125373      * @cfg {Boolean} enableDrop
125374      * <p>Defaults to <code>true</code></p>
125375      * <p>Set to <code>false</code> to disallow the View from accepting drop gestures</p>
125376      */
125377     enableDrop: true,
125378
125379     /**
125380      * @cfg {Boolean} enableDrag
125381      * <p>Defaults to <code>true</code></p>
125382      * <p>Set to <code>false</code> to disallow dragging items from the View </p>
125383      */
125384     enableDrag: true,
125385     
125386     /**
125387      * @cfg {String} nodeHighlightColor The color to use when visually highlighting the dragged
125388      * or dropped node (defaults to 'c3daf9' - light blue). The color must be a 6 digit hex value, without
125389      * a preceding '#'. See also {@link #nodeHighlightOnDrop} and {@link #nodeHighlightOnRepair}.
125390      */
125391     nodeHighlightColor: 'c3daf9',
125392     
125393     /**
125394      * @cfg {Boolean} nodeHighlightOnDrop Whether or not to highlight any nodes after they are
125395      * successfully dropped on their target. Defaults to the value of `Ext.enableFx`.
125396      * See also {@link #nodeHighlightColor} and {@link #nodeHighlightOnRepair}.
125397      * @markdown
125398      */
125399     nodeHighlightOnDrop: Ext.enableFx,
125400     
125401     /**
125402      * @cfg {Boolean} nodeHighlightOnRepair Whether or not to highlight any nodes after they are
125403      * repaired from an unsuccessful drag/drop. Defaults to the value of `Ext.enableFx`.
125404      * See also {@link #nodeHighlightColor} and {@link #nodeHighlightOnDrop}.
125405      * @markdown
125406      */
125407     nodeHighlightOnRepair: Ext.enableFx,
125408
125409     init : function(view) {
125410         view.on('render', this.onViewRender, this, {single: true});
125411     },
125412
125413     /**
125414      * @private
125415      * AbstractComponent calls destroy on all its plugins at destroy time.
125416      */
125417     destroy: function() {
125418         Ext.destroy(this.dragZone, this.dropZone);
125419     },
125420
125421     onViewRender : function(view) {
125422         var me = this;
125423
125424         if (me.enableDrag) {
125425             me.dragZone = Ext.create('Ext.tree.ViewDragZone', {
125426                 view: view,
125427                 ddGroup: me.dragGroup || me.ddGroup,
125428                 dragText: me.dragText,
125429                 repairHighlightColor: me.nodeHighlightColor,
125430                 repairHighlight: me.nodeHighlightOnRepair
125431             });
125432         }
125433
125434         if (me.enableDrop) {
125435             me.dropZone = Ext.create('Ext.tree.ViewDropZone', {
125436                 view: view,
125437                 ddGroup: me.dropGroup || me.ddGroup,
125438                 allowContainerDrops: me.allowContainerDrops,
125439                 appendOnly: me.appendOnly,
125440                 allowParentInserts: me.allowParentInserts,
125441                 expandDelay: me.expandDelay,
125442                 dropHighlightColor: me.nodeHighlightColor,
125443                 dropHighlight: me.nodeHighlightOnDrop
125444             });
125445         }
125446     }
125447 });
125448 /**
125449  * @class Ext.util.Cookies
125450
125451 Utility class for setting/reading values from browser cookies.
125452 Values can be written using the {@link #set} method.
125453 Values can be read using the {@link #get} method.
125454 A cookie can be invalidated on the client machine using the {@link #clear} method.
125455
125456  * @markdown
125457  * @singleton
125458  */
125459 Ext.define('Ext.util.Cookies', {
125460     singleton: true,
125461     
125462     /**
125463      * Create a cookie with the specified name and value. Additional settings
125464      * for the cookie may be optionally specified (for example: expiration,
125465      * access restriction, SSL).
125466      * @param {String} name The name of the cookie to set. 
125467      * @param {Mixed} value The value to set for the cookie.
125468      * @param {Object} expires (Optional) Specify an expiration date the
125469      * cookie is to persist until.  Note that the specified Date object will
125470      * be converted to Greenwich Mean Time (GMT). 
125471      * @param {String} path (Optional) Setting a path on the cookie restricts
125472      * access to pages that match that path. Defaults to all pages (<tt>'/'</tt>). 
125473      * @param {String} domain (Optional) Setting a domain restricts access to
125474      * pages on a given domain (typically used to allow cookie access across
125475      * subdomains). For example, "sencha.com" will create a cookie that can be
125476      * accessed from any subdomain of sencha.com, including www.sencha.com,
125477      * support.sencha.com, etc.
125478      * @param {Boolean} secure (Optional) Specify true to indicate that the cookie
125479      * should only be accessible via SSL on a page using the HTTPS protocol.
125480      * Defaults to <tt>false</tt>. Note that this will only work if the page
125481      * calling this code uses the HTTPS protocol, otherwise the cookie will be
125482      * created with default options.
125483      */
125484     set : function(name, value){
125485         var argv = arguments,
125486             argc = arguments.length,
125487             expires = (argc > 2) ? argv[2] : null,
125488             path = (argc > 3) ? argv[3] : '/',
125489             domain = (argc > 4) ? argv[4] : null,
125490             secure = (argc > 5) ? argv[5] : false;
125491             
125492         document.cookie = name + "=" + escape(value) + ((expires === null) ? "" : ("; expires=" + expires.toGMTString())) + ((path === null) ? "" : ("; path=" + path)) + ((domain === null) ? "" : ("; domain=" + domain)) + ((secure === true) ? "; secure" : "");
125493     },
125494
125495     /**
125496      * Retrieves cookies that are accessible by the current page. If a cookie
125497      * does not exist, <code>get()</code> returns <tt>null</tt>.  The following
125498      * example retrieves the cookie called "valid" and stores the String value
125499      * in the variable <tt>validStatus</tt>.
125500      * <pre><code>
125501      * var validStatus = Ext.util.Cookies.get("valid");
125502      * </code></pre>
125503      * @param {String} name The name of the cookie to get
125504      * @return {Mixed} Returns the cookie value for the specified name;
125505      * null if the cookie name does not exist.
125506      */
125507     get : function(name){
125508         var arg = name + "=",
125509             alen = arg.length,
125510             clen = document.cookie.length,
125511             i = 0,
125512             j = 0;
125513             
125514         while(i < clen){
125515             j = i + alen;
125516             if(document.cookie.substring(i, j) == arg){
125517                 return this.getCookieVal(j);
125518             }
125519             i = document.cookie.indexOf(" ", i) + 1;
125520             if(i === 0){
125521                 break;
125522             }
125523         }
125524         return null;
125525     },
125526
125527     /**
125528      * Removes a cookie with the provided name from the browser
125529      * if found by setting its expiration date to sometime in the past. 
125530      * @param {String} name The name of the cookie to remove
125531      * @param {String} path (optional) The path for the cookie. This must be included if you included a path while setting the cookie.
125532      */
125533     clear : function(name, path){
125534         if(this.get(name)){
125535             path = path || '/';
125536             document.cookie = name + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT; path=' + path;
125537         }
125538     },
125539     
125540     /**
125541      * @private
125542      */
125543     getCookieVal : function(offset){
125544         var endstr = document.cookie.indexOf(";", offset);
125545         if(endstr == -1){
125546             endstr = document.cookie.length;
125547         }
125548         return unescape(document.cookie.substring(offset, endstr));
125549     }
125550 });
125551
125552 /**
125553  * @class Ext.util.CSS
125554  * Utility class for manipulating CSS rules
125555  * @singleton
125556  */
125557 Ext.define('Ext.util.CSS', function() {
125558     var rules = null;
125559     var doc = document;
125560
125561     var camelRe = /(-[a-z])/gi;
125562     var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
125563
125564     return {
125565
125566         singleton: true,
125567
125568         constructor: function() {
125569             this.rules = {};
125570             this.initialized = false;
125571         },
125572  
125573         /**
125574          * Creates a stylesheet from a text blob of rules.
125575          * These rules will be wrapped in a STYLE tag and appended to the HEAD of the document.
125576          * @param {String} cssText The text containing the css rules
125577          * @param {String} id An id to add to the stylesheet for later removal
125578          * @return {StyleSheet}
125579          */
125580         createStyleSheet : function(cssText, id) {
125581             var ss,
125582                 head = doc.getElementsByTagName("head")[0],
125583                 styleEl = doc.createElement("style");
125584
125585             styleEl.setAttribute("type", "text/css");
125586             if (id) {
125587                styleEl.setAttribute("id", id);
125588             }
125589
125590             if (Ext.isIE) {
125591                head.appendChild(styleEl);
125592                ss = styleEl.styleSheet;
125593                ss.cssText = cssText;
125594             } else {
125595                 try{
125596                     styleEl.appendChild(doc.createTextNode(cssText));
125597                 } catch(e) {
125598                    styleEl.cssText = cssText;
125599                 }
125600                 head.appendChild(styleEl);
125601                 ss = styleEl.styleSheet ? styleEl.styleSheet : (styleEl.sheet || doc.styleSheets[doc.styleSheets.length-1]);
125602             }
125603             this.cacheStyleSheet(ss);
125604             return ss;
125605         },
125606
125607         /**
125608          * Removes a style or link tag by id
125609          * @param {String} id The id of the tag
125610          */
125611         removeStyleSheet : function(id) {
125612             var existing = document.getElementById(id);
125613             if (existing) {
125614                 existing.parentNode.removeChild(existing);
125615             }
125616         },
125617
125618         /**
125619          * Dynamically swaps an existing stylesheet reference for a new one
125620          * @param {String} id The id of an existing link tag to remove
125621          * @param {String} url The href of the new stylesheet to include
125622          */
125623         swapStyleSheet : function(id, url) {
125624             var doc = document;
125625             this.removeStyleSheet(id);
125626             var ss = doc.createElement("link");
125627             ss.setAttribute("rel", "stylesheet");
125628             ss.setAttribute("type", "text/css");
125629             ss.setAttribute("id", id);
125630             ss.setAttribute("href", url);
125631             doc.getElementsByTagName("head")[0].appendChild(ss);
125632         },
125633
125634         /**
125635          * Refresh the rule cache if you have dynamically added stylesheets
125636          * @return {Object} An object (hash) of rules indexed by selector
125637          */
125638         refreshCache : function() {
125639             return this.getRules(true);
125640         },
125641
125642         // private
125643         cacheStyleSheet : function(ss) {
125644             if(!rules){
125645                 rules = {};
125646             }
125647             try {// try catch for cross domain access issue
125648                 var ssRules = ss.cssRules || ss.rules,
125649                     selectorText,
125650                     i = ssRules.length - 1,
125651                     j,
125652                     selectors;
125653
125654                 for (; i >= 0; --i) {
125655                     selectorText = ssRules[i].selectorText;
125656                     if (selectorText) {
125657  
125658                         // Split in case there are multiple, comma-delimited selectors
125659                         selectorText = selectorText.split(',');
125660                         selectors = selectorText.length;
125661                         for (j = 0; j < selectors; j++) {
125662                             rules[Ext.String.trim(selectorText[j]).toLowerCase()] = ssRules[i];
125663                         }
125664                     }
125665                 }
125666             } catch(e) {}
125667         },
125668
125669         /**
125670         * Gets all css rules for the document
125671         * @param {Boolean} refreshCache true to refresh the internal cache
125672         * @return {Object} An object (hash) of rules indexed by selector
125673         */
125674         getRules : function(refreshCache) {
125675             if (rules === null || refreshCache) {
125676                 rules = {};
125677                 var ds = doc.styleSheets,
125678                     i = 0,
125679                     len = ds.length;
125680
125681                 for (; i < len; i++) {
125682                     try {
125683                         if (!ds[i].disabled) {
125684                             this.cacheStyleSheet(ds[i]);
125685                         }
125686                     } catch(e) {} 
125687                 }
125688             }
125689             return rules;
125690         },
125691
125692         /**
125693          * Gets an an individual CSS rule by selector(s)
125694          * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
125695          * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
125696          * @return {CSSRule} The CSS rule or null if one is not found
125697          */
125698         getRule: function(selector, refreshCache) {
125699             var rs = this.getRules(refreshCache);
125700             if (!Ext.isArray(selector)) {
125701                 return rs[selector.toLowerCase()];
125702             }
125703             for (var i = 0; i < selector.length; i++) {
125704                 if (rs[selector[i]]) {
125705                     return rs[selector[i].toLowerCase()];
125706                 }
125707             }
125708             return null;
125709         },
125710
125711         /**
125712          * Updates a rule property
125713          * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
125714          * @param {String} property The css property
125715          * @param {String} value The new value for the property
125716          * @return {Boolean} true If a rule was found and updated
125717          */
125718         updateRule : function(selector, property, value){
125719             if (!Ext.isArray(selector)) {
125720                 var rule = this.getRule(selector);
125721                 if (rule) {
125722                     rule.style[property.replace(camelRe, camelFn)] = value;
125723                     return true;
125724                 }
125725             } else {
125726                 for (var i = 0; i < selector.length; i++) {
125727                     if (this.updateRule(selector[i], property, value)) {
125728                         return true;
125729                     }
125730                 }
125731             }
125732             return false;
125733         }
125734     };
125735 }());
125736 /**
125737  * @class Ext.util.History
125738  * History management component that allows you to register arbitrary tokens that signify application
125739  * history state on navigation actions.  You can then handle the history {@link #change} event in order
125740  * to reset your application UI to the appropriate state when the user navigates forward or backward through
125741  * the browser history stack.
125742  * @singleton
125743  */
125744 Ext.define('Ext.util.History', {
125745     singleton: true,
125746     alternateClassName: 'Ext.History',
125747     mixins: {
125748         observable: 'Ext.util.Observable'
125749     },
125750     
125751     constructor: function() {
125752         var me = this;
125753         me.oldIEMode = Ext.isIE6 || Ext.isIE7 || !Ext.isStrict && Ext.isIE8;
125754         me.iframe = null;
125755         me.hiddenField = null;
125756         me.ready = false;
125757         me.currentToken = null;
125758     },
125759     
125760     getHash: function() {
125761         var href = window.location.href,
125762             i = href.indexOf("#");
125763             
125764         return i >= 0 ? href.substr(i + 1) : null;
125765     },
125766
125767     doSave: function() {
125768         this.hiddenField.value = this.currentToken;
125769     },
125770     
125771
125772     handleStateChange: function(token) {
125773         this.currentToken = token;
125774         this.fireEvent('change', token);
125775     },
125776
125777     updateIFrame: function(token) {
125778         var html = '<html><body><div id="state">' + 
125779                     Ext.util.Format.htmlEncode(token) + 
125780                     '</div></body></html>';
125781
125782         try {
125783             var doc = this.iframe.contentWindow.document;
125784             doc.open();
125785             doc.write(html);
125786             doc.close();
125787             return true;
125788         } catch (e) {
125789             return false;
125790         }
125791     },
125792
125793     checkIFrame: function () {
125794         var me = this,
125795             contentWindow = me.iframe.contentWindow;
125796             
125797         if (!contentWindow || !contentWindow.document) {
125798             Ext.Function.defer(this.checkIFrame, 10, this);
125799             return;
125800         }
125801        
125802         var doc = contentWindow.document,
125803             elem = doc.getElementById("state"),
125804             oldToken = elem ? elem.innerText : null,
125805             oldHash = me.getHash();
125806            
125807         Ext.TaskManager.start({
125808             run: function () {
125809                 var doc = contentWindow.document,
125810                     elem = doc.getElementById("state"),
125811                     newToken = elem ? elem.innerText : null,
125812                     newHash = me.getHash();
125813
125814                 if (newToken !== oldToken) {
125815                     oldToken = newToken;
125816                     me.handleStateChange(newToken);
125817                     window.top.location.hash = newToken;
125818                     oldHash = newToken;
125819                     me.doSave();
125820                 } else if (newHash !== oldHash) {
125821                     oldHash = newHash;
125822                     me.updateIFrame(newHash);
125823                 }
125824             }, 
125825             interval: 50,
125826             scope: me
125827         });
125828         me.ready = true;
125829         me.fireEvent('ready', me);            
125830     },
125831
125832     startUp: function () {
125833         var me = this;
125834         
125835         me.currentToken = me.hiddenField.value || this.getHash();
125836
125837         if (me.oldIEMode) {
125838             me.checkIFrame();
125839         } else {
125840             var hash = me.getHash();
125841             Ext.TaskManager.start({
125842                 run: function () {
125843                     var newHash = me.getHash();
125844                     if (newHash !== hash) {
125845                         hash = newHash;
125846                         me.handleStateChange(hash);
125847                         me.doSave();
125848                     }
125849                 },
125850                 interval: 50,
125851                 scope: me
125852             });
125853             me.ready = true;
125854             me.fireEvent('ready', me);
125855         }
125856         
125857     },
125858
125859     /**
125860      * The id of the hidden field required for storing the current history token.
125861      * @type String
125862      * @property
125863      */
125864     fieldId: Ext.baseCSSPrefix + 'history-field',
125865     /**
125866      * The id of the iframe required by IE to manage the history stack.
125867      * @type String
125868      * @property
125869      */
125870     iframeId: Ext.baseCSSPrefix + 'history-frame',
125871
125872     /**
125873      * Initialize the global History instance.
125874      * @param {Boolean} onReady (optional) A callback function that will be called once the history
125875      * component is fully initialized.
125876      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser window.
125877      */
125878     init: function (onReady, scope) {
125879         var me = this;
125880         
125881         if (me.ready) {
125882             Ext.callback(onReady, scope, [me]);
125883             return;
125884         }
125885         
125886         if (!Ext.isReady) {
125887             Ext.onReady(function() {
125888                 me.init(onReady, scope);
125889             });
125890             return;
125891         }
125892         
125893         me.hiddenField = Ext.getDom(me.fieldId);
125894         
125895         if (me.oldIEMode) {
125896             me.iframe = Ext.getDom(me.iframeId);
125897         }
125898         
125899         me.addEvents(
125900             /**
125901              * @event ready
125902              * Fires when the Ext.util.History singleton has been initialized and is ready for use.
125903              * @param {Ext.util.History} The Ext.util.History singleton.
125904              */
125905             'ready',
125906             /**
125907              * @event change
125908              * Fires when navigation back or forwards within the local page's history occurs.
125909              * @param {String} token An identifier associated with the page state at that point in its history.
125910              */
125911             'change'
125912         );
125913         
125914         if (onReady) {
125915             me.on('ready', onReady, scope, {single: true});
125916         }
125917         me.startUp();
125918     },
125919
125920     /**
125921      * Add a new token to the history stack. This can be any arbitrary value, although it would
125922      * commonly be the concatenation of a component id and another id marking the specifc history
125923      * state of that component.  Example usage:
125924      * <pre><code>
125925 // Handle tab changes on a TabPanel
125926 tabPanel.on('tabchange', function(tabPanel, tab){
125927 Ext.History.add(tabPanel.id + ':' + tab.id);
125928 });
125929 </code></pre>
125930      * @param {String} token The value that defines a particular application-specific history state
125931      * @param {Boolean} preventDuplicates When true, if the passed token matches the current token
125932      * it will not save a new history step. Set to false if the same state can be saved more than once
125933      * at the same history stack location (defaults to true).
125934      */
125935     add: function (token, preventDup) {
125936         var me = this;
125937         
125938         if (preventDup !== false) {
125939             if (me.getToken() === token) {
125940                 return true;
125941             }
125942         }
125943         
125944         if (me.oldIEMode) {
125945             return me.updateIFrame(token);
125946         } else {
125947             window.top.location.hash = token;
125948             return true;
125949         }
125950     },
125951
125952     /**
125953      * Programmatically steps back one step in browser history (equivalent to the user pressing the Back button).
125954      */
125955     back: function() {
125956         window.history.go(-1);
125957     },
125958
125959     /**
125960      * Programmatically steps forward one step in browser history (equivalent to the user pressing the Forward button).
125961      */
125962     forward: function(){
125963         window.history.go(1);
125964     },
125965
125966     /**
125967      * Retrieves the currently-active history token.
125968      * @return {String} The token
125969      */
125970     getToken: function() {
125971         return this.ready ? this.currentToken : this.getHash();
125972     }
125973 });
125974 /**
125975  * @class Ext.view.TableChunker
125976  * 
125977  * Produces optimized XTemplates for chunks of tables to be
125978  * used in grids, trees and other table based widgets.
125979  *
125980  * @singleton
125981  */
125982 Ext.define('Ext.view.TableChunker', {
125983     singleton: true,
125984     requires: ['Ext.XTemplate'],
125985     metaTableTpl: [
125986         '{[this.openTableWrap()]}',
125987         '<table class="' + Ext.baseCSSPrefix + 'grid-table ' + Ext.baseCSSPrefix + 'grid-table-resizer" border="0" cellspacing="0" cellpadding="0" {[this.embedFullWidth()]}>',
125988             '<tbody>',
125989             '<tr>',
125990             '<tpl for="columns">',
125991                 '<th class="' + Ext.baseCSSPrefix + 'grid-col-resizer-{id}" style="width: {width}px; height: 0px;"></th>',
125992             '</tpl>',
125993             '</tr>',
125994             '{[this.openRows()]}',
125995                 '{row}',
125996                 '<tpl for="features">',
125997                     '{[this.embedFeature(values, parent, xindex, xcount)]}',
125998                 '</tpl>',
125999             '{[this.closeRows()]}',
126000             '</tbody>',
126001         '</table>',
126002         '{[this.closeTableWrap()]}'
126003     ],
126004
126005     constructor: function() {
126006         Ext.XTemplate.prototype.recurse = function(values, reference) {
126007             return this.apply(reference ? values[reference] : values);
126008         };
126009     },
126010
126011     embedFeature: function(values, parent, x, xcount) {
126012         var tpl = '';
126013         if (!values.disabled) {
126014             tpl = values.getFeatureTpl(values, parent, x, xcount);
126015         }
126016         return tpl;
126017     },
126018
126019     embedFullWidth: function() {
126020         return 'style="width: {fullWidth}px;"';
126021     },
126022
126023     openRows: function() {
126024         return '<tpl for="rows">';
126025     },
126026
126027     closeRows: function() {
126028         return '</tpl>';
126029     },
126030
126031     metaRowTpl: [
126032         '<tr class="' + Ext.baseCSSPrefix + 'grid-row {addlSelector} {[this.embedRowCls()]}" {[this.embedRowAttr()]}>',
126033             '<tpl for="columns">',
126034                 '<td class="{cls} ' + Ext.baseCSSPrefix + 'grid-cell ' + Ext.baseCSSPrefix + 'grid-cell-{columnId} {{id}-modified} {{id}-tdCls} {[this.firstOrLastCls(xindex, xcount)]}" {{id}-tdAttr}><div unselectable="on" class="' + Ext.baseCSSPrefix + 'grid-cell-inner ' + Ext.baseCSSPrefix + 'unselectable" style="{{id}-style}; text-align: {align};">{{id}}</div></td>',
126035             '</tpl>',
126036         '</tr>'
126037     ],
126038     
126039     firstOrLastCls: function(xindex, xcount) {
126040         var cssCls = '';
126041         if (xindex === 1) {
126042             cssCls = Ext.baseCSSPrefix + 'grid-cell-first';
126043         } else if (xindex === xcount) {
126044             cssCls = Ext.baseCSSPrefix + 'grid-cell-last';
126045         }
126046         return cssCls;
126047     },
126048     
126049     embedRowCls: function() {
126050         return '{rowCls}';
126051     },
126052     
126053     embedRowAttr: function() {
126054         return '{rowAttr}';
126055     },
126056     
126057     openTableWrap: function() {
126058         return '';
126059     },
126060     
126061     closeTableWrap: function() {
126062         return '';
126063     },
126064
126065     getTableTpl: function(cfg, textOnly) {
126066         var tpl,
126067             tableTplMemberFns = {
126068                 openRows: this.openRows,
126069                 closeRows: this.closeRows,
126070                 embedFeature: this.embedFeature,
126071                 embedFullWidth: this.embedFullWidth,
126072                 openTableWrap: this.openTableWrap,
126073                 closeTableWrap: this.closeTableWrap
126074             },
126075             tplMemberFns = {},
126076             features = cfg.features || [],
126077             ln = features.length,
126078             i  = 0,
126079             memberFns = {
126080                 embedRowCls: this.embedRowCls,
126081                 embedRowAttr: this.embedRowAttr,
126082                 firstOrLastCls: this.firstOrLastCls
126083             },
126084             // copy the default
126085             metaRowTpl = Array.prototype.slice.call(this.metaRowTpl, 0),
126086             metaTableTpl;
126087             
126088         for (; i < ln; i++) {
126089             if (!features[i].disabled) {
126090                 features[i].mutateMetaRowTpl(metaRowTpl);
126091                 Ext.apply(memberFns, features[i].getMetaRowTplFragments());
126092                 Ext.apply(tplMemberFns, features[i].getFragmentTpl());
126093                 Ext.apply(tableTplMemberFns, features[i].getTableFragments());
126094             }
126095         }
126096         
126097         metaRowTpl = Ext.create('Ext.XTemplate', metaRowTpl.join(''), memberFns);
126098         cfg.row = metaRowTpl.applyTemplate(cfg);
126099         
126100         metaTableTpl = Ext.create('Ext.XTemplate', this.metaTableTpl.join(''), tableTplMemberFns);
126101         
126102         tpl = metaTableTpl.applyTemplate(cfg);
126103         
126104         // TODO: Investigate eliminating.
126105         if (!textOnly) {
126106             tpl = Ext.create('Ext.XTemplate', tpl, tplMemberFns);
126107         }
126108         return tpl;
126109         
126110     }
126111 });
126112
126113
126114
126115 })(this.Ext4 || (this.Ext4 = {}));
126116
126117