3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
8 window.undefined = window.undefined;
12 * Ext core utilities and functions.
18 * The version of the framework
30 * Copies all the properties of config to obj.
31 * @param {Object} obj The receiver of the properties
32 * @param {Object} config The source of the properties
33 * @param {Object} defaults A different object that will also be applied for default values
34 * @return {Object} returns obj
37 Ext.apply = function(o, c, defaults){
38 // no "this" reference for friendly out of scope calls
40 Ext.apply(o, defaults);
42 if(o && c && typeof c == 'object'){
52 toString = Object.prototype.toString,
53 ua = navigator.userAgent.toLowerCase(),
58 isStrict = DOC.compatMode == "CSS1Compat",
59 isOpera = check(/opera/),
60 isChrome = check(/\bchrome\b/),
61 isWebKit = check(/webkit/),
62 isSafari = !isChrome && check(/safari/),
63 isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
64 isSafari3 = isSafari && check(/version\/3/),
65 isSafari4 = isSafari && check(/version\/4/),
66 isIE = !isOpera && check(/msie/),
67 isIE7 = isIE && check(/msie 7/),
68 isIE8 = isIE && check(/msie 8/),
69 isIE6 = isIE && !isIE7 && !isIE8,
70 isGecko = !isWebKit && check(/gecko/),
71 isGecko2 = isGecko && check(/rv:1\.8/),
72 isGecko3 = isGecko && check(/rv:1\.9/),
73 isBorderBox = isIE && !isStrict,
74 isWindows = check(/windows|win32/),
75 isMac = check(/macintosh|mac os x/),
76 isAir = check(/adobeair/),
77 isLinux = check(/linux/),
78 isSecure = /^https/i.test(window.location.protocol);
80 // remove css image flicker
83 DOC.execCommand("BackgroundImageCache", false, true);
89 * URL to a blank file used by Ext when in secure mode for iframe src and onReady src to prevent
90 * the IE insecure content warning (<tt>'about:blank'</tt>, except for IE in secure mode, which is <tt>'javascript:""'</tt>).
93 SSL_SECURE_URL : isSecure && isIE ? 'javascript:""' : 'about:blank',
95 * True if the browser is in strict (standards-compliant) mode, as opposed to quirks mode
100 * True if the page is running over SSL
105 * True when the document is fully initialized and ready for action
111 * True if the {@link Ext.Fx} Class is available
117 * True to automatically uncache orphaned Ext.Elements periodically (defaults to true)
120 enableGarbageCollector : true,
123 * True to automatically purge event listeners during garbageCollection (defaults to false).
126 enableListenerCollection : false,
129 * EXPERIMENTAL - True to cascade listener removal to child elements when an element is removed.
130 * Currently not optimized for performance.
133 enableNestedListenerRemoval : false,
136 * Indicates whether to use native browser parsing for JSON methods.
137 * This option is ignored if the browser does not support native JSON methods.
138 * <b>Note: Native JSON methods will not work with objects that have functions.
139 * Also, property names must be quoted, otherwise the data will not parse.</b> (Defaults to false)
142 USE_NATIVE_JSON : false,
145 * Copies all the properties of config to obj if they don't already exist.
146 * @param {Object} obj The receiver of the properties
147 * @param {Object} config The source of the properties
148 * @return {Object} returns obj
150 applyIf : function(o, c){
153 if(!Ext.isDefined(o[p])){
162 * Generates unique ids. If the element already has an id, it is unchanged
163 * @param {Mixed} el (optional) The element to generate an id for
164 * @param {String} prefix (optional) Id prefix (defaults "ext-gen")
165 * @return {String} The generated Id.
167 id : function(el, prefix){
168 el = Ext.getDom(el, true) || {};
170 el.id = (prefix || "ext-gen") + (++idSeed);
176 * <p>Extends one class to create a subclass and optionally overrides members with the passed literal. This method
177 * also adds the function "override()" to the subclass that can be used to override members of the class.</p>
178 * For example, to create a subclass of Ext GridPanel:
180 MyGridPanel = Ext.extend(Ext.grid.GridPanel, {
181 constructor: function(config) {
183 // Create configuration for this Grid.
184 var store = new Ext.data.Store({...});
185 var colModel = new Ext.grid.ColumnModel({...});
187 // Create a new config object containing our computed properties
188 // *plus* whatever was in the config parameter.
194 MyGridPanel.superclass.constructor.call(this, config);
196 // Your postprocessing here
199 yourMethod: function() {
205 * <p>This function also supports a 3-argument call in which the subclass's constructor is
206 * passed as an argument. In this form, the parameters are as follows:</p>
207 * <div class="mdetail-params"><ul>
208 * <li><code>subclass</code> : Function <div class="sub-desc">The subclass constructor.</div></li>
209 * <li><code>superclass</code> : Function <div class="sub-desc">The constructor of class being extended</div></li>
210 * <li><code>overrides</code> : Object <div class="sub-desc">A literal with members which are copied into the subclass's
211 * prototype, and are therefore shared among all instances of the new class.</div></li>
214 * @param {Function} superclass The constructor of class being extended.
215 * @param {Object} overrides <p>A literal with members which are copied into the subclass's
216 * prototype, and are therefore shared between all instances of the new class.</p>
217 * <p>This may contain a special member named <tt><b>constructor</b></tt>. This is used
218 * to define the constructor of the new class, and is returned. If this property is
219 * <i>not</i> specified, a constructor is generated and returned which just calls the
220 * superclass's constructor passing on its parameters.</p>
221 * <p><b>It is essential that you call the superclass constructor in any provided constructor. See example code.</b></p>
222 * @return {Function} The subclass constructor from the <code>overrides</code> parameter, or a generated one if not provided.
226 var io = function(o){
231 var oc = Object.prototype.constructor;
233 return function(sb, sp, overrides){
234 if(typeof sp == 'object'){
237 sb = overrides.constructor != oc ? overrides.constructor : function(){sp.apply(this, arguments);};
239 var F = function(){},
244 sbp = sb.prototype = new F();
247 if(spp.constructor == oc){
250 sb.override = function(o){
253 sbp.superclass = sbp.supr = (function(){
257 Ext.override(sb, overrides);
258 sb.extend = function(o){return Ext.extend(sb, o);};
264 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
266 Ext.override(MyClass, {
267 newMethod1: function(){
270 newMethod2: function(foo){
275 * @param {Object} origclass The class to override
276 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
277 * containing one or more methods.
280 override : function(origclass, overrides){
282 var p = origclass.prototype;
283 Ext.apply(p, overrides);
284 if(Ext.isIE && overrides.hasOwnProperty('toString')){
285 p.toString = overrides.toString;
291 * Creates namespaces to be used for scoping variables and classes so that they are not global.
292 * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
294 Ext.namespace('Company', 'Company.data');
295 Ext.namespace('Company.data'); // equivalent and preferable to above syntax
296 Company.Widget = function() { ... }
297 Company.data.CustomStore = function(config) { ... }
299 * @param {String} namespace1
300 * @param {String} namespace2
301 * @param {String} etc
302 * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
305 namespace : function(){
307 Ext.each(arguments, function(v) {
309 o = window[d[0]] = window[d[0]] || {};
310 Ext.each(d.slice(1), function(v2){
311 o = o[v2] = o[v2] || {};
318 * Takes an object and converts it to an encoded URL. e.g. Ext.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2". Optionally, property values can be arrays, instead of keys and the resulting string that's returned will contain a name/value pair for each array value.
320 * @param {String} pre (optional) A prefix to add to the url encoded string
323 urlEncode : function(o, pre){
326 e = encodeURIComponent;
328 Ext.iterate(o, function(key, item){
329 empty = Ext.isEmpty(item);
330 Ext.each(empty ? key : item, function(val){
331 buf.push('&', e(key), '=', (!Ext.isEmpty(val) && (val != key || !empty)) ? (Ext.isDate(val) ? Ext.encode(val).replace(/"/g, '') : e(val)) : '');
338 return pre + buf.join('');
342 * Takes an encoded URL and and converts it to an object. Example: <pre><code>
343 Ext.urlDecode("foo=1&bar=2"); // returns {foo: "1", bar: "2"}
344 Ext.urlDecode("foo=1&bar=2&bar=3&bar=4", false); // returns {foo: "1", bar: ["2", "3", "4"]}
346 * @param {String} string
347 * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
348 * @return {Object} A literal with members
350 urlDecode : function(string, overwrite){
351 if(Ext.isEmpty(string)){
355 pairs = string.split('&'),
356 d = decodeURIComponent,
359 Ext.each(pairs, function(pair) {
360 pair = pair.split('=');
363 obj[name] = overwrite || !obj[name] ? value :
364 [].concat(obj[name]).concat(value);
370 * Appends content to the query string of a URL, handling logic for whether to place
371 * a question mark or ampersand.
372 * @param {String} url The URL to append to.
373 * @param {String} s The content to append to the URL.
374 * @return (String) The resulting URL
376 urlAppend : function(url, s){
378 return url + (url.indexOf('?') === -1 ? '?' : '&') + s;
384 * Converts any iterable (numeric indices and a length property) into a true array
385 * Don't use this on strings. IE doesn't support "abc"[0] which this implementation depends on.
386 * For strings, use this instead: "abc".match(/./g) => [a,b,c];
387 * @param {Iterable} the iterable object to be turned into a true Array.
388 * @return (Array) array
390 toArray : function(){
392 function(a, i, j, res){
394 for(var x = 0, len = a.length; x < len; x++) {
397 return res.slice(i || 0, j || res.length);
400 return Array.prototype.slice.call(a, i || 0, j || a.length);
404 isIterable : function(v){
405 //check for array or arguments
406 if(Ext.isArray(v) || v.callee){
409 //check for node list type
410 if(/NodeList|HTMLCollection/.test(toString.call(v))){
413 //NodeList has an item and length property
414 //IXMLDOMNodeList has nextNode method, needs to be checked first.
415 return ((typeof v.nextNode != 'undefined' || v.item) && Ext.isNumber(v.length));
419 * Iterates an array calling the supplied function.
420 * @param {Array/NodeList/Mixed} array The array to be iterated. If this
421 * argument is not really an array, the supplied function is called once.
422 * @param {Function} fn The function to be called with each item. If the
423 * supplied function returns false, iteration stops and this method returns
424 * the current <code>index</code>. This function is called with
425 * the following arguments:
426 * <div class="mdetail-params"><ul>
427 * <li><code>item</code> : <i>Mixed</i>
428 * <div class="sub-desc">The item at the current <code>index</code>
429 * in the passed <code>array</code></div></li>
430 * <li><code>index</code> : <i>Number</i>
431 * <div class="sub-desc">The current index within the array</div></li>
432 * <li><code>allItems</code> : <i>Array</i>
433 * <div class="sub-desc">The <code>array</code> passed as the first
434 * argument to <code>Ext.each</code>.</div></li>
436 * @param {Object} scope The scope (<code>this</code> reference) in which the specified function is executed.
437 * Defaults to the <code>item</code> at the current <code>index</code>
438 * within the passed <code>array</code>.
439 * @return See description for the fn parameter.
441 each : function(array, fn, scope){
442 if(Ext.isEmpty(array, true)){
445 if(!Ext.isIterable(array) || Ext.isPrimitive(array)){
448 for(var i = 0, len = array.length; i < len; i++){
449 if(fn.call(scope || array[i], array[i], i, array) === false){
456 * Iterates either the elements in an array, or each of the properties in an object.
457 * <b>Note</b>: If you are only iterating arrays, it is better to call {@link #each}.
458 * @param {Object/Array} object The object or array to be iterated
459 * @param {Function} fn The function to be called for each iteration.
460 * The iteration will stop if the supplied function returns false, or
461 * all array elements / object properties have been covered. The signature
462 * varies depending on the type of object being interated:
463 * <div class="mdetail-params"><ul>
464 * <li>Arrays : <tt>(Object item, Number index, Array allItems)</tt>
465 * <div class="sub-desc">
466 * When iterating an array, the supplied function is called with each item.</div></li>
467 * <li>Objects : <tt>(String key, Object value, Object)</tt>
468 * <div class="sub-desc">
469 * When iterating an object, the supplied function is called with each key-value pair in
470 * the object, and the iterated object</div></li>
472 * @param {Object} scope The scope (<code>this</code> reference) in which the specified function is executed. Defaults to
473 * the <code>object</code> being iterated.
475 iterate : function(obj, fn, scope){
476 if(Ext.isEmpty(obj)){
479 if(Ext.isIterable(obj)){
480 Ext.each(obj, fn, scope);
482 }else if(typeof obj == 'object'){
483 for(var prop in obj){
484 if(obj.hasOwnProperty(prop)){
485 if(fn.call(scope || obj, prop, obj[prop], obj) === false){
494 * Return the dom node for the passed String (id), dom node, or Ext.Element.
495 * Optional 'strict' flag is needed for IE since it can return 'name' and
496 * 'id' elements by using getElementById.
497 * Here are some examples:
499 // gets dom node based on id
500 var elDom = Ext.getDom('elId');
501 // gets dom node based on the dom node
502 var elDom1 = Ext.getDom(elDom);
504 // If we don't know if we are working with an
505 // Ext.Element or a dom node use Ext.getDom
507 var dom = Ext.getDom(el);
508 // do something with the dom node
511 * <b>Note</b>: the dom node to be found actually needs to exist (be rendered, etc)
512 * when this method is called to be successful.
514 * @return HTMLElement
516 getDom : function(el, strict){
523 if (typeof el == 'string') {
524 var e = DOC.getElementById(el);
525 // IE returns elements with the 'name' and 'id' attribute.
526 // we do a strict check to return the element with only the id attribute
527 if (e && isIE && strict) {
528 if (el == e.getAttribute('id')) {
542 * Returns the current document body as an {@link Ext.Element}.
543 * @return Ext.Element The document body
545 getBody : function(){
546 return Ext.get(DOC.body || DOC.documentElement);
550 * Returns the current document body as an {@link Ext.Element}.
551 * @return Ext.Element The document body
553 getHead : function() {
557 if (head == undefined) {
558 head = Ext.get(DOC.getElementsByTagName("head")[0]);
566 * Removes a DOM node from the document.
569 * <p>Removes this element from the document, removes all DOM event listeners, and deletes the cache reference.
570 * All DOM event listeners are removed from this element. If {@link Ext#enableNestedListenerRemoval} is
571 * <code>true</code>, then DOM event listeners are also removed from all child nodes. The body node
572 * will be ignored if passed in.</p>
573 * @param {HTMLElement} node The node to remove
575 removeNode : isIE && !isIE8 ? function(){
578 if(n && n.tagName != 'BODY'){
579 (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n, true) : Ext.EventManager.removeAll(n);
580 d = d || DOC.createElement('div');
583 delete Ext.elCache[n.id];
587 if(n && n.parentNode && n.tagName != 'BODY'){
588 (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n, true) : Ext.EventManager.removeAll(n);
589 n.parentNode.removeChild(n);
590 delete Ext.elCache[n.id];
595 * <p>Returns true if the passed value is empty.</p>
596 * <p>The value is deemed to be empty if it is<div class="mdetail-params"><ul>
599 * <li>an empty array</li>
600 * <li>a zero length string (Unless the <tt>allowBlank</tt> parameter is <tt>true</tt>)</li>
602 * @param {Mixed} value The value to test
603 * @param {Boolean} allowBlank (optional) true to allow empty strings (defaults to false)
606 isEmpty : function(v, allowBlank){
607 return v === null || v === undefined || ((Ext.isArray(v) && !v.length)) || (!allowBlank ? v === '' : false);
611 * Returns true if the passed value is a JavaScript array, otherwise false.
612 * @param {Mixed} value The value to test
615 isArray : function(v){
616 return toString.apply(v) === '[object Array]';
620 * Returns true if the passed object is a JavaScript date object, otherwise false.
621 * @param {Object} object The object to test
624 isDate : function(v){
625 return toString.apply(v) === '[object Date]';
629 * Returns true if the passed value is a JavaScript Object, otherwise false.
630 * @param {Mixed} value The value to test
633 isObject : function(v){
634 return !!v && Object.prototype.toString.call(v) === '[object Object]';
638 * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
639 * @param {Mixed} value The value to test
642 isPrimitive : function(v){
643 return Ext.isString(v) || Ext.isNumber(v) || Ext.isBoolean(v);
647 * Returns true if the passed value is a JavaScript Function, otherwise false.
648 * @param {Mixed} value The value to test
651 isFunction : function(v){
652 return toString.apply(v) === '[object Function]';
656 * Returns true if the passed value is a number. Returns false for non-finite numbers.
657 * @param {Mixed} value The value to test
660 isNumber : function(v){
661 return typeof v === 'number' && isFinite(v);
665 * Returns true if the passed value is a string.
666 * @param {Mixed} value The value to test
669 isString : function(v){
670 return typeof v === 'string';
674 * Returns true if the passed value is a boolean.
675 * @param {Mixed} value The value to test
678 isBoolean : function(v){
679 return typeof v === 'boolean';
683 * Returns true if the passed value is an HTMLElement
684 * @param {Mixed} value The value to test
687 isElement : function(v) {
688 return v ? !!v.tagName : false;
692 * Returns true if the passed value is not undefined.
693 * @param {Mixed} value The value to test
696 isDefined : function(v){
697 return typeof v !== 'undefined';
701 * True if the detected browser is Opera.
706 * True if the detected browser uses WebKit.
711 * True if the detected browser is Chrome.
716 * True if the detected browser is Safari.
721 * True if the detected browser is Safari 3.x.
724 isSafari3 : isSafari3,
726 * True if the detected browser is Safari 4.x.
729 isSafari4 : isSafari4,
731 * True if the detected browser is Safari 2.x.
734 isSafari2 : isSafari2,
736 * True if the detected browser is Internet Explorer.
741 * True if the detected browser is Internet Explorer 6.x.
746 * True if the detected browser is Internet Explorer 7.x.
751 * True if the detected browser is Internet Explorer 8.x.
756 * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
761 * True if the detected browser uses a pre-Gecko 1.9 layout engine (e.g. Firefox 2.x).
766 * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
771 * True if the detected browser is Internet Explorer running in non-strict mode.
774 isBorderBox : isBorderBox,
776 * True if the detected platform is Linux.
781 * True if the detected platform is Windows.
784 isWindows : isWindows,
786 * True if the detected platform is Mac OS.
791 * True if the detected platform is Adobe Air.
798 * Creates namespaces to be used for scoping variables and classes so that they are not global.
799 * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
801 Ext.namespace('Company', 'Company.data');
802 Ext.namespace('Company.data'); // equivalent and preferable to above syntax
803 Company.Widget = function() { ... }
804 Company.data.CustomStore = function(config) { ... }
806 * @param {String} namespace1
807 * @param {String} namespace2
808 * @param {String} etc
809 * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
812 Ext.ns = Ext.namespace;
815 Ext.ns("Ext.util", "Ext.lib", "Ext.data");
821 * These functions are available on every Function object (any JavaScript function).
823 Ext.apply(Function.prototype, {
825 * Creates an interceptor function. The passed function is called before the original one. If it returns false,
826 * the original one is not called. The resulting function returns the results of the original function.
827 * The passed function is called with the parameters of the original function. Example usage:
829 var sayHi = function(name){
830 alert('Hi, ' + name);
833 sayHi('Fred'); // alerts "Hi, Fred"
835 // create a new function that validates input without
836 // directly modifying the original function:
837 var sayHiToFriend = sayHi.createInterceptor(function(name){
838 return name == 'Brian';
841 sayHiToFriend('Fred'); // no alert
842 sayHiToFriend('Brian'); // alerts "Hi, Brian"
844 * @param {Function} fcn The function to call before the original
845 * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed.
846 * <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b>
847 * @return {Function} The new function
849 createInterceptor : function(fcn, scope){
851 return !Ext.isFunction(fcn) ?
858 return (fcn.apply(scope || me || window, args) !== false) ?
859 method.apply(me || window, args) :
865 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
866 * Call directly on any function. Example: <code>myFunction.createCallback(arg1, arg2)</code>
867 * Will create a function that is bound to those 2 args. <b>If a specific scope is required in the
868 * callback, use {@link #createDelegate} instead.</b> The function returned by createCallback always
869 * executes in the window scope.
870 * <p>This method is required when you want to pass arguments to a callback function. If no arguments
871 * are needed, you can simply pass a reference to the function as a callback (e.g., callback: myFn).
872 * However, if you tried to pass a function with arguments (e.g., callback: myFn(arg1, arg2)) the function
873 * would simply execute immediately when the code is parsed. Example usage:
875 var sayHi = function(name){
876 alert('Hi, ' + name);
879 // clicking the button alerts "Hi, Fred"
882 renderTo: Ext.getBody(),
883 handler: sayHi.createCallback('Fred')
886 * @return {Function} The new function
888 createCallback : function(/*args...*/){
889 // make args available, in function below
890 var args = arguments,
893 return method.apply(window, args);
898 * Creates a delegate (callback) that sets the scope to obj.
899 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this, [arg1, arg2])</code>
900 * Will create a function that is automatically scoped to obj so that the <tt>this</tt> variable inside the
901 * callback points to obj. Example usage:
903 var sayHi = function(name){
904 // Note this use of "this.text" here. This function expects to
905 // execute within a scope that contains a text property. In this
906 // example, the "this" variable is pointing to the btn object that
907 // was passed in createDelegate below.
908 alert('Hi, ' + name + '. You clicked the "' + this.text + '" button.');
911 var btn = new Ext.Button({
913 renderTo: Ext.getBody()
916 // This callback will execute in the scope of the
917 // button instance. Clicking the button alerts
918 // "Hi, Fred. You clicked the "Say Hi" button."
919 btn.on('click', sayHi.createDelegate(btn, ['Fred']));
921 * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
922 * <b>If omitted, defaults to the browser window.</b>
923 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
924 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
925 * if a number the args are inserted at the specified position
926 * @return {Function} The new function
928 createDelegate : function(obj, args, appendArgs){
931 var callArgs = args || arguments;
932 if (appendArgs === true){
933 callArgs = Array.prototype.slice.call(arguments, 0);
934 callArgs = callArgs.concat(args);
935 }else if (Ext.isNumber(appendArgs)){
936 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
937 var applyArgs = [appendArgs, 0].concat(args); // create method call params
938 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
940 return method.apply(obj || window, callArgs);
945 * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
947 var sayHi = function(name){
948 alert('Hi, ' + name);
951 // executes immediately:
954 // executes after 2 seconds:
955 sayHi.defer(2000, this, ['Fred']);
957 // this syntax is sometimes useful for deferring
958 // execution of an anonymous function:
963 * @param {Number} millis The number of milliseconds for the setTimeout call (if less than or equal to 0 the function is executed immediately)
964 * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
965 * <b>If omitted, defaults to the browser window.</b>
966 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
967 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
968 * if a number the args are inserted at the specified position
969 * @return {Number} The timeout id that can be used with clearTimeout
971 defer : function(millis, obj, args, appendArgs){
972 var fn = this.createDelegate(obj, args, appendArgs);
974 return setTimeout(fn, millis);
983 * These functions are available on every String object.
985 Ext.applyIf(String, {
987 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
988 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
990 var cls = 'my-class', text = 'Some text';
991 var s = String.format('<div class="{0}">{1}</div>', cls, text);
992 // s now contains the string: '<div class="my-class">Some text</div>'
994 * @param {String} string The tokenized string to be formatted
995 * @param {String} value1 The value to replace token {0}
996 * @param {String} value2 Etc...
997 * @return {String} The formatted string
1000 format : function(format){
1001 var args = Ext.toArray(arguments, 1);
1002 return format.replace(/\{(\d+)\}/g, function(m, i){
1011 Ext.applyIf(Array.prototype, {
1013 * Checks whether or not the specified object exists in the array.
1014 * @param {Object} o The object to check for
1015 * @param {Number} from (Optional) The index at which to begin the search
1016 * @return {Number} The index of o in the array (or -1 if it is not found)
1018 indexOf : function(o, from){
1019 var len = this.length;
1021 from += (from < 0) ? len : 0;
1022 for (; from < len; ++from){
1023 if(this[from] === o){
1031 * Removes the specified object from the array. If the object is not found nothing happens.
1032 * @param {Object} o The object to remove
1033 * @return {Array} this array
1035 remove : function(o){
1036 var index = this.indexOf(o);
1038 this.splice(index, 1);
1047 Ext.ns("Ext.grid", "Ext.list", "Ext.dd", "Ext.tree", "Ext.form", "Ext.menu",
1048 "Ext.state", "Ext.layout", "Ext.app", "Ext.ux", "Ext.chart", "Ext.direct");
1050 * Namespace alloted for extensions to the framework.
1055 Ext.apply(Ext, function(){
1062 * A reusable empty function
1066 emptyFn : function(){},
1069 * URL to a 1x1 transparent gif image used by Ext to create inline icons with CSS background images.
1070 * In older versions of IE, this defaults to "http://extjs.com/s.gif" and you should change this to a URL on your server.
1071 * For other browsers it uses an inline data URL.
1074 BLANK_IMAGE_URL : Ext.isIE6 || Ext.isIE7 || Ext.isAir ?
1075 'http:/' + '/www.extjs.com/s.gif' :
1076 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
1078 extendX : function(supr, fn){
1079 return Ext.extend(supr, fn(supr.prototype));
1083 * Returns the current HTML document object as an {@link Ext.Element}.
1084 * @return Ext.Element The document
1086 getDoc : function(){
1087 return Ext.get(document);
1091 * Utility method for validating that a value is numeric, returning the specified default value if it is not.
1092 * @param {Mixed} value Should be a number, but any type will be handled appropriately
1093 * @param {Number} defaultValue The value to return if the original value is non-numeric
1094 * @return {Number} Value, if numeric, else defaultValue
1096 num : function(v, defaultValue){
1097 v = Number(Ext.isEmpty(v) || Ext.isArray(v) || typeof v == 'boolean' || (typeof v == 'string' && v.trim().length == 0) ? NaN : v);
1098 return isNaN(v) ? defaultValue : v;
1102 * <p>Utility method for returning a default value if the passed value is empty.</p>
1103 * <p>The value is deemed to be empty if it is<div class="mdetail-params"><ul>
1105 * <li>undefined</li>
1106 * <li>an empty array</li>
1107 * <li>a zero length string (Unless the <tt>allowBlank</tt> parameter is <tt>true</tt>)</li>
1109 * @param {Mixed} value The value to test
1110 * @param {Mixed} defaultValue The value to return if the original value is empty
1111 * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
1112 * @return {Mixed} value, if non-empty, else defaultValue
1114 value : function(v, defaultValue, allowBlank){
1115 return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
1119 * Escapes the passed string for use in a regular expression
1120 * @param {String} str
1123 escapeRe : function(s) {
1124 return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
1127 sequence : function(o, name, fn, scope){
1128 o[name] = o[name].createSequence(fn, scope);
1132 * Applies event listeners to elements by selectors when the document is ready.
1133 * The event name is specified with an <tt>@</tt> suffix.
1136 // add a listener for click on all anchors in element with id foo
1137 '#foo a@click' : function(e, t){
1141 // add the same listener to multiple selectors (separated by comma BEFORE the @)
1142 '#foo a, #bar span.some-class@mouseover' : function(){
1147 * @param {Object} obj The list of behaviors to apply
1149 addBehaviors : function(o){
1151 Ext.onReady(function(){
1152 Ext.addBehaviors(o);
1155 var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
1160 if ((parts = b.split('@'))[1]) { // for Object prototype breakers
1163 cache[s] = Ext.select(s);
1165 cache[s].on(parts[1], o[b]);
1173 * Utility method for getting the width of the browser scrollbar. This can differ depending on
1174 * operating system settings, such as the theme or font size.
1175 * @param {Boolean} force (optional) true to force a recalculation of the value.
1176 * @return {Number} The width of the scrollbar.
1178 getScrollBarWidth: function(force){
1183 if(force === true || scrollWidth === null){
1184 // Append our div, do our calculation and then remove it
1185 var div = Ext.getBody().createChild('<div class="x-hide-offsets" style="width:100px;height:50px;overflow:hidden;"><div style="height:200px;"></div></div>'),
1186 child = div.child('div', true);
1187 var w1 = child.offsetWidth;
1188 div.setStyle('overflow', (Ext.isWebKit || Ext.isGecko) ? 'auto' : 'scroll');
1189 var w2 = child.offsetWidth;
1191 // Need to add 2 to ensure we leave enough space
1192 scrollWidth = w1 - w2 + 2;
1199 combine : function(){
1200 var as = arguments, l = as.length, r = [];
1201 for(var i = 0; i < l; i++){
1205 }else if(a.length !== undefined && !a.substr){
1206 r = r.concat(Array.prototype.slice.call(a, 0));
1215 * Copies a set of named properties fom the source object to the destination object.
1216 * <p>example:<pre><code>
1217 ImageComponent = Ext.extend(Ext.BoxComponent, {
1218 initComponent: function() {
1219 this.autoEl = { tag: 'img' };
1220 MyComponent.superclass.initComponent.apply(this, arguments);
1221 this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
1225 * @param {Object} dest The destination object.
1226 * @param {Object} source The source object.
1227 * @param {Array/String} names Either an Array of property names, or a comma-delimited list
1228 * of property names to copy.
1229 * @return {Object} The modified object.
1231 copyTo : function(dest, source, names){
1232 if(typeof names == 'string'){
1233 names = names.split(/[,;\s]/);
1235 Ext.each(names, function(name){
1236 if(source.hasOwnProperty(name)){
1237 dest[name] = source[name];
1244 * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
1245 * DOM (if applicable) and calling their destroy functions (if available). This method is primarily
1246 * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
1247 * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be
1248 * passed into this function in a single call as separate arguments.
1249 * @param {Mixed} arg1 An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy
1250 * @param {Mixed} arg2 (optional)
1251 * @param {Mixed} etc... (optional)
1253 destroy : function(){
1254 Ext.each(arguments, function(arg){
1256 if(Ext.isArray(arg)){
1257 this.destroy.apply(this, arg);
1258 }else if(typeof arg.destroy == 'function'){
1268 * Attempts to destroy and then remove a set of named properties of the passed object.
1269 * @param {Object} o The object (most likely a Component) who's properties you wish to destroy.
1270 * @param {Mixed} arg1 The name of the property to destroy and remove from the object.
1271 * @param {Mixed} etc... More property names to destroy and remove.
1273 destroyMembers : function(o, arg1, arg2, etc){
1274 for(var i = 1, a = arguments, len = a.length; i < len; i++) {
1275 Ext.destroy(o[a[i]]);
1281 * Creates a copy of the passed Array with falsy values removed.
1282 * @param {Array/NodeList} arr The Array from which to remove falsy values.
1283 * @return {Array} The new, compressed Array.
1285 clean : function(arr){
1287 Ext.each(arr, function(v){
1296 * Creates a copy of the passed Array, filtered to contain only unique values.
1297 * @param {Array} arr The Array to filter
1298 * @return {Array} The new Array containing unique values.
1300 unique : function(arr){
1304 Ext.each(arr, function(v) {
1314 * Recursively flattens into 1-d Array. Injects Arrays inline.
1315 * @param {Array} arr The array to flatten
1316 * @return {Array} The new, flattened array.
1318 flatten : function(arr){
1320 function rFlatten(a) {
1321 Ext.each(a, function(v) {
1330 return rFlatten(arr);
1334 * Returns the minimum value in the Array.
1335 * @param {Array|NodeList} arr The Array from which to select the minimum value.
1336 * @param {Function} comp (optional) a function to perform the comparision which determines minimization.
1337 * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
1338 * @return {Object} The minimum value in the Array.
1340 min : function(arr, comp){
1342 comp = comp || function(a,b){ return a < b ? -1 : 1; };
1343 Ext.each(arr, function(v) {
1344 ret = comp(ret, v) == -1 ? ret : v;
1350 * Returns the maximum value in the Array
1351 * @param {Array|NodeList} arr The Array from which to select the maximum value.
1352 * @param {Function} comp (optional) a function to perform the comparision which determines maximization.
1353 * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
1354 * @return {Object} The maximum value in the Array.
1356 max : function(arr, comp){
1358 comp = comp || function(a,b){ return a > b ? 1 : -1; };
1359 Ext.each(arr, function(v) {
1360 ret = comp(ret, v) == 1 ? ret : v;
1366 * Calculates the mean of the Array
1367 * @param {Array} arr The Array to calculate the mean value of.
1368 * @return {Number} The mean.
1370 mean : function(arr){
1371 return arr.length > 0 ? Ext.sum(arr) / arr.length : undefined;
1375 * Calculates the sum of the Array
1376 * @param {Array} arr The Array to calculate the sum value of.
1377 * @return {Number} The sum.
1379 sum : function(arr){
1381 Ext.each(arr, function(v) {
1388 * Partitions the set into two sets: a true set and a false set.
1393 Ext.partition([true, false, true, true, false]); // [[true, true, true], [false, false]]
1399 return val.className == "class1"
1402 // true are those paragraph elements with a className of "class1",
1403 // false set are those that do not have that className.
1405 * @param {Array|NodeList} arr The array to partition
1406 * @param {Function} truth (optional) a function to determine truth. If this is omitted the element
1407 * itself must be able to be evaluated for its truthfulness.
1408 * @return {Array} [true<Array>,false<Array>]
1410 partition : function(arr, truth){
1412 Ext.each(arr, function(v, i, a) {
1413 ret[ (truth && truth(v, i, a)) || (!truth && v) ? 0 : 1].push(v);
1419 * Invokes a method on each item in an Array.
1422 Ext.invoke(Ext.query("p"), "getAttribute", "id");
1423 // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
1425 * @param {Array|NodeList} arr The Array of items to invoke the method on.
1426 * @param {String} methodName The method name to invoke.
1427 * @param {...*} args Arguments to send into the method invocation.
1428 * @return {Array} The results of invoking the method on each item in the array.
1430 invoke : function(arr, methodName){
1432 args = Array.prototype.slice.call(arguments, 2);
1433 Ext.each(arr, function(v,i) {
1434 if (v && typeof v[methodName] == 'function') {
1435 ret.push(v[methodName].apply(v, args));
1437 ret.push(undefined);
1444 * Plucks the value of a property from each item in the Array
1447 Ext.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
1449 * @param {Array|NodeList} arr The Array of items to pluck the value from.
1450 * @param {String} prop The property name to pluck from each element.
1451 * @return {Array} The value from each item in the Array.
1453 pluck : function(arr, prop){
1455 Ext.each(arr, function(v) {
1456 ret.push( v[prop] );
1462 * <p>Zips N sets together.</p>
1465 Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]]
1472 return "$" + a + "" + b + "." + c
1474 ); // ["$+12.43", "$-10.15", "$+22.96"]
1476 * @param {Arrays|NodeLists} arr This argument may be repeated. Array(s) to contribute values.
1477 * @param {Function} zipper (optional) The last item in the argument list. This will drive how the items are zipped together.
1478 * @return {Array} The zipped set.
1481 var parts = Ext.partition(arguments, function( val ){ return typeof val != 'function'; }),
1484 len = Ext.max(Ext.pluck(arrs, "length")),
1487 for (var i = 0; i < len; i++) {
1490 ret[i] = fn.apply(fn, Ext.pluck(arrs, i));
1492 for (var j = 0, aLen = arrs.length; j < aLen; j++){
1493 ret[i].push( arrs[j][i] );
1501 * This is shorthand reference to {@link Ext.ComponentMgr#get}.
1502 * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id}
1503 * @param {String} id The component {@link Ext.Component#id id}
1504 * @return Ext.Component The Component, <tt>undefined</tt> if not found, or <tt>null</tt> if a
1507 getCmp : function(id){
1508 return Ext.ComponentMgr.get(id);
1512 * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
1513 * you may want to set this to true.
1516 useShims: E.isIE6 || (E.isMac && E.isGecko2),
1518 // inpired by a similar function in mootools library
1520 * Returns the type of object that is passed in. If the object passed in is null or undefined it
1521 * return false otherwise it returns one of the following values:<div class="mdetail-params"><ul>
1522 * <li><b>string</b>: If the object passed is a string</li>
1523 * <li><b>number</b>: If the object passed is a number</li>
1524 * <li><b>boolean</b>: If the object passed is a boolean value</li>
1525 * <li><b>date</b>: If the object passed is a Date object</li>
1526 * <li><b>function</b>: If the object passed is a function reference</li>
1527 * <li><b>object</b>: If the object passed is an object</li>
1528 * <li><b>array</b>: If the object passed is an array</li>
1529 * <li><b>regexp</b>: If the object passed is a regular expression</li>
1530 * <li><b>element</b>: If the object passed is a DOM Element</li>
1531 * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
1532 * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
1533 * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
1535 * @param {Mixed} object
1539 if(o === undefined || o === null){
1546 if(t == 'object' && o.nodeName) {
1547 switch(o.nodeType) {
1548 case 1: return 'element';
1549 case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
1552 if(t == 'object' || t == 'function') {
1553 switch(o.constructor) {
1554 case Array: return 'array';
1555 case RegExp: return 'regexp';
1556 case Date: return 'date';
1558 if(typeof o.length == 'number' && typeof o.item == 'function') {
1565 intercept : function(o, name, fn, scope){
1566 o[name] = o[name].createInterceptor(fn, scope);
1570 callback : function(cb, scope, args, delay){
1571 if(typeof cb == 'function'){
1573 cb.defer(delay, scope, args || []);
1575 cb.apply(scope, args || []);
1584 * These functions are available on every Function object (any JavaScript function).
1586 Ext.apply(Function.prototype, {
1588 * Create a combined function call sequence of the original function + the passed function.
1589 * The resulting function returns the results of the original function.
1590 * The passed fcn is called with the parameters of the original function. Example usage:
1592 var sayHi = function(name){
1593 alert('Hi, ' + name);
1596 sayHi('Fred'); // alerts "Hi, Fred"
1598 var sayGoodbye = sayHi.createSequence(function(name){
1599 alert('Bye, ' + name);
1602 sayGoodbye('Fred'); // both alerts show
1604 * @param {Function} fcn The function to sequence
1605 * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed.
1606 * <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b>
1607 * @return {Function} The new function
1609 createSequence : function(fcn, scope){
1611 return (typeof fcn != 'function') ?
1614 var retval = method.apply(this || window, arguments);
1615 fcn.apply(scope || this || window, arguments);
1624 * These functions are available as static methods on the JavaScript String object.
1626 Ext.applyIf(String, {
1629 * Escapes the passed string for ' and \
1630 * @param {String} string The string to escape
1631 * @return {String} The escaped string
1634 escape : function(string) {
1635 return string.replace(/('|\\)/g, "\\$1");
1639 * Pads the left side of a string with a specified character. This is especially useful
1640 * for normalizing number and date strings. Example usage:
1642 var s = String.leftPad('123', 5, '0');
1643 // s now contains the string: '00123'
1645 * @param {String} string The original string
1646 * @param {Number} size The total length of the output string
1647 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
1648 * @return {String} The padded string
1651 leftPad : function (val, size, ch) {
1652 var result = String(val);
1656 while (result.length < size) {
1657 result = ch + result;
1664 * Utility function that allows you to easily switch a string between two alternating values. The passed value
1665 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
1666 * they are already different, the first value passed in is returned. Note that this method returns the new value
1667 * but does not change the current string.
1669 // alternate sort directions
1670 sort = sort.toggle('ASC', 'DESC');
1672 // instead of conditional logic:
1673 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
1675 * @param {String} value The value to compare to the current string
1676 * @param {String} other The new value to use if the string already equals the first value passed in
1677 * @return {String} The new value
1679 String.prototype.toggle = function(value, other){
1680 return this == value ? other : value;
1684 * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
1686 var s = ' foo bar ';
1687 alert('-' + s + '-'); //alerts "- foo bar -"
1688 alert('-' + s.trim() + '-'); //alerts "-foo bar-"
1690 * @return {String} The trimmed string
1692 String.prototype.trim = function(){
1693 var re = /^\s+|\s+$/g;
1694 return function(){ return this.replace(re, ""); };
1697 // here to prevent dependency on Date.js
1699 Returns the number of milliseconds between this date and date
1700 @param {Date} date (optional) Defaults to now
1701 @return {Number} The diff in milliseconds
1702 @member Date getElapsed
1704 Date.prototype.getElapsed = function(date) {
1705 return Math.abs((date || new Date()).getTime()-this.getTime());
1712 Ext.applyIf(Number.prototype, {
1714 * Checks whether or not the current number is within a desired range. If the number is already within the
1715 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
1716 * exceeded. Note that this method returns the constrained value but does not change the current number.
1717 * @param {Number} min The minimum number in the range
1718 * @param {Number} max The maximum number in the range
1719 * @return {Number} The constrained value if outside the range, otherwise the current value
1721 constrain : function(min, max){
1722 return Math.min(Math.max(this, min), max);
1726 * @class Ext.util.TaskRunner
1727 * Provides the ability to execute one or more arbitrary tasks in a multithreaded
1728 * manner. Generally, you can use the singleton {@link Ext.TaskMgr} instead, but
1729 * if needed, you can create separate instances of TaskRunner. Any number of
1730 * separate tasks can be started at any time and will run independently of each
1731 * other. Example usage:
1733 // Start a simple clock task that updates a div once per second
1734 var updateClock = function(){
1735 Ext.fly('clock').update(new Date().format('g:i:s A'));
1739 interval: 1000 //1 second
1741 var runner = new Ext.util.TaskRunner();
1744 // equivalent using TaskMgr
1751 * <p>See the {@link #start} method for details about how to configure a task object.</p>
1752 * Also see {@link Ext.util.DelayedTask}.
1755 * @param {Number} interval (optional) The minimum precision in milliseconds supported by this TaskRunner instance
1758 Ext.util.TaskRunner = function(interval){
1759 interval = interval || 10;
1766 stopThread = function(){
1773 startThread = function(){
1776 id = setInterval(runTasks, interval);
1781 removeTask = function(t){
1782 removeQueue.push(t);
1784 t.onStop.apply(t.scope || t);
1789 runTasks = function(){
1790 var rqLen = removeQueue.length,
1791 now = new Date().getTime();
1794 for(var i = 0; i < rqLen; i++){
1795 tasks.remove(removeQueue[i]);
1798 if(tasks.length < 1){
1803 for(var i = 0, t, itime, rt, len = tasks.length; i < len; ++i){
1805 itime = now - t.taskRunTime;
1806 if(t.interval <= itime){
1807 rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
1808 t.taskRunTime = now;
1809 if(rt === false || t.taskRunCount === t.repeat){
1814 if(t.duration && t.duration <= (now - t.taskStartTime)){
1821 * Starts a new task.
1823 * @param {Object} task <p>A config object that supports the following properties:<ul>
1824 * <li><code>run</code> : Function<div class="sub-desc"><p>The function to execute each time the task is invoked. The
1825 * function will be called at each interval and passed the <code>args</code> argument if specified, and the
1826 * current invocation count if not.</p>
1827 * <p>If a particular scope (<code>this</code> reference) is required, be sure to specify it using the <code>scope</code> argument.</p>
1828 * <p>Return <code>false</code> from this function to terminate the task.</p></div></li>
1829 * <li><code>interval</code> : Number<div class="sub-desc">The frequency in milliseconds with which the task
1830 * should be invoked.</div></li>
1831 * <li><code>args</code> : Array<div class="sub-desc">(optional) An array of arguments to be passed to the function
1832 * specified by <code>run</code>. If not specified, the current invocation count is passed.</div></li>
1833 * <li><code>scope</code> : Object<div class="sub-desc">(optional) The scope (<tt>this</tt> reference) in which to execute the
1834 * <code>run</code> function. Defaults to the task config object.</div></li>
1835 * <li><code>duration</code> : Number<div class="sub-desc">(optional) The length of time in milliseconds to invoke
1836 * the task before stopping automatically (defaults to indefinite).</div></li>
1837 * <li><code>repeat</code> : Number<div class="sub-desc">(optional) The number of times to invoke the task before
1838 * stopping automatically (defaults to indefinite).</div></li>
1840 * <p>Before each invocation, Ext injects the property <code>taskRunCount</code> into the task object so
1841 * that calculations based on the repeat count can be performed.</p>
1842 * @return {Object} The task
1844 this.start = function(task){
1846 task.taskStartTime = new Date().getTime();
1847 task.taskRunTime = 0;
1848 task.taskRunCount = 0;
1854 * Stops an existing running task.
1856 * @param {Object} task The task to stop
1857 * @return {Object} The task
1859 this.stop = function(task){
1865 * Stops all tasks that are currently running.
1868 this.stopAll = function(){
1870 for(var i = 0, len = tasks.length; i < len; i++){
1871 if(tasks[i].onStop){
1881 * @class Ext.TaskMgr
1882 * @extends Ext.util.TaskRunner
1883 * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop arbitrary tasks. See
1884 * {@link Ext.util.TaskRunner} for supported methods and task config properties.
1886 // Start a simple clock task that updates a div once per second
1889 Ext.fly('clock').update(new Date().format('g:i:s A'));
1891 interval: 1000 //1 second
1893 Ext.TaskMgr.start(task);
1895 * <p>See the {@link #start} method for details about how to configure a task object.</p>
1898 Ext.TaskMgr = new Ext.util.TaskRunner();(function(){
1901 version = Prototype.Version.split('.'),
1902 mouseEnterSupported = (parseInt(version[0]) >= 2) || (parseInt(version[1]) >= 7) || (parseInt(version[2]) >= 1),
1904 elContains = function(parent, child) {
1905 if(parent && parent.firstChild){
1907 if(child === parent) {
1910 child = child.parentNode;
1911 if(child && (child.nodeType != 1)) {
1918 checkRelatedTarget = function(e) {
1919 return !elContains(e.currentTarget, Ext.lib.Event.getRelatedTarget(e));
1923 getViewWidth : function(full){
1924 return full ? this.getDocumentWidth() : this.getViewportWidth();
1927 getViewHeight : function(full){
1928 return full ? this.getDocumentHeight() : this.getViewportHeight();
1931 getDocumentHeight: function() { // missing from prototype?
1932 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1933 return Math.max(scrollHeight, this.getViewportHeight());
1936 getDocumentWidth: function() { // missing from prototype?
1937 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1938 return Math.max(scrollWidth, this.getViewportWidth());
1941 getViewportHeight: function() { // missing from prototype?
1942 var height = self.innerHeight;
1943 var mode = document.compatMode;
1945 if ( (mode || Ext.isIE) && !Ext.isOpera ) {
1946 height = (mode == "CSS1Compat") ?
1947 document.documentElement.clientHeight : // Standards
1948 document.body.clientHeight; // Quirks
1954 getViewportWidth: function() { // missing from prototype?
1955 var width = self.innerWidth; // Safari
1956 var mode = document.compatMode;
1958 if (mode || Ext.isIE) { // IE, Gecko, Opera
1959 width = (mode == "CSS1Compat") ?
1960 document.documentElement.clientWidth : // Standards
1961 document.body.clientWidth; // Quirks
1966 isAncestor : function(p, c){ // missing from prototype?
1973 return p.contains(c);
1974 } else if (p.compareDocumentPosition) {
1975 return !!(p.compareDocumentPosition(c) & 16);
1977 while (c = c.parentNode) {
1978 ret = c == p || ret;
1985 getRegion : function(el){
1986 return Ext.lib.Region.getRegion(el);
1989 getY : function(el){
1990 return this.getXY(el)[1];
1993 getX : function(el){
1994 return this.getXY(el)[0];
1997 getXY : function(el){ // this initially used Position.cumulativeOffset but it is not accurate enough
1998 var p, pe, b, scroll, bd = (document.body || document.documentElement);
1999 el = Ext.getDom(el);
2005 if (el.getBoundingClientRect) {
2006 b = el.getBoundingClientRect();
2007 scroll = fly(document).getScroll();
2008 return [Math.round(b.left + scroll.left), Math.round(b.top + scroll.top)];
2014 var hasAbsolute = fly(el).getStyle("position") == "absolute";
2021 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
2028 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
2029 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
2036 if (p != el && pe.getStyle('overflow') != 'visible') {
2044 if (Ext.isSafari && hasAbsolute) {
2049 if (Ext.isGecko && !hasAbsolute) {
2051 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
2052 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
2056 while (p && p != bd) {
2057 if (!Ext.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
2066 setXY : function(el, xy){ // this initially used Position.cumulativeOffset but it is not accurate enough
2067 el = Ext.fly(el, '_setXY');
2069 var pts = el.translatePoints(xy);
2070 if(xy[0] !== false){
2071 el.dom.style.left = pts.left + "px";
2073 if(xy[1] !== false){
2074 el.dom.style.top = pts.top + "px";
2078 setX : function(el, x){
2079 this.setXY(el, [x, false]);
2082 setY : function(el, y){
2083 this.setXY(el, [false, y]);
2088 getPageX : function(e){
2089 return Event.pointerX(e.browserEvent || e);
2092 getPageY : function(e){
2093 return Event.pointerY(e.browserEvent || e);
2096 getXY : function(e){
2097 e = e.browserEvent || e;
2098 return [Event.pointerX(e), Event.pointerY(e)];
2101 getTarget : function(e){
2102 return Event.element(e.browserEvent || e);
2105 resolveTextNode: Ext.isGecko ? function(node){
2109 var s = HTMLElement.prototype.toString.call(node);
2110 if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]'){
2113 return node.nodeType == 3 ? node.parentNode : node;
2115 return node && node.nodeType == 3 ? node.parentNode : node;
2118 getRelatedTarget: function(ev) { // missing from prototype?
2119 ev = ev.browserEvent || ev;
2120 var t = ev.relatedTarget;
2122 if (ev.type == "mouseout") {
2124 } else if (ev.type == "mouseover") {
2129 return this.resolveTextNode(t);
2132 on : function(el, eventName, fn){
2133 if((eventName == 'mouseenter' || eventName == 'mouseleave') && !mouseEnterSupported){
2134 var item = mouseCache[el.id] || (mouseCache[el.id] = {});
2135 item[eventName] = fn;
2136 fn = fn.createInterceptor(checkRelatedTarget);
2137 eventName = (eventName == 'mouseenter') ? 'mouseover' : 'mouseout';
2139 Event.observe(el, eventName, fn, false);
2142 un : function(el, eventName, fn){
2143 if((eventName == 'mouseenter' || eventName == 'mouseleave') && !mouseEnterSupported){
2144 var item = mouseCache[el.id],
2145 ev = item && item[eventName];
2149 delete item[eventName];
2150 eventName = (eventName == 'mouseenter') ? 'mouseover' : 'mouseout';
2153 Event.stopObserving(el, eventName, fn, false);
2156 purgeElement : function(el){
2160 preventDefault : function(e){ // missing from prototype?
2161 e = e.browserEvent || e;
2162 if(e.preventDefault) {
2165 e.returnValue = false;
2169 stopPropagation : function(e){ // missing from prototype?
2170 e = e.browserEvent || e;
2171 if(e.stopPropagation) {
2172 e.stopPropagation();
2174 e.cancelBubble = true;
2178 stopEvent : function(e){
2179 Event.stop(e.browserEvent || e);
2182 onAvailable : function(id, fn, scope){ // no equiv
2183 var start = new Date(), iid;
2185 if(start.getElapsed() > 10000){
2188 var el = document.getElementById(id);
2191 fn.call(scope||window, el);
2194 iid = setInterval(f, 50);
2198 Ext.lib.Ajax = function(){
2199 var createSuccess = function(cb){
2200 return cb.success ? function(xhr){
2201 cb.success.call(cb.scope||window, createResponse(cb, xhr));
2204 var createFailure = function(cb){
2205 return cb.failure ? function(xhr){
2206 cb.failure.call(cb.scope||window, createResponse(cb, xhr));
2209 var createResponse = function(cb, xhr){
2216 headerStr = xhr.getAllResponseHeaders();
2217 Ext.each(headerStr.replace(/\r\n/g, '\n').split('\n'), function(v){
2220 s = v.substr(0, t).toLowerCase();
2221 if(v.charAt(t + 1) == ' '){
2224 headerObj[s] = v.substr(t + 1);
2230 responseText: xhr.responseText,
2231 responseXML : xhr.responseXML,
2232 argument: cb.argument,
2234 statusText: xhr.statusText,
2235 getResponseHeader : function(header){return headerObj[header.toLowerCase()];},
2236 getAllResponseHeaders : function(){return headerStr}
2240 request : function(method, uri, cb, data, options){
2243 parameters: data || '',
2244 timeout: cb.timeout,
2245 onSuccess: createSuccess(cb),
2246 onFailure: createFailure(cb)
2249 var hs = options.headers;
2251 o.requestHeaders = hs;
2253 if(options.xmlData){
2254 method = (method ? method : (options.method ? options.method : 'POST'));
2255 if (!hs || !hs['Content-Type']){
2256 o.contentType = 'text/xml';
2258 o.postBody = options.xmlData;
2259 delete o.parameters;
2261 if(options.jsonData){
2262 method = (method ? method : (options.method ? options.method : 'POST'));
2263 if (!hs || !hs['Content-Type']){
2264 o.contentType = 'application/json';
2266 o.postBody = typeof options.jsonData == 'object' ? Ext.encode(options.jsonData) : options.jsonData;
2267 delete o.parameters;
2270 new Ajax.Request(uri, o);
2273 formRequest : function(form, uri, cb, data, isUpload, sslUri){
2274 new Ajax.Request(uri, {
2275 method: Ext.getDom(form).method ||'POST',
2276 parameters: Form.serialize(form)+(data?'&'+data:''),
2277 timeout: cb.timeout,
2278 onSuccess: createSuccess(cb),
2279 onFailure: createFailure(cb)
2283 isCallInProgress : function(trans){
2287 abort : function(trans){
2291 serializeForm : function(form){
2292 return Form.serialize(form.dom||form);
2298 Ext.lib.Anim = function(){
2301 easeOut: function(pos) {
2302 return 1-Math.pow(1-pos,2);
2304 easeIn: function(pos) {
2305 return 1-Math.pow(1-pos,2);
2308 var createAnim = function(cb, scope){
2310 stop : function(skipToLast){
2311 this.effect.cancel();
2314 isAnimated : function(){
2315 return this.effect.state == 'running';
2318 proxyCallback : function(){
2319 Ext.callback(cb, scope);
2324 scroll : function(el, args, duration, easing, cb, scope){
2325 // not supported so scroll immediately?
2326 var anim = createAnim(cb, scope);
2327 el = Ext.getDom(el);
2328 if(typeof args.scroll.to[0] == 'number'){
2329 el.scrollLeft = args.scroll.to[0];
2331 if(typeof args.scroll.to[1] == 'number'){
2332 el.scrollTop = args.scroll.to[1];
2334 anim.proxyCallback();
2338 motion : function(el, args, duration, easing, cb, scope){
2339 return this.run(el, args, duration, easing, cb, scope);
2342 color : function(el, args, duration, easing, cb, scope){
2343 return this.run(el, args, duration, easing, cb, scope);
2346 run : function(el, args, duration, easing, cb, scope, type){
2349 switch(k){ // scriptaculous doesn't support, so convert these
2351 var by, pts, e = Ext.fly(el, '_animrun');
2353 if(by = args.points.by){
2355 pts = e.translatePoints([xy[0]+by[0], xy[1]+by[1]]);
2357 pts = e.translatePoints(args.points.to);
2359 o.left = pts.left+'px';
2360 o.top = pts.top+'px';
2363 o.width = args.width.to+'px';
2366 o.height = args.height.to+'px';
2369 o.opacity = String(args.opacity.to);
2372 o[k] = String(args[k].to);
2376 var anim = createAnim(cb, scope);
2377 anim.effect = new Effect.Morph(Ext.id(el), {
2379 afterFinish: anim.proxyCallback,
2380 transition: easings[easing] || Effect.Transitions.linear,
2389 // all lib flyweight calls use their own flyweight to prevent collisions with developer flyweights
2392 libFlyweight = new Ext.Element.Flyweight();
2394 libFlyweight.dom = el;
2395 return libFlyweight;
2398 Ext.lib.Region = function(t, r, b, l) {
2407 Ext.lib.Region.prototype = {
2408 contains : function(region) {
2409 return ( region.left >= this.left &&
2410 region.right <= this.right &&
2411 region.top >= this.top &&
2412 region.bottom <= this.bottom );
2416 getArea : function() {
2417 return ( (this.bottom - this.top) * (this.right - this.left) );
2420 intersect : function(region) {
2421 var t = Math.max( this.top, region.top );
2422 var r = Math.min( this.right, region.right );
2423 var b = Math.min( this.bottom, region.bottom );
2424 var l = Math.max( this.left, region.left );
2426 if (b >= t && r >= l) {
2427 return new Ext.lib.Region(t, r, b, l);
2432 union : function(region) {
2433 var t = Math.min( this.top, region.top );
2434 var r = Math.max( this.right, region.right );
2435 var b = Math.max( this.bottom, region.bottom );
2436 var l = Math.min( this.left, region.left );
2438 return new Ext.lib.Region(t, r, b, l);
2441 constrainTo : function(r) {
2442 this.top = this.top.constrain(r.top, r.bottom);
2443 this.bottom = this.bottom.constrain(r.top, r.bottom);
2444 this.left = this.left.constrain(r.left, r.right);
2445 this.right = this.right.constrain(r.left, r.right);
2449 adjust : function(t, l, b, r){
2458 Ext.lib.Region.getRegion = function(el) {
2459 var p = Ext.lib.Dom.getXY(el);
2462 var r = p[0] + el.offsetWidth;
2463 var b = p[1] + el.offsetHeight;
2466 return new Ext.lib.Region(t, r, b, l);
2469 Ext.lib.Point = function(x, y) {
2470 if (Ext.isArray(x)) {
2474 this.x = this.right = this.left = this[0] = x;
2475 this.y = this.top = this.bottom = this[1] = y;
2478 Ext.lib.Point.prototype = new Ext.lib.Region();
2483 function fnCleanUp() {
2484 var p = Function.prototype;
2485 delete p.createSequence;
2487 delete p.createDelegate;
2488 delete p.createCallback;
2489 delete p.createInterceptor;
2491 window.detachEvent("onunload", fnCleanUp);
2493 window.attachEvent("onunload", fnCleanUp);